@idosgames/core 0.22.1 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/{VoiceController-ClFmHUGH.d.cts → VoiceController-BOiBH9Jd.d.cts} +34 -3
- package/dist/{VoiceController-JKfvxpjs.d.ts → VoiceController-Cx6eziQG.d.ts} +34 -3
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/realtime/index.d.cts +2 -2
- package/dist/realtime/index.d.ts +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),jt=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var jt__default=/*#__PURE__*/_interopDefault(jt);var Pi=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,s=>{i(),t(s);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let s of [...i])s(t);}removeAllListeners(){this.listeners.clear();}};function Mm(){let r=new Map;return {get:e=>r.get(e)??null,set:(e,t)=>{r.set(e,t);},remove:e=>{r.delete(e);}}}function Za(){return Om()??Mm()}function Om(){try{let r=globalThis.localStorage;if(!r)return null;let e="__idos_probe__";return r.setItem(e,"1"),r.removeItem(e),{get:t=>{try{return r.getItem(t)}catch{return null}},set:(t,i)=>{try{r.setItem(t,i);}catch{try{r.removeItem(t);}catch{}}},remove:t=>{try{r.removeItem(t);}catch{}}}}catch{return null}}var Ya="https://api.idosgames.com";function Xa(r){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??Ya).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??Za(),locale:r.locale??Um(),appVersion:r.appVersion??""}}function Um(){try{return globalThis.navigator?.language??""}catch{return ""}}var ii=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},si=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,t){this.map.set(e,t);}remove(e){this.map.delete(e);}};function ni(){return globalThis.Telegram?.WebApp??null}function B(){return crypto.randomUUID()}var el="idos_device_id",ri=class{storage;constructor(e=new ii){this.storage=e;}getPlatform(){return ni()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=ni()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=ni()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(el);return e||(e=B(),this.storage.setString(el,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=ni();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=ni();if(t?.openInvoice){t.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let t=globalThis;typeof t.showAd=="function"&&await t.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var Jr="idos_acq",tl=["gclid","fbclid","ttclid","msclkid","yclid"],Em=["ref","r"],qm=["ref_","ref-","ref=","r_","r-"];var _t=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();Lm(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=Fm(this.platform.getDeviceModel());return s&&(i.OsVersion=s),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(Jr);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let i=nl(sl(t));if(i)return i}return Vi(t)}readFromEnvironment(){let e={},t=sl(this.platform.getFullURL());Vt(e,"UtmSource",t.get("utm_source")),Vt(e,"UtmMedium",t.get("utm_medium")),Vt(e,"UtmCampaign",t.get("utm_campaign")),Vt(e,"UtmTerm",t.get("utm_term")),Vt(e,"UtmContent",t.get("utm_content")),Vt(e,"ClaimToken",t.get("idos_click"));for(let R of tl){let V=t.get(R);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",s=Gm(i);if(s){for(let R of Bm)Vt(e,R,s.get(rl[R])??null);for(let R of tl){let V=s.get(R);if(V){e.ClickID=V;break}}}let n=Vi(s?s.get("ref")??s.get("r")??"":i),o=nl(t),p=n||o;p&&(e.ReferralCode=p,e.ChannelHint=n?"telegram":"query");let d=this.platform.getReferrer?.();return d&&(e.Referrer=d),e}read(){try{let e=this.platform.storage.getString(Jr);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.platform.storage.setString(Jr,JSON.stringify(e));}catch{}}};function Lm(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function Vt(r,e,t){t&&(r[e]=t);}var il="a1_",rl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Bm=Object.keys(rl);function Gm(r){let e=(r||"").trim();if(!e.startsWith(il))return null;let t=e.slice(il.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,d=>d.charCodeAt(0)),o=new TextDecoder().decode(n),p=new URLSearchParams(o);return [...p.keys()].length>0?p:null}catch{return null}}function sl(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function nl(r){for(let e of Em){let t=r.get(e);if(t)return Vi(t)}return null}function Vi(r){let e=(r||"").trim();if(!e)return null;for(let t of qm)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Fm(r){let e=r||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var ol="idos_usage_pending",al="idos_usage_session",ll="idos_usage_closed_session",ul="idos_usage_new_session",cl="idos_usage_last_activity",Ii=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=typeof document<"u"&&document.visibilityState==="hidden",this.timer=setInterval(()=>this.tick(),200*1e3),window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();}};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,i=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,i,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(ol),this.currentSessionSeconds=this.readNumber(al),this.pendingClosedSessionSeconds=this.readNumber(ll),this.isNewSessionPending=this.readNumber(ul)!==0;let e=this.readNumber(cl);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(ol,this.pendingSeconds),this.writeNumber(al,this.currentSessionSeconds),this.writeNumber(ll,this.pendingClosedSessionSeconds),this.writeNumber(ul,this.isNewSessionPending?1:0),this.writeNumber(cl,Date.now());}readNumber(e){let t=this.ctx.platform.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.platform.storage.setString(e,String(Math.floor(t)));}catch{}}};var ut={Virtual:"Virtual",Crypto:"Crypto"},ai=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),_i={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase"},li=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase"]).catch("Item"),mt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Ni=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),Vm={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},ji=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),_m={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Wi=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Nm={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},vi=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),we={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function hl(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return pl(e);let t=r.cordova?.platformId;return t?pl(t):r.navigator?.userAgent??""?mt.Web:mt.Unknown}function pl(r){let e=r.toLowerCase();return e==="android"?mt.Android:e==="ios"?mt.Ios:e==="web"?mt.Web:mt.Unknown}function F(r){return {ok:true,data:r}}function u(r,e){return {ok:false,reason:r,error:e}}var a=u("unauthorized","Not logged in.");function jm(r){return r.ok}function Wm(r){return !r.ok}var j=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="string"?Number(r):r;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(r)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="number"?String(r):r.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(r)}`}),zod.z.NEVER):t}),c=zod.z.string();var Zr=zod.z.object({Type:li.nullish(),CurrencyID:zod.z.string().nullish(),Amount:j.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),Km=zod.z.object({Type:Wi.nullish(),EntityID:zod.z.string()}),Qm=zod.z.object({Address:Km.nullish(),Amount:j.nullish(),Source:zod.z.string().nullish()}),ce=zod.z.object({Entries:zod.z.array(Zr).nullish(),EventTokens:zod.z.array(Qm).nullish()}),dl=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:ce.nullish()}),H=zod.z.object({Standard:ce.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(dl).nullish()}),xt=zod.z.object({Standard:ce.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(dl).nullish()}),M=zod.z.object({Grant:H.nullish(),Consume:xt.nullish()}),bt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:ce.nullish()});var Hm=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),$m={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Jm=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),Z=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:Hm.nullish(),Tutorial:Jm.nullish(),Platforms:zod.z.array(Ni).nullish()}).passthrough();var Re=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var Zm=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Ym=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Xm=zod.z.object({AnchorUtc:zod.z.string().nullish(),MaxCycles:zod.z.number().nullish(),PauseBetweenPhasesSec:zod.z.number().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish()}).passthrough();zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();var ef=zod.z.object({Reset:zod.z.string().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:zod.z.string().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();zod.z.object({SourceType:zod.z.string().nullish(),TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var st=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:Re.nullish()}).passthrough(),ge=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:Ym.nullish(),Chain:Xm.nullish(),Cyclic:ef.nullish(),ActivationTriggers:zod.z.array(st).nullish(),Relative:Zm.nullish()}).passthrough();var tf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},sf=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),nf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},rf=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),of=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Fe=zod.z.object({Base:zod.z.number().nullish(),Shape:sf.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(of).nullish(),Interpolation:rf.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var af=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:H.nullish()}).passthrough(),lf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),Yr=zod.z.object({Bundles:zod.z.array(af).nullish(),Multipliers:zod.z.array(lf).nullish()}).passthrough();var uf=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Ki=zod.z.object({Source:uf.nullish(),SourceKey:zod.z.string().nullish(),Curve:Fe.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:ce.nullish(),ExcludeRewards:ce.nullish()}).passthrough(),ml=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),Le=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:Yr.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),ui=zod.z.object({Milestones:zod.z.record(zod.z.string(),Le).nullish()}).passthrough();var K=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var cf=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Nt=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxBalance:zod.z.number().nullish(),MaxPerGrant:zod.z.number().nullish(),DailyEarnCap:zod.z.number().nullish(),BurnOnEventEnd:zod.z.boolean().nullish(),BurnConversion:cf.nullish()}).passthrough();var pf=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),fl=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:pf.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Q=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),fl).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var ve=r=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:r.nullish()}),ft=r=>zod.z.object({ServerTimeUtc:c,Items:zod.z.array(ve(r)),Resources:M.nullish(),Inventory:Q.nullish()});var hf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},gl=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),df=zod.z.object({}).passthrough().transform(r=>r),mf=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:c.nullish(),CycleEndUtc:c.nullish(),PointsTotalEarned:j.nullish(),PointsCurrent:j.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:Le.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Xr=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:j.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:gl}),yl=zod.z.object({State:df.nullish(),PointsTracks:zod.z.record(zod.z.string(),mf).nullish()}),eo=zod.z.object({ServerTimeUtc:c,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:gl.nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),to=zod.z.object({ServerTimeUtc:c,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:j.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),NextMilestone:Le.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Rl=zod.z.object({ServerTimeUtc:c,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Cl=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(Xr).nullish()}),Sl=zod.z.array(ve(eo)),xl=zod.z.array(ve(to)),ff={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},gf=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),yf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Rf=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),bl=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:gf.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(st).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),io=zod.z.object({Milestones:K.nullish(),Linking:K.nullish(),Availability:K.nullish(),Reward:K.nullish(),Objectives:K.nullish()}).passthrough(),Cf=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Dl=zod.z.object({CycleIDs:zod.z.array(zod.z.string()).nullish(),GroupID:zod.z.string().nullish(),PhaseIDs:zod.z.array(zod.z.string()).nullish(),RequiredQuestIDs:zod.z.array(zod.z.string()).nullish(),PrerequisiteMode:Rf.nullish()}).passthrough(),Pl=zod.z.object({Schedule:ge.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Il=zod.z.object({Grant:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Sf=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Cf.nullish(),Linking:Dl.nullish(),Availability:Pl.nullish(),Objectives:zod.z.record(zod.z.string(),bl).nullish(),Reward:Il.nullish(),Presets:io.nullish()}).passthrough(),xf=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),bf=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:Z.nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),Presets:io.nullish(),PointsToken:Nt.nullish()}).passthrough(),Df=zod.z.object({Milestones:zod.z.record(zod.z.string(),ui).nullish(),Linking:zod.z.record(zod.z.string(),Dl).nullish(),Availability:zod.z.record(zod.z.string(),Pl).nullish(),Reward:zod.z.record(zod.z.string(),Il).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),bl)).nullish()}).passthrough(),Pf=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ge.nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),Gate:Z.nullish(),PointsToken:Nt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),xf).nullish(),Phases:zod.z.record(zod.z.string(),bf).nullish(),Presets:io.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Hi=zod.z.object({Cycles:zod.z.record(zod.z.string(),Pf).nullish(),Quests:zod.z.record(zod.z.string(),Sf).nullish(),Presets:Df.nullish()}).passthrough(),pt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var If={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},vf=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Tf={Never:"Never",OnRequest:"OnRequest",Always:"Always"},Af=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),kf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},zf=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),wf={GameLoop:"GameLoop"},Mf={Raid:"Raid",Attack:"Attack"},Of=zod.z.object({Title:zod.z.string().nullish(),TitleKey:zod.z.string().nullish(),Body:zod.z.string().nullish(),BodyKey:zod.z.string().nullish(),AnchorID:zod.z.string().nullish(),HighlightTarget:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),UiHint:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Uf=zod.z.object({Mode:vf.nullish(),Triggers:zod.z.array(st).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),Ef=zod.z.object({Grant:H.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),qf=zod.z.object({TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),RandomActionType:zod.z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),Lf=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:qf.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),Bf=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),so=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:Of.nullish(),Completion:Uf.nullish(),Effects:Ef.nullish(),Script:Lf.nullish(),Policy:Bf.nullish()}).passthrough(),Gf=zod.z.object({DisplayName:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),Description:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),vl=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:st.nullish()}).passthrough(),Tl=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:Af.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Al=zod.z.object({Grant:H.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),Ff=zod.z.object({Availability:K.nullish(),Policy:K.nullish(),Reward:K.nullish(),Steps:K.nullish()}).passthrough(),Vf=zod.z.object({FlowID:zod.z.string().nullish(),Identity:Gf.nullish(),Availability:vl.nullish(),Policy:Tl.nullish(),Steps:zod.z.record(zod.z.string(),so).nullish(),Reward:Al.nullish(),Presets:Ff.nullish()}).passthrough(),_f=zod.z.object({BlockingFlowIDs:zod.z.array(zod.z.string()).nullish(),BlockedModules:zod.z.array(zod.z.string()).nullish(),BlockedActions:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),BlockBeforeStart:zod.z.boolean().nullish(),SkipLiftsBlock:zod.z.boolean().nullish()}).passthrough(),Nf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:_f.nullish()}).passthrough(),jf=zod.z.object({Availability:zod.z.record(zod.z.string(),vl).nullish(),Policy:zod.z.record(zod.z.string(),Tl).nullish(),Reward:zod.z.record(zod.z.string(),Al).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),so)).nullish()}).passthrough(),kl=zod.z.object({Flows:zod.z.record(zod.z.string(),Vf).nullish(),Settings:Nf.nullish(),Presets:jf.nullish()}).passthrough(),Wf=zod.z.object({}).passthrough().transform(r=>r),zl=zod.z.object({FlowID:zod.z.string(),Status:zf,CurrentStepID:zod.z.string().nullish(),CurrentStep:so.nullish(),TotalSteps:zod.z.number(),CompletedSteps:zod.z.number(),CanSkip:zod.z.boolean(),RewardClaimed:zod.z.boolean(),RewardPending:zod.z.boolean(),VariantID:zod.z.string().nullish()}).passthrough(),$i=zod.z.object({State:Wf.nullish(),Flows:zod.z.array(zl).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),wt=zod.z.object({Flow:zl.nullish()}).passthrough(),wl=zod.z.object({FlowID:zod.z.string().nullish(),Granted:M.nullish()}).passthrough(),Ml=zod.z.array(ve(wt)),Ol=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),nt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Ji(r){return Array.isArray(r)?r.filter(e=>e!==null).map(Ji):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,Ji(t)])):r}var Zi=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var Yi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Ul(r){return r===429||r>=500&&r<=599}function Xi(r,e=Math.random){let t=Math.min(500*Math.pow(2,r-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Mt(r){return new Promise(e=>setTimeout(e,r))}var El=15e3;async function ql(r){try{let t=JSON.parse(await r.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(r.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Ll(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function Bl(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var no=15,Gl=1e3,es=class{constructor(e=no,t=()=>Date.now(),i=Mt){this.perSecond=e;this.now=t;this.wait=i;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=Gl;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Gl-(e-this.starts[0])+5);}}};var Kf=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function pi(r){if(!r)return null;let e=Kf.exec(r);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new jt__default.default(i),o=new jt__default.default(s),p=o.minus(jt__default.default.max(n,0));return p.lte(0)?null:{currencyID:t,required:o.toNumber(),available:n.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var Qf=12e3,Hf=new Set(["RelatedEntityID"]);function $f(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[i,s]of Object.entries(e))Hf.has(i)||(t[i]=s);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var Jf=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(Xr).nullish(),TutorialProgress:zod.z.array(Ol).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),ts=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Yi;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new Zi(e.throttleMs),this.pacer=new es(e.maxRequestsPerSecond??no),this.clientPlatform=e.clientPlatform??mt.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,s={}){let n=s.throttleKey??$f(e,t);if(!this.throttler.tryAcquire(n))return u("throttled","Throttled");if(!this.inflight.add(n))return u("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,p=JSON.stringify(t),d=s.ticket??null,R=s.silent??!1,V=s.timeoutMs??Qf,re=s.autoRetry??!0,Se=!1,ae=!1,me=0;for(;;){let St;s.keepalive||await this.pacer.take();try{St=await this.doFetch(o,p,d,V,s.keepalive??!1);}catch{if(re&&me<3){me++,await Mt(Xi(me));continue}return this.connectionFailure("Internet Connection Error",R)}let Je=St.status;if(Je>=200&&Je<300){let ne=!ae&&this.cryptoTopUpHandler!==null,Ie=await this.parseSuccess(St,i,R,e,ne);if(!Ie.ok&&ne){let pe=pi(Ie.error);if(pe){if(ae=!0,await this.runTopUp(pe))continue;R||this.emitter.emit("error:global",Ie.error);}}return Ie}if(Je===401){if(!Se&&this.sessionRefreshHandler){Se=!0;let ne=null;try{ne=await this.sessionRefreshHandler();}catch{ne=null;}if(ne){d=ne;continue}}return this.emitter.emit("auth:unauthorized",void 0),u("unauthorized","Unauthorized")}if(Ul(Je)){let ne=Je===429?await ql(St):null;if(ne!==null&&ne>El)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ne/1e3)} s`,R);if(re&&me<3){me++,await Mt(ne!==null?Ll(ne):Je===429?Bl(me):Xi(me));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Je})`,R)}let bi="";try{bi=await St.text();}catch{}if(Je===409&&/operation in progress/i.test(bi)&&re&&me<3){me++,await Mt(Xi(me));continue}return this.handleWebError(bi,Je,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let o=new AbortController,p=setTimeout(()=>{o.abort();},s);try{let d={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(d.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:d,signal:o.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,i,s,n=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",i)}let p;try{p=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",i)}let d=Jf.safeParse(p);if(!d.success)return this.globalError("Malformed response envelope",i);if(!d.data.Success){let ae=d.data.Error??"Server returned Success=false",me=n&&pi(ae);return !i&&!me&&this.emitter.emit("error:global",ae),u("server",ae)}let R=d.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:d.data.StateEpoch??null,versions:R});let V=d.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let re=d.data.TutorialProgress;re&&re.length>0&&this.emitter.emit("tutorial:systemProgress",re);let Se=t.safeParse(d.data.Data);if(!Se.success){let ae=t.safeParse(Ji(d.data.Data));ae.success&&(Se=ae);}if(!Se.success){let ae=`Validation error (${s}): ${Se.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",ae),i||this.emitter.emit("error:global",ae),u("validation",ae)}return F(Se.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),u("server","PLAY_ACCESS_REQUIRED");s=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),u("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),u("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),u("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function hi(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function Ti(r){return `${hi(r)}T00:00:00.000Z`}function Fl(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Vl(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function ao(r,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;r.InventoryV2??={};let n=r.InventoryV2,o=i.toISOString(),p=new Map,d=new Map,R=new Map,V=new Map,re=new Map,Se=new Map,ae=new Map,me=new Map,St=e.Grant?.PremiumTiers??[],Je=St.length;for(let ne=0;;ne++){let Ie,pe;if(ne===0)Ie=e.Grant?.Standard?.Entries,pe=false;else if(ne-1<Je)Ie=St[ne-1]?.Resources?.Entries,pe=false;else if(ne===1+Je)Ie=e.Consume?.Standard?.Entries,pe=true;else break;if(Ie)for(let le of Ie){if(le.Type==null)continue;let he=Math.max(0,le.Amount??0);if(!(he<=0))switch(le.Type){case "VirtualCurrency":{if(!le.CurrencyID)continue;let de=pe?d:p;de.set(le.CurrencyID,(de.get(le.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!le.CurrencyID)continue;let de=pe?V:R;de.set(le.CurrencyID,(de.get(le.CurrencyID)??new jt__default.default(0)).plus(he));break}case "Item":{if(!le.ItemID)continue;let de=Yf(t,le.CatalogID,le.ItemID),be=(de?de.IsStackable??true:true)?pe?Se:re:pe?me:ae;be.set(le.ItemID,(be.get(le.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||d.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let ne of new Set([...p.keys(),...d.keys()])){let Ie=p.get(ne)??0,pe=d.get(ne)??0,le=Ie-pe,he=n.VirtualCurrencies[ne];he?(he.Amount+=le,he.UpdatedAt=o,he.Daily&&hi(he.Daily.PeriodStartUtc)===hi(i)?(he.Daily.Earned+=Ie,he.Daily.Spent+=pe):he.Daily={PeriodStartUtc:Ti(i),Earned:Ie,Spent:pe}):n.VirtualCurrencies[ne]={Amount:le,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Ti(i),Earned:Ie,Spent:pe}};}}if(s.ccChanged=R.size>0||V.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let ne of new Set([...R.keys(),...V.keys()])){let Ie=R.get(ne)??new jt__default.default(0),pe=V.get(ne)??new jt__default.default(0),le=Ie.minus(pe),he=n.CryptoCurrencies[ne];he?(he.Amount=new jt__default.default(he.Amount).plus(le).toString(),he.UpdatedAt=o):n.CryptoCurrencies[ne]={Amount:le.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(s.itemsChanged=re.size>0||Se.size>0||ae.size>0||me.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let ne=n.UnstackableItems,Ie=new Set([...re.keys(),...Se.keys(),...ae.keys(),...me.keys()]);for(let pe of Ie){let le=(re.get(pe)??0)-(Se.get(pe)??0),he=(ae.get(pe)??0)-(me.get(pe)??0),de=le+he,it=n.Items[pe];it?(le!==0&&(it.StackableAmount+=le),he!==0&&(it.UnstackableAmount+=he),de!==0&&(it.TotalAmount+=de)):n.Items[pe]={StackableAmount:Math.max(0,le),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,de)};}for(let[pe,le]of me){if(le<=0)continue;let he=Object.values(ne).filter(de=>de.ItemID===pe&&de.EquippedSlot==null&&(de.ExpiresAt==null||new Date(de.ExpiresAt)>i)).sort(Zf).slice(0,le).map(de=>de.ItemInstanceID);for(let de of he)delete ne[de];}for(let[pe,le]of ae){let he=Xf(t,pe);for(let de=0;de<le;de++){let it=B();ne[it]={ItemInstanceID:it,ItemID:pe,CatalogID:he,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let bi=r.EventToken;for(let ne=0;;ne++){let Ie,pe;if(ne===0)Ie=e.Grant?.Standard?.EventTokens,pe=false;else if(ne-1<Je)Ie=St[ne-1]?.Resources?.EventTokens,pe=false;else if(ne===1+Je)Ie=e.Consume?.Standard?.EventTokens,pe=true;else break;if(!(!Ie||Ie.length===0))for(let le of Ie){let he=le.Address;if(!he||he.Type==null)continue;let de=le.Amount??0;if(de<=0)continue;let it=eg(bi,he.Type);if(!it)continue;let be=it[he.EntityID];be||(be={},it[he.EntityID]=be),be.Balance??={Current:0,TotalEarned:0,TotalSpent:0},be.Daily??={Date:Ti(i),TotalEarned:0},be.Meta??={};let Di=le.Source&&le.Source.length>0?le.Source:"CustomAction";pe?(be.Balance.Current-=de,be.Balance.TotalSpent+=de):(be.Balance.Current+=de,be.Balance.TotalEarned+=de,hi(be.Daily.Date)!==hi(i)&&(be.Daily={Date:Ti(i),TotalEarned:0}),be.Daily.TotalEarned+=de,be.Daily.EarnedBySource??={},be.Daily.EarnedBySource[Di]=(be.Daily.EarnedBySource[Di]??0)+de,be.Daily.TriggersBySource??={},be.Daily.TriggersBySource[Di]=(be.Daily.TriggersBySource[Di]??0)+1,be.Daily.LastTriggerBySource??={},be.Daily.LastTriggerBySource[Di]=o,be.Meta.JoinedAtUtc||(be.Meta.JoinedAtUtc=o),be.Meta.LastEarnedAtUtc=o),s.tokensChanged=true;}}return s}function Zf(r,e){return r.AcquiredAt!==e.AcquiredAt?r.AcquiredAt<e.AcquiredAt?-1:1:r.ItemInstanceID===e.ItemInstanceID?0:r.ItemInstanceID<e.ItemInstanceID?-1:1}function Yf(r,e,t){let i=r?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function Xf(r,e){let t=r?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function eg(r,e){switch(e){case "TimedEvent":return r.TimedEvent??={};case "Quest":return r.Quest??={};case "Leaderboard":return r.Leaderboard??={};case "CoopEvent":return r.CoopEvent??={};case "Season":return r.Season??={};default:return null}}function _l(r,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let d of Object.values(s))d?.ItemID&&o.add(d.ItemID);for(let d of n){let R=r[d]?.ItemID;R&&o.add(R);}if(o.size===0)return i;let p=d=>n.has(d)||d in s;if(e){for(let[d,R]of Object.entries(e))d in r||p(d)||R&&o.has(R.ItemID)&&i.drop.push(d);for(let[d,R]of Object.entries(r))d in e||p(d)||R&&o.has(R.ItemID)&&(i.restore[d]=R);}return i}function lo(r,e){return r===e||r.startsWith(`${e}:`)}var ss=class r{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){r.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];r.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){r.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=ao(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,o={...n.InventoryV2?.UnstackableItems??{}},p=ao(n,e,i,s),d=_l(o,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],re=d.drop.length>0||Object.keys(d.restore).length>0||R.length>0||V.length>0;if(re){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let Se=n.InventoryV2.UnstackableItems;for(let ae of d.drop)delete Se[ae];for(let[ae,me]of Object.entries(d.restore))Se[ae]=me;for(let[ae,me]of R)Se[ae]=me;for(let ae of V)delete Se[ae];}this.emitResourceChanges(p,re);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof jt__default.default?t:new jt__default.default(t),p=s===void 0?new jt__default.default(0):s instanceof jt__default.default?s:new jt__default.default(s),d=i??new Date().toISOString(),R=n[e];R?(R.Amount=new jt__default.default(R.Amount).plus(o).toString(),p.isZero()||(R.Frozen=new jt__default.default(R.Frozen??0).plus(p).toString()),R.UpdatedAt=d):n[e]={Amount:o.toString(),Frozen:p.toString(),CreatedAt:d,UpdatedAt:d},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=Fl(i)):n.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let o of t)o.RuleID&&(s.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let o=n.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(lo(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((s?n!==s:!lo(n,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let o of n)o.Type!==e||o.TimedEventID!==t||s&&o.TokenEntityID&&o.TokenEntityID!==s||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let s=false;for(let n of Object.values(i))for(let o of Object.values(n.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,p={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")o.Private??={},o.Private[t]=p;else if(e==="Public")o.Public??={},o.Public[t]=p;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!n.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var ns=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var rs=class{user;config;constructor(e){this.user=new ss(e),this.config=new ns;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function tg(r){return r}var ig=0,sg=1500,ng=3,as=class{constructor(e,t,i=null,s="",n="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=n;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return F(void 0);let i=Date.now(),s=[],n=[];for(let d of new Set(e)){let R=this.rules.get(d);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(d,R));continue}(t?.force||!this.state.isStateFresh(d,t?.maxAgeMs))&&n.push(d);}let p=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(F(void 0))])).find(d=>!d.ok);return p&&!p.ok?p:F(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},ig),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(s=>i=s);try{let s=this.state?await this.state.readStateSlice(e):F(void 0),n=s.ok?F(void 0):s;for(let o of t)o(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=os(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(s,i?.maxAgeMs);if(R)return F(R.data);let V=this.loginFailures.get(s);if(V)return this.loginFailures.delete(s),V;let re=this.inflight.get(s);if(re)return re}let n=this.generation.get(s)??0,o=Date.now(),d=t().then(R=>{if(!R.ok)return R;let V=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:uo(e,R.data,V)}),R;let re=this.entries.get(s);if(re&&re.storedAt>=o)return R;let Se=uo(e,R.data,V);return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:Math.min(Se??1/0,V+sg)}),R}).finally(()=>{this.inflight.get(s)===d&&this.inflight.delete(s);});return this.inflight.set(s,d),d}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let s=t.Key?t.Key:void 0,n=os(i.view,s);if(!t.Success){this.loginFailures.set(n,u("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(n),i.apply(o.data,s),this.put(i.view,o.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=Nl({Name:s,Key:t});this.used.get(n)?.n!==this.session&&(this.used.set(n,{Name:s,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>ng||this.used.set(Nl(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(os(e,t))?.data}put(e,t,i){this.register(e);let s=os(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:uo(e,t,n)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(s=>t.has(s))&&this.invalidate(i);}};function os(r,e){return e===void 0?r.key:`${r.key}|${e}`}function Nl(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function uo(r,e,t){let i=r.expiresAt?.(e)??null,s=r.ttlMs!==void 0?t+r.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var ls=class{constructor(e,t){this.storage=e;this.authTypeKey=`Saved_AuthType_${t}`,this.emailKey=`Saved_Auth_Email_${t}`,this.passwordKey=`Saved_Auth_Password_${t}`,this.refreshTokenKey=`Saved_Auth_RefreshToken_${t}`;}storage;authTypeKey;emailKey;passwordKey;refreshTokenKey;get lastAuthType(){let e=this.storage.getString(this.authTypeKey);return rg(e)?e:we.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 rg(r){return r!==null&&Object.values(we).includes(r)}var og=8,ag=100,lg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,jl=["GameLoop"];function ug(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var us=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=we.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let s=this.authContext;if(!s)return a;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(n);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return a;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(i);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(we.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return u("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(we.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let s=await this.ctx.api.authentication.loginWithEmail(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(we.Email);return n.ok&&this.keepEmailCredentials(e,t),n}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let s=await this.ctx.api.authentication.registerWithEmail(i);return s.ok?(this.pendingRegistration={email:e,password:t},F({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(we.Email);return n.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,n}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?F(void 0):i}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let i=await this.ctx.api.authentication.loginWithGoogle(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(we.Google)):i}async loginWithApple(e,t){if(!e?.trim())return u("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(we.Apple)):s}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=i,s.Platform=this.ctx.platform.getPlatform(),s.Device=this.ctx.platform.getDeviceModel(),s.DeviceID=this.ctx.platform.getDeviceID();let n=await this.ctx.api.authentication.loginWithWallet(s);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(we.Wallet)):n}async loginWithSsoCode(e){if(!e)return u("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(we.iDosGames)):i}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=i,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==we.None?e:we.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let s=await this.ctx.api.authentication.refreshSession(i);return s.ok?(this.applyRefresh(s.data),"ok"):(ug(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case we.Email:return this.loginWithEmail(t,i);case we.Device:case we.None:return this.loginWithDeviceID();case we.Telegram:return this.loginWithTelegram();default:return Promise.resolve(u("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;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!==we.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===we.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&&lg.test(e)}static isValidPasswordLength(e){return e.length>=og&&e.length<=ag}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.sessionAuthType=we.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e){let t=await this.ctx.userService.getClientStateExcept(jl,jl);return t.ok&&(this.sessionAuthType=e,this.rememberSession?(this.ctx.authStore.saveAuthType(e),this.ctx.authStore.saveRefreshToken(this.sessionRefreshToken)):this.ctx.authStore.clear(),this.ctx.emitter.emit("auth:loggedIn",void 0)),t}};var cg="idos:cfg",di=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Wl(t)}`:e&&e.length>0?`f:${Wl(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${cg}:${this.titleId}:${e}`}};function Wl(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var Kl="idos:loc",mi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[s,n]of Object.entries(t))typeof n=="number"&&n>0&&(i[s]=n);return i}catch{return {}}}async noteVersion(e,t){let i=await this.readVersions();i[e]!==t&&(i[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(i)));}keyOf(e){return `${Kl}:${this.titleId}:${e}`}versionsKey(){return `${Kl}:${this.titleId}:versions`}};var pg="idos:sec",cs=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let i=JSON.parse(t);return !i||typeof i!="object"||i.v!==e||!i.s||typeof i.s!="object"?{}:i.s}catch{return {}}}async write(e,t){try{let i={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(i));}catch{}}keyOf(){return `${pg}:${this.titleId}`}};var hg="idos:state",ps=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,s){if(!(!e||!t))try{let n={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}keyOf(e){return `${hg}:${this.titleId}:${e}`}};function dg(r,e){if(!r)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return r;let i={};for(let[s,n]of Object.entries(r))t.has(s.toLowerCase())||(i[s]=n);return i}function co(r,e,t,i){let s={...r??{}};if(!e||!t||!i)return s;for(let[n,o]of Object.entries(t))i[n]===o&&n in e&&(s[n]=e[n]);return s}function mg(r){return {...r??{}}}function po(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var hs=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let s=this.confirmedAt[e];return s===void 0?false:t===void 0||i-s<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=dg(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,o]of Object.entries(t)){let p=this.versions[n];p!==o&&(p!==void 0&&o===p+1?(this.versions[n]=o,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=mg(t);let s=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=s;this.dirty=true;let n=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&n.add(o);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,o]of Object.entries(t??{}))this.versions[n]!==o&&s.push(n),this.versions[n]=o,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Ql=u("server","Title configuration is unavailable (CDN and API both failed)."),ds=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),RelatedEntityID:B()}:null}get configCache(){return this.cache??=new di(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new mi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new cs(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new hs(new ps(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return a;let t=di.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let o=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return o==null?Ql:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,o),await this.applyClientState(n.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=co(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=po(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,i,s){let n=e.TitleConfigVersion;if(i&&n&&i.v===n)return i.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return n&&await this.configCache.write(t,n,p),p}let o=await this.fetchConfigFromApi(s);return o!=null?(n&&await this.configCache.write(t,n,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return a;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=di.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let p=await this.ctx.api.user.getClientStateExcept(i);if(!p.ok)return p;let d=await this.resolveTitleConfig(p.data,s,n,{ExcludeFields:t??[]});return d==null?Ql:(this.finishStateHandshake(p.data,o),await this.restoreSections(p.data.TitleConfigVersion,d),await this.applyClientState(p.data,d,e,t),this.ctx.cache.acceptLoginViews(p.data.Views),await this.applyLocalization(p.data.Localization),await this.flushState(o),p)}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,s={};for(let[n,o]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=o);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,o)=>{i[n]!=null||o==null||(s[n]=o,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let o=n.Entries??{},p=n.Version??0,d=n.Locale??e;return p>0&&await this.localizationCache.write(d,p,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):a}async getUserState(e){let t=this.baseRequest();if(!t)return a;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=co(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let o=i.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([R,V])=>o[R]!==V||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,p);let d=po(s.data);return d&&(this.stateStore.afterSliceRead(d,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let s=this.baseRequest();if(!s)return a;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=i;let n=await this.ctx.api.user.addUsageTime(s);return n.ok&&this.ctx.emitter.emit("user:usageTimeAdded",n.data),n}async deleteUserAccount(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return a;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,s){let n=i?.includes("GameLoop")===true,o=s?.includes("GameLoop")===true,p=n?this.ctx.data.user.state?.GameLoop:void 0,d=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let R=this.ctx.data.user.state;n&&R&&R.GameLoop==null&&(R.GameLoop=p);let V=this.ctx.data.config.titlePublicConfiguration;o&&V&&V.GameLoop==null&&(V.GameLoop=d),this.ctx.emitter.emit("user:clientStateReceived",e);}};var fs=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,s,n,o){if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(n<=0)return u("client","Amount must be positive.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===ut.Crypto||i===ut.Crypto)return u("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return a;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${s}_${B()}`},d=await this.ctx.api.currency.convert(p);if(d.ok){let R=d.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.SourceID,Amount:R.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.TargetID,Amount:R.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return d}async cryptoConvert(e,t,i,s,n,o){let p=n instanceof jt__default.default?n:new jt__default.default(n);if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(p.lte(0))return u("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===ut.Virtual&&i===ut.Virtual)return u("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ut.Virtual&&!p.isInteger())return u("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return a;let d={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:p.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${s}_${B()}`},R=await this.ctx.api.currency.cryptoConvert(d);if(R.ok){let V=R.data,re=[],Se=[];if(V.SourceType===ut.Virtual&&re.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===ut.Virtual&&Se.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),re.length>0||Se.length>0){let ae={Consume:re.length>0?{Standard:{Entries:re}}:null,Grant:Se.length>0?{Standard:{Entries:Se}}:null};this.ctx.data.user.applyResourceOperation(ae,this.ctx.data.config.itemDefinitions);}V.SourceType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new jt__default.default(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new jt__default.default(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return R}};var gs=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let s=e.trim();if(!s)return u("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${s}_${B()}`};t&&t.length>0&&(n.FodderInstanceIDs=[...t]);let o=await this.ctx.api.item.upgradeLevel(n);return o.ok&&(this.ctx.data.user.patchEquippedItemLevel(o.data.ItemInstanceID??s,o.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",o.data)),o}async upgradeLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let s of i.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var Hl=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:xt.nullish(),AllowedPlatforms:zod.z.array(Ni).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ue=zod.z.record(zod.z.string(),Hl),fg=zod.z.object({Store:ji,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var ho=zod.z.object({ServerTimeUtc:c,OfferID:zod.z.string(),Count:zod.z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),$l=zod.z.array(ve(ho)),gg=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:c,LastPurchasedAt:c}),yg=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:c}),Jl=zod.z.object({Purchases:zod.z.record(zod.z.string(),gg).nullish(),Rotations:zod.z.record(zod.z.string(),yg).nullish()}).passthrough().transform(r=>r),Dt=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ys=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Rg={Fixed:"Fixed",Title:"Title",Player:"Player"},Cg=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:Z.nullish()}).passthrough(),Zl=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(Cg).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),Sg=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Rotation:K.nullish()}).passthrough(),xg=zod.z.object({SlotID:zod.z.string().nullish(),Identity:Dt.nullish(),Availability:ys.nullish(),Rotation:Zl.nullish(),Presets:Sg.nullish()}).passthrough(),bg=zod.z.object({Identity:K.nullish(),Availability:K.nullish()}).passthrough(),Dg=zod.z.object({SectionID:zod.z.string().nullish(),Identity:Dt.nullish(),Availability:ys.nullish(),Slots:zod.z.record(zod.z.string(),xg).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:bg.nullish()}).passthrough(),Yl=zod.z.object({Sections:zod.z.record(zod.z.string(),Dg).nullish()}).passthrough(),Pg=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Layout:K.nullish()}).passthrough(),Ig=zod.z.object({StoreID:zod.z.string().nullish(),Identity:Dt.nullish(),Availability:ys.nullish(),Layout:Yl.nullish(),Presets:Pg.nullish()}).passthrough(),Xl=zod.z.object({Options:ue.nullish(),CompareAt:zod.z.record(zod.z.string(),xt).nullish()}).passthrough(),eu=zod.z.object({Grant:H.nullish()}).passthrough(),tu=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),vg=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish(),Availability:K.nullish()}).passthrough(),Tg=zod.z.object({OfferID:zod.z.string().nullish(),Identity:Dt.nullish(),Pricing:Xl.nullish(),Reward:eu.nullish(),Availability:tu.nullish(),Presets:vg.nullish()}).passthrough(),Ag=zod.z.object({Identity:zod.z.record(zod.z.string(),Dt).nullish(),Availability:zod.z.record(zod.z.string(),ys).nullish(),Layout:zod.z.record(zod.z.string(),Yl).nullish(),Rotation:zod.z.record(zod.z.string(),Zl).nullish(),Pricing:zod.z.record(zod.z.string(),Xl).nullish(),Reward:zod.z.record(zod.z.string(),eu).nullish(),OfferAvailability:zod.z.record(zod.z.string(),tu).nullish()}).passthrough(),Rs=zod.z.object({Stores:zod.z.record(zod.z.string(),Ig).nullish(),StoreOffers:zod.z.record(zod.z.string(),Tg).nullish(),Presets:Ag.nullish()}).passthrough(),kg=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:c.nullish()}).passthrough(),zg=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:xt.nullish(),CompareAtCost:xt.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),wg=zod.z.object({OfferID:zod.z.string(),Identity:Dt.nullish(),PriceOptions:zod.z.array(zg).nullish(),Rewards:H.nullish(),State:kg.nullish()}).passthrough(),Mg=zod.z.object({SlotID:zod.z.string(),Identity:Dt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:c.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:wg.nullish()}).passthrough(),Og=zod.z.object({SectionID:zod.z.string(),Identity:Dt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(Mg).nullish()}).passthrough(),Ug=zod.z.object({StoreID:zod.z.string(),Identity:Dt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:c.nullish(),Sections:zod.z.array(Og).nullish()}).passthrough(),Cs=zod.z.object({ServerTimeUtc:c,Stores:zod.z.array(Ug).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Wt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront"},Eg="OFFER_NOT_IN_ROTATION";var iu="Store",su={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=null;for(let t of r.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},Ss=class{constructor(e){this.ctx=e;e.cache.bindLoginView(su,{schema:Cs,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return u("client","OfferID is required.");if(t<1)return u("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return a;let n={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,RelatedEntityID:`store_buy_${e}_${s.userID}_${B()}`},o=await this.ctx.api.store.purchase(n);if(o.ok){let p=o.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return o}async purchaseBatch(e){if(!e||e.length===0)return u("client","purchases is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||!n.Data.OfferID||(this.ctx.data.user.patchStorePurchase(n.Data.OfferID,n.Data.Count,n.Data.ServerTimeUtc),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(iu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(iu,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(su,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=s.RefreshesAtUtc;n&&(e===null||Date.parse(n)<Date.parse(e))&&(e=n);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var xs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?F(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return u("client","Receipt is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},n=await this.ctx.api.purchase.validatePurchase(s);return n.ok&&this.applyValidation(n.data),n}async buyWithTelegramStars(e,t){if(!e)return u("client","productID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(i);return s.ok&&t?.open!==false&&this.ctx.platform.openInvoice(s.data.InvoiceLink),s}async validatePurchasesBatch(e){if(!e||e.length===0)return u("client","receipts is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let s of i.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Pt=["https://idosgames.com","https://www.idosgames.com"];function nu(r){return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r.endsWith(".localhost")}function bs(r){if(Pt.includes(r))return true;if(typeof window>"u"||!nu(window.location.hostname))return false;try{return nu(new URL(r).hostname)}catch{return false}}var ru="IDOS_PLATFORM_WALLET_ACK",ou="PLATFORM_WALLET_UNAVAILABLE",qg=5e3,Lg=18e4;function Bg(){let r=[...Pt],e=window.location.ancestorOrigins?.[0];return e&&!r.includes(e)&&bs(e)&&r.push(e),r}function Gg(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ai(r,e,t,i={}){let s={ok:false,error:ou,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(s);let n=window.parent;if(!n)return Promise.resolve(s);let o=Gg(),p=i.answerTimeoutMs??Lg;return new Promise(d=>{let R=false,V,re=ae=>{R||(R=true,window.removeEventListener("message",Se),clearTimeout(V),d(ae));},Se=ae=>{if(!bs(ae.origin))return;let me=ae.data;if(!(!me||me.requestId!==o)){if(me.type===ru){clearTimeout(V),V=setTimeout(()=>re({ok:false,error:"TIMEOUT",data:{}}),p);return}me.type===e&&re({ok:me.ok===true,error:typeof me.error=="string"?me.error:void 0,data:me});}};V=setTimeout(()=>re(s),qg),window.addEventListener("message",Se);for(let ae of Bg())try{n.postMessage({type:r,requestId:o,...t},ae);}catch{}})}var mo={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},Fg=15*6e4,Vg=/^[a-z0-9]{8}-preview\.idos\.games$/;function fo(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !Vg.test(window.location.hostname.toLowerCase())}async function go(r){let e=await Ai(mo.request,mo.response,{titleID:r.titleID,userID:r.userID,currencyID:r.currencyID,amount:r.amount},{answerTimeoutMs:Fg});return e.ok?{ok:true}:{ok:false,error:e.error}}var au=3,_g=700,Ds=class{constructor(e){this.ctx=e;fo()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return pi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await go({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return i.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:i.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=au;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===au)break;await Mt(_g);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===_i.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==_i.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let n=this.cryptoBalance(i.CurrencyID);return n>=s?null:{currencyID:i.CurrencyID,required:s,available:n,missing:s-n}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var lu="Lootbox",Ps=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(lu,e);if(t){let n={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(lu,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s){if(!e)return u("client","LootboxID is required.");if(t<1)return u("client","Count must be at least 1.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,RelatedEntityID:`lootbox_${e}_${i??"default"}_${B()}`},o=await this.ctx.api.lootbox.open(n);if(o.ok){let p=o.data;p.TriggeredPity&&p.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,p.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",p);}return o}};var yo="Reward";function Ro(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Is=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Reward",{needsServer:()=>!t&&Object.values(e.cache.configSection(yo)?.Comebacks??{}).some(i=>i?.TrackPresenceOnRead===true),refresh:async()=>{let i=await this.getUserRewardsState();return i.ok&&(t=true),i}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(yo,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(yo,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${B()}`},s=await this.ctx.api.reward.claimDailyReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchDailyCalendarState(n.CalendarID,n.DailyState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",n);}return s}async collectIdleAccrual(e){if(!Ro(e))return u("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${B()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let s=i.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return i}async claimComebackReward(e){if(!Ro(e))return u("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${B()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return i}async claimReward(e){if(!Ro(e))return u("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${B()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return i}};var vs="Tutorial",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"]},Ts=class{constructor(e){this.ctx=e;e.cache.bindLoginView(uu,{schema:$i,apply:i=>this.applyUserTutorialState(i)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(vs)?.Flows??{}).length>0,refresh:async()=>{let i=await this.getUserTutorialState();return i.ok&&(t=true),i}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(vs,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(vs,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}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 a;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${B()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return u("client","FlowID is required.");if(!t||t.length===0)return u("client","stepIDs is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${B()}`},n=await this.ctx.api.tutorial.completeStepsBatch(s);return n.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",n.data)),n}async skipStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.skipStep(i))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${B()}`},s=await this.ctx.api.tutorial.claimFlowReward(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let s=e?.trim();if(!s)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},o=await t(n);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,s){let n=e?.trim(),o=t?.trim();if(!n)return u("client","FlowID is required.");if(!o)return u("client","StepID is required.");if(!this.ctx.auth.context)return a;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:o};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let d=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(p);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,o,d,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(vs)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}};var As=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return a;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return u("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return u("client","campaignID is required.");if(!t)return u("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return a;s.CampaignID=e,s.WalletAddress=t,i&&(s.Amount=i);let n=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return n.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",n.data),n}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Oe=zod.z.object({Username:zod.z.string().nullish(),Country:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Premium:zod.z.boolean().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BoardRank:zod.z.number().nullish()}).passthrough();var Ng={Global:"Global",Announcement:"Announcement",Group:"Group"},pu=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),jg={None:"None",Language:"Language",Region:"Region"},Wg=zod.z.enum(["None","Language","Region"]).catch("None"),Kg={Anyone:"Anyone",Friends:"Friends"},Qg=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),Hg={Reject:"Reject",Mask:"Mask"},$g=zod.z.enum(["Reject","Mask"]).catch("Reject"),Jg={Player:"Player",Publisher:"Publisher",System:"System"},Zg=zod.z.enum(["Player","Publisher","System"]).catch("Player"),Yg={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Xg=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),hu=zod.z.object({Gate:Z.nullish(),Schedule:ge.nullish()}).passthrough(),du=zod.z.object({Gate:Z.nullish(),Limits:Re.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),mu=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),ey=zod.z.object({Availability:K.nullish(),Write:K.nullish(),Retention:K.nullish()}).passthrough(),ty=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:Xg.nullish(),Type:pu.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:Wg.nullish(),Capacity:zod.z.number().nullish(),Availability:hu.nullish(),Write:du.nullish(),Retention:mu.nullish(),Presets:ey.nullish()}).passthrough(),iy=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Qg.nullish(),Limits:Re.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),sy=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:$g.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Re.nullish()}).passthrough(),ny=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),ry=zod.z.object({Availability:zod.z.record(zod.z.string(),hu).nullish(),Write:zod.z.record(zod.z.string(),du).nullish(),Retention:zod.z.record(zod.z.string(),mu).nullish()}).passthrough(),fu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),ty).nullish(),Direct:iy.nullish(),Moderation:sy.nullish(),Polling:ny.nullish(),Presets:ry.nullish()}).passthrough(),oy=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),cu=zod.z.object({LastAt:zod.z.string().nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:zod.z.string().nullish(),TotalCount:zod.z.number().nullish(),LastTextHash:zod.z.string().nullish()}).passthrough();zod.z.object({MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish(),Ignored:zod.z.array(zod.z.string()).nullish(),Channels:zod.z.record(zod.z.string(),oy).nullish(),Limits:zod.z.record(zod.z.string(),cu).nullish(),ReportLimits:cu.nullish()}).passthrough();var Co=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),ks=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:Oe.nullish(),AuthorType:Zg.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),ay=zod.z.object({ChannelID:zod.z.string().nullish(),RoomID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Type:pu.nullish(),CanWrite:zod.z.boolean().nullish(),WriteBlockedReason:zod.z.string().nullish(),SlowModeSeconds:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),zs=zod.z.object({Channels:zod.z.array(ay).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),ly=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(ks).nullish(),NextCursor:Co.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),gu=zod.z.object({Rooms:zod.z.array(ly).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),yu=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(ks).nullish(),NextBefore:Co.nullish()}).passthrough(),Ru=zod.z.object({Message:ks.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),Cu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Oe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),uy=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Oe.nullish(),LastMessage:ks.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Su=zod.z.object({Conversations:zod.z.array(uy).nullish()}).passthrough(),fi=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Co.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),xu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),Ke={GetChatDefinitions:"GetChatDefinitions",GetChannels:"GetChannels",Poll:"Poll",GetHistory:"GetHistory",GetConversations:"GetConversations",SendMessage:"SendMessage",OpenDirectChannel:"OpenDirectChannel",MarkRead:"MarkRead",JoinChannel:"JoinChannel",LeaveChannel:"LeaveChannel",ReportMessage:"ReportMessage",IgnoreUser:"IgnoreUser",UnignoreUser:"UnignoreUser"};var bu="Chat",Du={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Du,{schema:zs,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(bu,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(bu,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(Du,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let s of i.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return i}async getHistory(e,t,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),i&&(s.Limit=i),this.ctx.api.chat.getHistory(s)):a}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return a;s.ChannelID=e,s.Text=t,i&&(s.Locale=i);let n=await this.ctx.api.chat.sendMessage(s);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Text=t;let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):a}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):a}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(i);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):a}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):a}async reportMessage(e,t,i,s){let n=this.ctx.authedRequest();return n?(n.RoomID=e,n.MessageID=t,n.Reason=i,s&&(n.Comment=s),this.ctx.api.chat.reportMessage(n)):a}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):a}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):a}resetCursors(){this.cursors.clear();}};var cy={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},py=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),hy={Player:"player",Title:"title",Creator:"creator"},gi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Pu=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),dy=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),So=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:py.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(dy).nullish()}).passthrough(),Iu=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(So).nullish()}).passthrough(),It={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var my="IDOS_PLATFORM_PUSH_REQUEST",fy="IDOS_PLATFORM_PUSH_RESPONSE",gy=12e4;function vu(r){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,n=d=>{s||(s=true,window.removeEventListener("message",o),clearTimeout(p),i(d));},o=d=>{let R=d?.data;!R||R.type!==fy||R.requestId!==t||Pt.includes(d.origin)&&n(R.ok===true);},p=setTimeout(()=>n(false),gy);window.addEventListener("message",o);for(let d of Pt)try{e.postMessage({type:my,requestId:t,titleID:r},d);}catch{}})}var Ms=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return It.Unsupported;if(this.isEmbedded())return It.Embedded;if(!this.isSupported())return It.Unsupported;let t=Notification.permission;return t==="denied"?It.Blocked:t!=="granted"?It.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?It.Subscribed:It.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return u("client","Push notifications are not available for this title.");if(this.isEmbedded())return await vu(this.ctx.settings.titleID)?F({Where:"portal",Subscription:null}):u("client","The portal did not complete the subscription.");if(!this.isSupported())return u("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return u("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:yy(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return a;let d=o.toJSON();p.PushEndpoint=d.endpoint,p.PushP256dh=d.keys?.p256dh,p.PushAuth=d.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(p);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),F({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return a;if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return u("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):a}async unsubscribeByHash(e){if(!e)return u("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return a;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function yy(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var Os=Object.freeze({}),Us=class{constructor(e){this.ctx=e;}ctx;table={...Os};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new mi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),s=this.lookup(i)??this.lookup(e);return s===void 0?this.onMissing(e):t?Ry(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Os},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return a;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:o}=i.data,p=null;if(o){let d=await this.loadTableFromApi(o);d.ok&&(p=d.data.table);}return this.table=n,this.fallbackTable=p,this.currentFallbackLocale=o,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:o,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):a}reset(){this.table={...Os},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:B()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return a;t.Locale=e;let i=await this.cache.read(Tu(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,o=n.Locale??Tu(e),p=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:R?.t??{...Os},fallbackLocale:n.FallbackLocale??null}}}let d=n.Entries??{};return p>0&&await this.cache.write(o,p,d),{ok:true,data:{locale:o,table:d,fallbackLocale:n.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function Ry(r,e){return r.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function Tu(r){return r.trim().replace(/_/g,"-").toLowerCase()}var xo="Quest",Cy={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:r=>{let e=Date.now(),t=null,i=[...Object.values(r.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(r.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},Es=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(xo)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(s)){let p=Date.parse(n[o]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=i&&t<p)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true,{forceRefresh:true});return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(xo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(xo,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(Cy,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let s=i.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let i=e.trim();if(!i)return u("client","QuestID is required.");if(!this.ctx.auth.context)return a;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${B()}`},o=await this.ctx.api.quest.claimQuestReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return u("client","quests is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchQuestStatus(n.Data.QuestID,n.Data.CycleID,"Claimed"),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return u("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${B()}`},o=await this.ctx.api.quest.claimMilestoneReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchMilestoneClaimed(n.Data.CycleID,n.Data.MilestoneID),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return u("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${B()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return u("client","MetricID is required.");if(t<0)return u("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},n=await this.ctx.api.quest.addQuestProgress(s);return n.ok&&(this.ctx.data.user.patchQuestProgressUpdates(n.data.Updates),this.ctx.emitter.emit("quest:progressAdded",n.data)),n}};var Au=zod.z.object({}).passthrough().transform(r=>r);var Sy=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),xy=zod.z.object({Schedule:zod.z.array(Sy).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),by=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:c.nullish(),NextBonusStartUtc:c.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),Dy=zod.z.object({Milestones:K.nullish()}).passthrough(),bo=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Category:zod.z.string().nullish(),Token:Nt.nullish(),TokenSources:zod.z.array(st).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),Presets:Dy.nullish(),BonusWindow:xy.nullish()}).passthrough(),Py=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:bo.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Iy=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:ge.nullish(),Content:bo.nullish(),Events:zod.z.array(Py).nullish(),Gate:Z.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),vy=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),Ty=zod.z.object({Milestones:zod.z.record(zod.z.string(),ui).nullish()}).passthrough(),qs=zod.z.object({Definitions:zod.z.record(zod.z.string(),Iy).nullish(),Settings:vy.nullish(),Presets:Ty.nullish()}).passthrough(),Ay=zod.z.object({Type:vi,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:bo.nullish(),Progress:Au.nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:Le.nullish(),BonusWindow:by.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Ls=zod.z.object({ActiveEvents:zod.z.array(Ay).nullish()}).passthrough(),ku=zod.z.object({Tokens:zod.z.record(zod.z.string(),Au).nullish()}),Do=zod.z.object({Type:vi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Po=zod.z.object({Type:vi.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:M.nullish(),Inventory:Q.nullish()}),ky=zod.z.object({Type:vi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Io=zod.z.array(ve(Po)),zu=zod.z.array(ve(Do)),wu=zod.z.array(ve(ky)),ot={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Mu="TimedEvent",Ou={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:r=>{let e=null;for(let t of r.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Bs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ou,{schema:Ls,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(Ou,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(Mu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Mu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,s,n,o,p=1){if(!t)return u("client","LteID is required.");if(!i)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let d={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:o,RollMultiplier:p},R=await this.ctx.api.timedEvent.grantTokens(d);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return u("client","LteID is required.");if(i<=0)return u("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},n=await this.ctx.api.timedEvent.spendTokens(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",n.data)),n}async claimMilestone(e,t,i){if(!t||!i)return u("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let o=n.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return a;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return u("client","spends is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return u("client","grants is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let s=i.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var zy=zod.z.object({UserID:zod.z.string(),Score:j.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:c.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:Oe.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),ki=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:j.nullish(),CycleEndUtc:c.nullish(),TopUsers:zod.z.array(zy).nullish(),BracketID:zod.z.string().nullish()}),wy=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:c.nullish(),ClaimDeadlineUtc:c.nullish(),MilestoneTokensEarned:j.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Gs=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:j.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:j.nullish(),MilestoneTokensEarned:j.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:Le.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(wy).nullish()}),Fs=zod.z.object({LeaderboardID:zod.z.string(),NewScore:j,CycleVersion:zod.z.number()}),Vs=zod.z.object({ServerTimeUtc:c,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),_s=zod.z.object({ServerTimeUtc:c,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Uu=zod.z.array(ve(ki)),Ns=zod.z.array(ve(Gs)),Eu=zod.z.array(ve(Vs)),qu=zod.z.array(ve(_s)),Lu=zod.z.array(ve(Fs)),My=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:ve(Vs).nullish(),Milestones:zod.z.array(ve(_s)).nullish()}),Bu=zod.z.array(My),Oy=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:ve(ki).nullish(),Progress:ve(Gs).nullish()}),Gu=zod.z.array(Oy),Uy=zod.z.string(),Fu=zod.z.object({Rank:zod.z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:Yr.nullish()}).passthrough(),Ey=zod.z.object({RankRewards:zod.z.array(Fu).nullish()}).passthrough(),qy=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Ly=zod.z.object({Milestones:K.nullish(),RankRewards:K.nullish()}).passthrough(),By=zod.z.object({LeaderboardID:zod.z.string(),DisplayName:zod.z.string().nullish(),ScoreDisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsEnabled:zod.z.boolean().nullish(),ScoreAggregation:Uy.nullish(),Schedule:ge.nullish(),ChainEvents:zod.z.array(qy).nullish(),Gate:Z.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(Fu).nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),Presets:Ly.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(st).nullish()}).passthrough(),Gy=zod.z.object({Milestones:zod.z.record(zod.z.string(),ui).nullish(),RankRewards:zod.z.record(zod.z.string(),Ey).nullish()}).passthrough(),js=zod.z.object({Definitions:zod.z.record(zod.z.string(),By).nullish(),Presets:Gy.nullish()}).passthrough(),Ve={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 Vu="Leaderboard",_u={key:"leaderboard.progress",login:"LeaderboardProgress",ttlMs:5*6e4,dependsOn:["Leaderboard","EventToken"],invalidateOn:["leaderboard:scoreSubmitted","leaderboard:scoresSubmittedBatch","leaderboard:cycleRewardClaimed","leaderboard:cycleRewardsClaimedBatch","leaderboard:milestoneClaimed","leaderboard:milestonesClaimedBatch","leaderboard:allRewardsClaimedBatch"]},Ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(_u,{schema:Ns,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Vu,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Vu,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return u("client","LeaderboardID is required.");if(t<=0)return u("client","Score must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(i);if(s.ok){let n=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),n.NewScore,t,n.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",n);}return s}async submitScoreFromSource(e,t,i,s,n=1){if(!e)return u("client","LeaderboardID is required.");if(!t)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},p=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(p.ok){let d=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),d.NewScore,d.NewScore,d.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",d);}return p}async claimCycleReward(e){if(!e)return u("client","LeaderboardID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return i}async claimMilestone(e,t,i){if(!e||!t)return u("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let o=n.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return n}async getFriendsLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(u("client","leaderboardIDs is required.")):this.ctx.cache.read(_u,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return u("client","scores is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of s.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let s of i.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var vo=zod.z.object({}).passthrough().transform(r=>r),Ks=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>Ku).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:j.nullish(),UserState:vo.nullish(),NextTier:zod.z.lazy(()=>Wu).nullish()}).passthrough(),Nu=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:j.nullish(),NewStatusTokens:j.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),To=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),ju=ft(To);var Wu=zod.z.object({Tier:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredTokens:j.nullish(),TierReachedReward:H.nullish()}).passthrough(),Ku=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:j.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(Wu).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var Fy=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ge.nullish(),Seasons:zod.z.array(Ku).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:Z.nullish()}).passthrough(),Qs=zod.z.object({Chains:zod.z.record(zod.z.string(),Fy).nullish()}).passthrough(),Ut={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Qu="Season",Hu={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=Date.parse(r.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Hs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Hu,{schema:Ks,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Qu,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Qu,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(Hu,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(u("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return u("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","Amount must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${B()}`},s=await this.ctx.api.season.grantStatusTokens(i);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","TierNumber must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${B()}`},s=await this.ctx.api.season.claimTierReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",n);}return s}async claimTierRewardsBatch(e,t){if(!e)return u("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return u("client","TierNumbers is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${B()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let o=n.data;for(let p of o.Items??[]){let d=p.Data?.TierNumber;p.Success&&typeof d=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,d);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return n}};var $u="Premium",$s=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection($u,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection($u,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(i);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,i="Default",s=1){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,RelatedEntityID:`premium_purchase_${e}_${t}`},o=await this.ctx.api.premium.purchaseItemOrCurrency(n);if(o.ok){let p=o.data;p.Premium&&this.ctx.data.user.applyPremium(p.Premium),this.ctx.data.user.applyResourceOperation(p.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",p);}return o}async purchaseRealMoney(e,t,i,s,n,o,p,d){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!s||!n)return u("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return a;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:o,PackageName:p,AppStoreEnvironment:d,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(R);if(V.ok){let re=V.data;re.Premium&&this.ctx.data.user.applyPremium(re.Premium),this.ctx.data.user.applyResourceOperation(re.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",re);}return V}};var Js=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:c.nullish()}),Ao=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:j.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),Js).nullish(),UpdatedAt:c.nullish()}).passthrough(),Ju=zod.z.object({Characters:zod.z.record(zod.z.string(),Ao).nullish()}),ko=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),zo=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),Zu=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Js).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),Yu=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),Vy=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Xu=zod.z.object({ServerTimeUtc:c,Characters:zod.z.record(zod.z.string(),Vy).nullish(),Inventory:Q.nullish()}),wo=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:M.nullish()}),ec=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Js.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),tc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Js.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),ic=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),_y=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:c.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:ue.nullish()}),Ny=zod.z.object({CharacterID:zod.z.string(),CharacterOpen:zod.z.boolean().nullish(),DefaultSkinID:zod.z.string().nullish(),WornSkinID:zod.z.string().nullish(),Skins:zod.z.array(_y).nullish()}),sc=zod.z.object({ServerTimeUtc:c,Characters:zod.z.record(zod.z.string(),Ny).nullish()}),nc=ft(wo),rc=ft(zo),oc=ft(ko),Mo=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),ac=zod.z.object({StatID:zod.z.string(),TypeID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish(),Weight:zod.z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Fe.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Fe.nullish(),RankCurve:Fe.nullish(),Requirements:zod.z.array(Mo).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),jy=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Mo).nullish(),AllowedRarityIDs:zod.z.array(zod.z.string()).nullish(),AllowedItemTags:zod.z.array(zod.z.string()).nullish(),MinItemLevel:zod.z.number().nullish(),MaxItemLevel:zod.z.number().nullish()}).passthrough(),lc=zod.z.object({Slots:zod.z.record(zod.z.string(),jy).nullish()}).passthrough(),uc=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Lore:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Wy=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ky=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:ue.nullish()}).passthrough(),Qy=zod.z.object({Stats:K.nullish(),Levels:K.nullish(),Equipment:K.nullish()}).passthrough(),cc=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Fe.nullish()}).passthrough(),Oo="@skin";function Hy(r){return !!r&&r.startsWith("@")}var $y=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),Jy=zod.z.object({PriceOptions:ue.nullish(),Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Zy=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Mo).nullish()}).passthrough(),Yy=zod.z.object({SkinID:zod.z.string().nullish(),Identity:uc.nullish(),Item:$y.nullish(),Sale:Jy.nullish(),Requirements:Zy.nullish()}).passthrough(),Xy=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),Yy).nullish()}).passthrough(),eR=zod.z.object({CharacterID:zod.z.string(),Identity:uc.nullish(),Classification:Wy.nullish(),Unlock:Ky.nullish(),Presets:Qy.nullish(),Equipment:lc.nullish(),Stats:zod.z.record(zod.z.string(),ac).nullish(),RankLadder:cc.nullish(),RankStatCurve:Fe.nullish(),StatMaxLevelCurve:Fe.nullish(),Skins:Xy.nullish()}).passthrough(),tR=zod.z.object({Stats:zod.z.record(zod.z.string(),ac).nullish()}).passthrough(),iR=zod.z.object({RankLadder:cc.nullish()}).passthrough(),sR=zod.z.object({Equipment:lc.nullish()}).passthrough(),nR=zod.z.object({Stats:zod.z.record(zod.z.string(),tR).nullish(),Levels:zod.z.record(zod.z.string(),iR).nullish(),Equipment:zod.z.record(zod.z.string(),sR).nullish()}).passthrough(),Zs=zod.z.object({Definitions:zod.z.record(zod.z.string(),eR).nullish(),Presets:nR.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"},rR="SKIN_ALREADY_OWNED";var Uo="Character",Ys=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Uo)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,n])=>n?.Unlock?.UnlockedByDefault===true&&!i[n.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Uo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Uo,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${B()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return u("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${B()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok){let o=n.data;this.ctx.data.user.patchCharacter(o.CharacterID,p=>{p.StatLevels??={},p.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(p.Power=o.Power),p.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return n}async upgradeCharacterLevel(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${B()}`,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level=n.NewLevel,n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(i);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(i);if(s.ok){let n=s.data;this.applyUnequipChangesLocally(e,n),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:n.ClearedSlotIDs??[],power:n.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${B()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok){let o=n.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return n}async equipSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let o=n.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return n}async unequipSkin(e){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let s=i.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):a}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,Oo,t??null),n.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return u("client","characterIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level??=1,n.StatLevels??={},n.Equipment??={},s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level=s.NewLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(n.StatLevels??={},n.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.StatLevels??={},n.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[s,n]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,s,n);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let n of i)s.patchCharacterEquipment(e,n,null);s.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,s]of Object.entries(e.Characters??{})){for(let n of s.ClearedSlotIDs??[])t.patchCharacterEquipment(i,n,null);t.patchCharacter(i,n=>{s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=e.ServerTimeUtc;});}}};var pc="Match",Xs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,o){let p=this.ctx.auth.context;if(!p)return a;let d={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:o,RelatedEntityID:`pvp_create_${p.userID}_${B()}`},R=await this.ctx.api.match.createMatch(d);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 u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(i);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,s){let n=this.ctx.auth.context;if(!n)return a;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${B()}`},p=await this.ctx.api.match.instantBattle(o);if(p.ok){let d=p.data,R=this.ctx.data.config.itemDefinitions;if(d.Resources)this.ctx.data.user.applyResourceOperation(d.Resources,R);else if(d.ResourcesDual){let V=d.ResourcesDual;V.FromUserID===n.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,R):V.ToUserID===n.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",d);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;s.Page=e,s.PageSize=t,s.Statuses=i;let n=await this.ctx.api.match.getMyMatches(s);return n.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",n.data),n}async getAvailableMatches(e=0,t=20,i=false){let s=this.ctx.authedRequest();if(!s)return a;s.Page=e,s.PageSize=t,s.OnlyPublic=i;let n=await this.ctx.api.match.getAvailableMatches(s);return n.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",n.data),n}async getDefinitions(e){let t=this.ctx.cache.configSection(pc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(pc,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var hc="Craft",en=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(hc,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(hc,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n){if(!e)return u("client","CraftID is required.");let o=this.ctx.auth.context;if(!o)return a;let p={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,RelatedEntityID:`craft_${e}_${o.userID}_${B()}`},d=await this.ctx.api.craft.craft(p);return d.ok&&(this.ctx.data.user.applyResourcesWithDelta(d.data.Resources,d.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",d.data)),d}};var Et=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Et),zod.z.record(zod.z.string(),Et)]));var qt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},dc=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Kt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function zi(r){return r!==Kt.Pending&&r!==Kt.Running}var oR={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 aR(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var lR=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),uR=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),tn=zod.z.object({GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:dc.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Et).nullish(),Assets:zod.z.array(lR).nullish(),Error:uR.nullish(),Charge:M.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reward:M.nullish(),Context:zod.z.record(zod.z.string(),Et).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish()}),mc=zod.z.object({Data:zod.z.array(tn).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),cR=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish()}).passthrough(),pR=zod.z.object({Modality:dc.nullish(),Async:zod.z.boolean().nullish(),Limits:Re.nullish(),PriceOptions:ue.nullish(),Tags:zod.z.array(zod.z.string()).nullish(),HistoryMessages:zod.z.number().nullish(),MaxTokens:zod.z.number().nullish(),AllowImages:zod.z.boolean().nullish(),MaxInputImages:zod.z.number().nullish(),MaxInputImageBytes:zod.z.number().nullish(),AllowedImageTypes:zod.z.array(zod.z.string()).nullish(),MaxImages:zod.z.number().nullish(),AllowEdit:zod.z.boolean().nullish(),AllowReferenceImage:zod.z.boolean().nullish(),MaxPromptChars:zod.z.number().nullish(),LockBehavior:zod.z.boolean().nullish(),ImageSize:zod.z.string().nullish(),VideoSize:zod.z.string().nullish(),VideoSeconds:zod.z.number().nullish(),Voice:zod.z.string().nullish(),AudioFormat:zod.z.string().nullish(),MusicFormat:zod.z.string().nullish(),ThreeDOperation:zod.z.string().nullish(),ArtStyle:zod.z.string().nullish(),ThreeDFormat:zod.z.string().nullish(),Reward:H.nullish(),PromptVariables:zod.z.array(cR).nullish(),AllowFreePrompt:zod.z.boolean().nullish()}).passthrough(),fc=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),pR).nullish()}).passthrough(),Ge={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic"};var gc="AI",hR=/^[A-Za-z0-9_-]{1,128}$/,dR=2e3,mR=5e3,fR=30*6e4;function gR(r,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,r);e?.addEventListener("abort",i,{once:true});})}var sn=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(gc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(gc,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):a}async getGeneration(e){if(!e)return u("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):a}isTerminal(e){return zi(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;i=p.data;}else {if(!e?.GenerationID)return u("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??fR),n=Math.max(1,t.intervalMs??dR),o=Math.max(n,t.maxIntervalMs??mR);for(;!zi(i.Status);){if(t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return u("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await gR(n,t.signal),t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(i);if(n=Math.min(o,Math.round(n*1.5)),!p.ok){if(p.reason==="connection")continue;return p}i=p.data,zi(i.Status)||t.onUpdate?.(i);}return F(i)}pollFor(e){switch(e.Modality){case qt.Text:return this.getText(e.GenerationID);case qt.Image:return this.getImage(e.GenerationID);case qt.Audio:return this.getAudio(e.GenerationID);case qt.Music:return this.getMusic(e.GenerationID);case qt.Video:return this.getVideo(e.GenerationID);case qt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return u("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!hR.test(n))return u("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??B()},p=await s(o);return p.ok&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return u("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.GenerationID=e;let s=await t(i);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Kt.Completed&&!this.rewarded.has(e.GenerationID)&&(this.rewarded.add(e.GenerationID),await this.ctx.userService.getUserInventory()),!(!t||!e.Charge||this.charged.has(e.GenerationID))&&(this.charged.add(e.GenerationID),this.ctx.data.user.applyResourceOperation(e.Charge,this.ctx.data.config.itemDefinitions));}emitView(e){this.ctx.emitter.emit("ai:generationUpdated",e),e.Status===Kt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Kt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Eo="Collection",nn=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let i=e.cache.configSection(Eo),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(p=>(p?.Seasons??[]).some(d=>!!d?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Eo,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Eo,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,s){let n=this.ctx.auth.context;if(!n)return a;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${B()}`},p=await this.ctx.api.collection.openPack(o);return p.ok&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${B()}`},o=await this.ctx.api.collection.openCollectionChest(n);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${B()}`},n=await this.ctx.api.collection.useCollectibleJoker(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",n.data)),n}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${B()}`},n=await this.ctx.api.collection.claimSetReward(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",n.data)),n}async claimSetRewardsBatch(e){if(!e||e.length===0)return u("client","sets is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${B()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,o=false){let p=this.ctx.auth.context;if(!p)return a;let d={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${p.userID}_${s}_${B()}`},R=await this.ctx.api.collection.sendTradeOffer(d);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${B()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${B()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${B()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var yR=zod.z.object({}).passthrough().transform(r=>r),RR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},CR={Active:"Active",Left:"Left",Replaced:"Replaced"},SR=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),xR=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Oe.nullish(),BuildObjectsProgress:SR.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),bR=zod.z.object({Index:zod.z.number().nullish(),OwnerUserID:zod.z.string().nullish(),CurrentProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish(),IsCompleted:zod.z.boolean().nullish()}).passthrough(),DR=zod.z.object({Objects:zod.z.array(bR).nullish()}).passthrough(),yc=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CoopChainID:zod.z.string().nullish(),CoopEventID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),Members:zod.z.array(xR).nullish(),BuildObjectsState:DR.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:zod.z.number().nullish()}).passthrough(),Rc=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Cc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),PR=zod.z.string(),qo=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Weight:zod.z.number().nullish(),MinProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish()}).passthrough(),IR=zod.z.object({Index:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxProgress:zod.z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),vR=zod.z.object({Objects:zod.z.array(IR).nullish(),PriceOptions:ue.nullish(),SpinnerTable:zod.z.array(qo).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Cc=zod.z.object({CoopEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),EventType:PR.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:vR.nullish(),GrandPrize:H.nullish()}).passthrough(),TR=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ge.nullish(),Events:zod.z.array(Cc).nullish(),Gate:Z.nullish()}).passthrough(),rn=zod.z.object({ServerTimeUtc:c.nullish(),UserState:yR.nullish(),ActiveGroup:yc.nullish()}),Lo=zod.z.object({ServerTimeUtc:c.nullish(),Group:yc.nullish(),SecondsRemaining:j.nullish()}),Sc=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Resources:M.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:qo.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(qo).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),Bo=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),xc=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),on=zod.z.object({Chains:zod.z.record(zod.z.string(),TR).nullish()}).passthrough(),ht={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var bc="CoopEvent",Dc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},an=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Dc,{schema:rn,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(bc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(bc,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return u("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(Dc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return u("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return u("client","CoopChainID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let s=i.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,s){if(!e||!t)return u("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,RelatedEntityID:B()},o=await this.ctx.api.coopEvent.spin(n);return o.ok&&(this.ctx.data.user.applyResourceOperation(o.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",o.data)),o}async claimObjectReward(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var AR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},kR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},zR=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:c.nullish(),CompletedAtUtc:c.nullish(),LastExecutedAtUtc:c.nullish(),NextAvailableAtUtc:c.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),wR=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),Pc=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:c.nullish(),ExhaustedAtUtc:c.nullish(),ExpiredAtUtc:c.nullish(),DismissedAtUtc:c.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:c.nullish(),Nodes:zod.z.record(zod.z.string(),zR).nullish(),Tracks:zod.z.record(zod.z.string(),wR).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),MR=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:c.nullish(),ActiveOfferExpiresAtUtc:c.nullish(),ActiveOffer:Pc.nullish(),NextCycleStartsAtUtc:c.nullish(),LastUpdatedUtc:c.nullish(),DismissSkipAvailableAtUtc:c.nullish(),LastDismissedAtUtc:c.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),OR=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),UR=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:c.nullish(),LastActivatedAtUtc:c.nullish(),LastExhaustedAtUtc:c.nullish(),NodeCounts:zod.z.record(zod.z.string(),OR).nullish()}).passthrough(),ER=zod.z.object({Slots:zod.z.record(zod.z.string(),MR).nullish(),OfferHistory:zod.z.record(zod.z.string(),UR).nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),qR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},LR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},BR=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),ln=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ic=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),vc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),GR=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Behaviour:K.nullish()}).passthrough(),FR=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ln.nullish(),Availability:Ic.nullish(),Behaviour:vc.nullish(),Queue:zod.z.array(BR).nullish(),Presets:GR.nullish()}).passthrough(),VR=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),_R=zod.z.object({RewardedVideo:VR.nullish()}).passthrough(),NR=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),jR=zod.z.object({Identity:K.nullish(),Graph:K.nullish(),Milestones:K.nullish()}).passthrough(),WR=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish()}).passthrough(),KR=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),QR=zod.z.object({TrackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),StartValue:zod.z.number().nullish(),MinValue:zod.z.number().nullish(),MaxValue:zod.z.number().nullish(),ClampToMin:zod.z.boolean().nullish(),ClampToMax:zod.z.boolean().nullish(),HiddenFromUI:zod.z.boolean().nullish()}).passthrough(),HR=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(NR).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),Tc=zod.z.object({Options:ue.nullish()}).passthrough(),Ac=zod.z.object({Grants:H.nullish(),TrackChanges:zod.z.array(KR).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),$R=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:ln.nullish(),Pricing:Tc.nullish(),Reward:Ac.nullish(),Action:_R.nullish(),UnlockRules:HR.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Re.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:WR.nullish()}).passthrough(),kc=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array($R).nullish(),Tracks:zod.z.array(QR).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),zc=zod.z.object({Milestones:zod.z.record(zod.z.string(),Le).nullish(),ClaimMode:zod.z.string().nullish(),Token:Nt.nullish()}).passthrough(),wc=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ln.nullish(),Graph:kc.nullish(),Milestones:zc.nullish(),Presets:jR.nullish()}).passthrough(),JR=zod.z.object({Identity:zod.z.record(zod.z.string(),ln).nullish(),Availability:zod.z.record(zod.z.string(),Ic).nullish(),Behaviour:zod.z.record(zod.z.string(),vc).nullish(),Graph:zod.z.record(zod.z.string(),kc).nullish(),Milestones:zod.z.record(zod.z.string(),zc).nullish(),Pricing:zod.z.record(zod.z.string(),Tc).nullish(),Reward:zod.z.record(zod.z.string(),Ac).nullish()}).passthrough(),Go=zod.z.object({Slots:zod.z.record(zod.z.string(),FR).nullish(),Offers:zod.z.record(zod.z.string(),wc).nullish(),Presets:JR.nullish()}).passthrough(),Mc=zod.z.object({DealOfferDefinitions:Go.nullish()}),Oc=zod.z.object({DealOffers:ER.nullish()}),ZR=zod.z.object({EntityID:zod.z.string().nullish(),TotalEarned:zod.z.number().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),ReachedUnclaimedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),YR=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:wc.nullish(),ActivationState:Pc.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:c.nullish(),Cost:xt.nullish(),Milestone:ZR.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),un=zod.z.object({Slots:zod.z.array(YR).nullish()}),Uc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ec=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),qc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),Lc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Bc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),yt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var XR="DealOffer",Gc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},cn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Gc,{schema:un,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(XR,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(Gc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${B()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,s){if(!e||!t)return u("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return a;let n=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:n??`deal_exec_${e}_${t}_${B()}`},p=await this.ctx.api.dealOffer.executeNode(o);return p.ok&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${B()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return u("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${B()}`},s=await this.ctx.api.dealOffer.claimMilestone(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${B()}`},n=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",n.data)),n}};var Fc="Referral",pn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Fc,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Fc,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=_t.parseReferralCode(e)?.toUpperCase();if(!t)return u("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let o=n.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return n}async claimInviteReward(e){let t=e.trim();if(!t)return u("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let o=n.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return n}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return u("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let o=n.data;for(let p of o.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return n}};var eC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Vc=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),tC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},iC=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),sC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},nC=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),et={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},rC={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"},oC=100,aC=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),_c=zod.z.object({FeatureID:zod.z.string().nullish(),Args:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Url:zod.z.string().nullish(),Label:zod.z.string().nullish()}).passthrough(),lC=zod.z.object({Texts:zod.z.record(zod.z.string(),aC).nullish(),Category:Vc.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:_c.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),uC=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:ce.nullish(),Cost:ce.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:c.nullish(),SenderGate:Z.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),cC=zod.z.object({Type:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxAmountPerGift:zod.z.number().nullish()}).passthrough(),pC=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(cC).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:c.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:ce.nullish(),SenderGate:Z.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),Nc=zod.z.object({Enabled:zod.z.boolean().nullish(),Capacity:zod.z.number().nullish(),RewardLetterDays:zod.z.number().nullish(),PlainLetterDays:zod.z.number().nullish(),ClaimedRetentionDays:zod.z.number().nullish(),DefaultLanguage:zod.z.string().nullish(),Templates:zod.z.record(zod.z.string(),lC).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),uC).nullish(),Transfer:pC.nullish()}).passthrough().nullish(),Integrations:zod.z.object({Leaderboard:zod.z.boolean().nullish(),CoopEvent:zod.z.boolean().nullish(),Season:zod.z.boolean().nullish(),Referral:zod.z.boolean().nullish()}).passthrough().nullish()}).passthrough(),hC=zod.z.object({MessageID:zod.z.string(),Source:iC,Category:Vc,TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:_c.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:H.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:c,ExpiresAt:c.nullish(),ReadAt:c.nullish(),ClaimedAt:c.nullish()}).passthrough(),dC=zod.z.object({MessageID:zod.z.string(),Module:nC,Key:zod.z.string(),TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish()}).passthrough(),Fo=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),jc=zod.z.object({ServerTimeUtc:c.nullish(),Messages:zod.z.array(hC).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(dC).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),hn=zod.z.object({ServerTimeUtc:c.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Vo=zod.z.object({ServerTimeUtc:c.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(Fo).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),mC=zod.z.object({MessageID:zod.z.string(),Rewards:ce.nullish()}).passthrough(),dn=zod.z.object({ServerTimeUtc:c.nullish(),Claimed:zod.z.array(mC).default([]),Failed:zod.z.array(Fo).default([]),Resources:M.nullish(),Inventory:Q.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Wc=zod.z.object({ServerTimeUtc:c.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(Fo).default([]),Resources:M.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish()}).passthrough(),Kc=zod.z.object({ServerTimeUtc:c.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),RecipientReceives:ce.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),Qc=zod.z.object({ServerTimeUtc:c.nullish(),ResetsAt:c.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:c.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish()}).passthrough().nullish()}).passthrough();var _o="Mailbox",No={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},mn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(No,{schema:hn,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(No,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(_o)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(_o,e);if(t)return F(t);let i=this.request();if(!i)return a;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(_o,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return a;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(No,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return a;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return a;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return u("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):a}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return u("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):a}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):a}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return a;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return u("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return u("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return a;let n=await this.ctx.api.mailbox.sendGift(s);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",n.data)),n}async sendTransfer(e,t,i){if(!e?.trim())return u("client","RecipientUserID is required.");if(!i?.requestID?.trim())return u("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return a;let n=await this.ctx.api.mailbox.sendTransfer(s);return n.ok&&(n.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(n.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",n.data)),n}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):a}};var fC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},gC={Title:"Title",Platform:"Platform"},Hc=zod.z.object({UserID:zod.z.string(),PublicData:Oe.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),wi=zod.z.object({Friends:zod.z.array(Hc).nullish()}),yC=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Mi=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:Hc.nullish(),Counters:yC.nullish()}),RC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},CC={Like:"Like",Favorite:"Favorite"},SC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},xC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},bC={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},DC=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),PC=zod.z.object({Id:zod.z.string(),Verb:zod.z.string().nullish(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Count:zod.z.number().nullish(),LastActors:zod.z.array(DC).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),OccurredAt:c.nullish(),OwnerImpact:M.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),$c=zod.z.object({Items:zod.z.array(PC).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:c.nullish()}).passthrough(),Oi=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:c.nullish()}).passthrough(),IC=zod.z.object({Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),Followers:zod.z.number().nullish(),Following:zod.z.number().nullish(),Comments:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Posts:zod.z.number().nullish(),Dislikes:zod.z.number().nullish()}).passthrough(),Lt=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:IC.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Jc=zod.z.object({Items:zod.z.array(Lt).nullish()}).passthrough(),jo={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},vC=zod.z.object({UserID:zod.z.string(),PublicData:Oe.nullish(),Mutual:zod.z.boolean().nullish(),Since:c.nullish()}).passthrough(),fn=zod.z.object({Items:zod.z.array(vC).nullish(),...jo}).passthrough(),TC=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:c.nullish()}).passthrough(),Zc=zod.z.object({Items:zod.z.array(TC).nullish(),...jo}).passthrough(),gn=zod.z.object({CommentID:zod.z.string(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),ParentCommentID:zod.z.string().nullish(),AuthorUserID:zod.z.string().nullish(),AuthorPublicData:Oe.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:c.nullish(),EditedAt:c.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Yc=zod.z.object({Items:zod.z.array(gn).nullish(),...jo,TotalCount:zod.z.number().nullish()}).passthrough(),Xc=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),ep=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),tp=zod.z.object({CommentsEnabled:zod.z.boolean().nullish(),CommentableTypes:zod.z.array(zod.z.string()).nullish(),CommentMaxLength:zod.z.number().nullish(),CommentMaxLinks:zod.z.number().nullish()}).passthrough(),AC="FRIENDS_FROM_PLATFORM",kC={Off:"Off",Default:"Default",Always:"Always"},zC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},ip=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),Ce={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report"};var Wo={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},yn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Wo,{schema:Oi,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return a;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return u("client","TargetUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return u("client","FriendUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return a;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(Wo,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(Wo,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):a}async getEntityStates(e,t){if(!t?.length)return u("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):a}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return u("client","Text is required.");n.Text=i,n.ParentCommentID=s;let o=await this.ctx.api.social.addComment(n);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return u("client","CommentID is required.");if(!t?.trim())return u("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return a;i.CommentID=e,i.Text=t;let s=await this.ctx.api.social.editComment(i);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return u("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=i.parentCommentID,this.applyPage(s,i.cursor,i.limit),this.ctx.api.social.getComments(s))}async report(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i)return u("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let o=await this.ctx.api.social.report(n);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let o=await this.ctx.api.social[e](n);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):a}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return u("client","EntityType is required.");if(!t)return u("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):a}};var sp="TimedBoost";function wC(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Rn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(sp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(sp,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let i=e.trim();if(!wC(i))return u("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${B()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok){let o=n.data;if(o.ActivatedBoost){let p=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var Tt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},MC={Client:"Client",Server:"Server",System:"System"},OC=zod.z.enum(["Client","Server","System"]).catch("Client"),UC=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:c.nullish(),Version:zod.z.number().nullish(),LastWriter:OC.nullish(),ExpiresAt:c.nullish()}).passthrough(),Cn=zod.z.record(zod.z.string(),UC),np=zod.z.object({Version:zod.z.number().nullish(),Private:Cn.nullish(),Public:Cn.nullish(),ReadOnly:Cn.nullish()}),Ko=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Cn.nullish()}),Qo=zod.z.object({ServerTimeUtc:c.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:c.nullish()}),EC=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:c.nullish()}),rp=zod.z.object({ServerTimeUtc:c.nullish(),Results:zod.z.array(EC).nullish()}),op=zod.z.object({ServerTimeUtc:c.nullish(),DeletedCount:zod.z.number().nullish()}),ap=zod.z.object({Results:zod.z.array(Ko).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),qC={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},LC=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),BC=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:LC.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Sn=zod.z.object({Keys:zod.z.record(zod.z.string(),BC).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),dt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var GC="UserCustomData";function lp(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var xn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(GC,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,Tt.Private)}async setPublicData(e,t){return this.setData(e,t,Tt.Public)}async setData(e,t,i){let s=e.trim();if(!lp(s))return u("client",'KeyID is required and must not contain "." or "$".');if(t==null)return u("client","Value is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(i===Tt.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(p.ok){let d=p.data;this.ctx.data.user.patchUserCustomDataKey(i,d.KeyID,t,d.Version??0,d.ExpiresAt),this.ctx.emitter.emit(i===Tt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",d);}return p}async deleteKey(e,t){let i=e.trim();if(!lp(i))return u("client",'KeyID is required and must not contain "." or "$".');if(t!==Tt.Private&&t!==Tt.Public)return u("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},n=await this.ctx.api.userCustomData.deleteKey(s);return n.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),n}async batchSet(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??Tt.Private,o=e.find(p=>p.Bucket===n&&p.KeyID===s.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,o.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return u("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var FC="TitleCustomDataDefinitions",up=50;function VC(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function Ho(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function _C(r){let e={};for(let[t,i]of Object.entries(r))Ho(i)||(e[t]=i);return e}var bn=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(FC,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return a;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return u("client","At least one KeyID is required.");if(t.some(n=>!VC(n)))return u("client",'KeyID must not contain "." or "$".');if(t.length>up)return u("client",`At most ${up} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return a;i.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Ho(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Ho(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=_C(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var Dn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var NC=15,jC="GameLoop",cp="BoardDefinition",Pn=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(jC,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(cp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),F(i);let s=this.ctx.authedRequest();if(!s)return a;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(cp,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return u("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return a;i.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return u("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${B()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,o=Vl(new Date,NC);this.ctx.data.user.patchBoardState(p=>{p.Position=n.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?p.Pending={Type:n.ActionRequired,TargetUserID:n.ActionData.TargetUserID,TargetPublicData:n.ActionData.PublicData,TargetBuildingStates:n.ActionData.TargetBuildingStates??void 0,TargetHasShield:n.ActionData.TargetHasShield??void 0,RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o}:n.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${B()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.IsBotTarget&&n.Operation?this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs):!n.IsBotTarget&&n.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(n.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",n);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return u("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${B()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let o=n.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return n}async boardLoopRaidFast(e){if(!e.length)return u("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${B()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(s.ok){let n=s.data;n.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(n)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",n);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return u("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${B()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(n.BuiltIndex,o=>{n.NewLevel!=null&&(o.Level=n.NewLevel),o.IsDamaged=false,n.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t){if(!e)return u("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${B()}`},n=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(n.ok){let o=n.data;o.Mode==="Instant"||o.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(d=>{d.ChoiceID=e,d.ChosenMode=o.Mode??"Timed",d.StartedAtUtc=o.StartedAtUtc??null,d.DurationSeconds=o.DurationSeconds??null,d.AdViewsUsed=0;}),o.Operation&&this.ctx.data.user.applyResourcesWithDelta(o.Operation,o.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",o);}return n}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${B()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=n.AdViewsUsed??0,o.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${B()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",n);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return u("client","milestoneID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var In=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return u("client","FunctionName is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(o);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var pp=zod.z.object({ServerTimeUtc:c,SourceType:ai,SourceID:zod.z.string(),TargetType:ai,TargetID:zod.z.string(),SourceSpent:j,FeeAmount:j,RateApplied:Y,TargetCredited:j}),hp=zod.z.object({ServerTimeUtc:c,SourceType:ai,SourceID:zod.z.string(),TargetType:ai,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),vn={Convert:"Convert",CryptoConvert:"CryptoConvert"},WC={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},dp=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),KC={Automatic:"Automatic",Manual:"Manual"},QC=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),HC=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),$C=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),JC=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),ZC=zod.z.object({TargetCurrencyType:ai.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),mp=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:QC.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(ZC).nullish()}).passthrough(),fp=zod.z.object({CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough(),YC=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:HC.nullish(),Recharge:$C.nullish(),Conversion:mp.nullish(),Permissions:JC.nullish(),Audit:fp.nullish(),Status:dp.nullish()}).passthrough(),XC=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),eS=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),tS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),iS=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish(),RefuseOverCap:zod.z.boolean().nullish()}).passthrough(),$o=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),DisplayDecimals:zod.z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:zod.z.array(XC).nullish(),Limits:eS.nullish(),Permissions:tS.nullish(),Conversion:mp.nullish(),Audit:fp.nullish(),Status:dp.nullish(),ServerGrantPolicy:iS.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),Tn=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),YC).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),$o).nullish()}).passthrough();var sS={EVM:"EVM",Solana:"Solana"},nS=zod.z.enum(["EVM","Solana"]).catch("EVM"),rS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},oS=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),aS={Token:"Token",Nft:"Nft"},gp=zod.z.enum(["Token","Nft"]).catch("Token"),lS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},uS=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),cS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},pS=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),hS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Jo=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),yp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function An(r){let e=r?.trim();return e||yp.GameTopUp}var dS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Rp=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),mS=zod.z.object({ContractAddress:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),Cp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),fS=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:nS.nullish(),ChainID:zod.z.number().nullish(),ChainTicker:zod.z.string().nullish(),RewardPoolAddress:zod.z.string().nullish(),VaultDepositAddress:zod.z.string().nullish(),ChainConfigVersion:zod.z.number().nullish(),RequiredConfirmations:zod.z.number().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Cp.nullish(),NftCollections:zod.z.array(mS).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RpcUrl:zod.z.string().nullish(),GasPrice:zod.z.number().nullish(),NftBridgeAddress:zod.z.string().nullish(),SignatureEpoch:zod.z.number().nullish()}).passthrough(),gS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Cp.nullish()}).passthrough(),yS=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),RS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},CS=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Sp=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:CS.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),SS=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),xS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ui=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),bS=zod.z.object({Mode:Ui.nullish(),TokenGates:zod.z.array(Sp).nullish()}).passthrough(),Zo=zod.z.object({SystemState:gS.nullish(),Networks:zod.z.record(zod.z.string(),fS).nullish(),AccountSafety:yS.nullish(),WalletLogin:SS.nullish(),PlayAccess:bS.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),DS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:c.nullish(),LastUsedAt:c.nullish(),LinkType:oS.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),xp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:gp.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),PS=zod.z.object({Status:uS.nullish(),Tier:pS.nullish(),VerifiedAt:c.nullish(),ExpiresAt:c.nullish(),RejectedAt:c.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),IS=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),vS=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:zod.z.record(zod.z.string(),IS).nullish()}).passthrough(),TS=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),AS=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),PerCollection:zod.z.record(zod.z.string(),TS).nullish()}).passthrough(),kS=zod.z.object({Tokens:vS.nullish(),Nfts:AS.nullish()}).passthrough(),Yo=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Bt=zod.z.object({Granted:zod.z.boolean(),Mode:Ui.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:c.nullish(),Balances:zod.z.array(Yo).nullish()}).passthrough(),zS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:c.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:c.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(Yo).nullish()}).passthrough(),wS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),bp=zod.z.object({Mode:Ui.nullish(),TokenGates:zod.z.array(Sp).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(wS).nullish(),Status:Bt.nullish()}).passthrough(),MS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:c.nullish(),LoggedInAt:c.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(Yo).nullish()}).passthrough(),OS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:c.nullish()}).passthrough(),US=zod.z.object({Version:zod.z.number().nullish(),Stats:kS.nullish(),LinkedWallets:zod.z.record(zod.z.string(),DS).nullish(),LastWalletLogin:MS.nullish(),PlayAccess:zS.nullish(),PendingWithdrawals:zod.z.array(xp).nullish(),Kyc:PS.nullish(),FirstActivityAt:c.nullish(),LastActivityAt:c.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(OS).nullish()}).passthrough(),ES=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:c}).passthrough(),yi=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),ES).nullish(),PendingAdded:xp.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),qS=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough().transform(r=>r),LS=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Rp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Jo.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:c.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:c.nullish(),RefundCheckedAt:c.nullish()}).passthrough(),BS=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Rp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Jo.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:c.nullish()}).passthrough(),Dp=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Xo=zod.z.object({TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ContractAddress:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(Dp).nullish(),Signature:zod.z.string().nullish()}).passthrough(),ea=zod.z.object({Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),ProgramID:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(Dp).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Pp=zod.z.object({Blockchain:Zo.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),$o).nullish()}).passthrough(),Ip=zod.z.object({State:US.nullish(),CryptoBalances:zod.z.record(zod.z.string(),qS).nullish()}).passthrough(),vp=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:yi.nullish()}).passthrough(),Tp=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Ap=zod.z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:c.nullish(),EvmSignature:Xo.nullish(),SolanaSignature:ea.nullish(),StateDelta:yi.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),kp=zod.z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),EvmSignature:Xo.nullish(),SolanaSignature:ea.nullish(),StateDelta:yi.nullish(),Inventory:Q.nullish()}).passthrough(),zp=zod.z.object({TokenTransactions:zod.z.array(LS).nullish(),NFTTransactions:zod.z.array(BS).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),ta=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:zod.z.string().nullish()}).passthrough(),wp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:gp.nullish(),EvmSignature:Xo.nullish(),SolanaSignature:ea.nullish()}).passthrough(),Mp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:Jo.nullish(),StateDelta:yi.nullish()}).passthrough(),Qe={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 GS="Blockchain",Op="Blockchain:Definitions",kn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Op,e);if(t)return F(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return a;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(GS,n.data.Blockchain),this.ctx.data.config.patchSection(Op,n.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",n.data)),n)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,i,s,n){if(!e)return u("client","CurrencyID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return a;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=s,o.Category=An(n);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,i,s,n,o,p){if(!e)return u("client","ItemID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let d=this.ctx.authedRequest();if(!d)return a;d.ItemID=e,d.NetworkID=t,d.WalletAddress=i,d.Amount=s,d.Category=An(n),o!==void 0&&(d.Level=o),p&&(d.ItemInstanceID=p);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(d);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return a;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return u("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return u("client","TitleTransactionID is required.");if(!t)return u("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TitleTransactionID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var FS={Head:"Head",Torso:"Torso",Legs:"Legs"},zn=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),VS={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},ia=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Ep=zod.z.object({AttackTarget:zn,DefenseTarget:zn});var _S=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),NS=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:zn.nullish(),DefenseZone:zn.nullish(),HitType:_S.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),jS=zod.z.object({MaxHp:zod.z.number().nullish(),CurrentHp:zod.z.number().nullish(),Damage:zod.z.number().nullish(),AttackSpeed:zod.z.number().nullish(),CritChance:zod.z.number().nullish(),CritMultiplier:zod.z.number().nullish(),Armor:zod.z.number().nullish(),DodgeChance:zod.z.number().nullish()}).passthrough(),WS=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Up=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:Ao.nullish(),BattleStrategy:zod.z.array(Ep).nullish(),UnstackableItems:zod.z.record(zod.z.string(),WS).nullish(),Stats:jS.nullish()}).passthrough(),KS=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:ce.nullish(),NetReward:ce.nullish(),BattleLog:zod.z.array(NS).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:Up.nullish(),P2BattleProfile:Up.nullish()}).passthrough(),qp=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:c.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(Ep).nullish(),TargetUserID:zod.z.string().nullish(),Entry:ce.nullish(),CreationCostPaid:ce.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:c.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:c.nullish(),Status:ia.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:c.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:c.nullish()}).passthrough(),Lp=zod.z.object({Status:ia,MatchID:zod.z.string(),Entry:ce.nullish(),Resources:M.nullish()}),Bp=zod.z.object({Match:qp.nullish()}),Gp=zod.z.object({MatchID:zod.z.string(),Status:ia,Resources:M.nullish()}),Fp=zod.z.object({Battle:KS.nullish(),Resources:M.nullish(),ResourcesDual:bt.nullish()}),sa=zod.z.object({Matches:zod.z.array(qp).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),Rt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var QS=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var HS=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),$S=zod.z.object({HealthStatID:zod.z.string().nullish(),DamageStatID:zod.z.string().nullish(),ArmorStatID:zod.z.string().nullish(),AttackSpeedStatID:zod.z.string().nullish(),CritChanceStatID:zod.z.string().nullish(),CritDamageStatID:zod.z.string().nullish(),DodgeStatID:zod.z.string().nullish(),AllMightStatID:zod.z.string().nullish()}).passthrough(),JS=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),ZS=zod.z.object({MaxRounds:zod.z.number().nullish(),BlockDamageMultiplier:zod.z.number().nullish(),MinHitDamage:zod.z.number().nullish(),DefaultCritMultiplier:zod.z.number().nullish(),MaxCritChance:zod.z.number().nullish(),MaxDodgeChance:zod.z.number().nullish(),ArmorMode:JS.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),YS=zod.z.object({Kind:HS.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Fe.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),XS=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(YS).nullish()}).passthrough(),Qt=zod.z.object({Terms:zod.z.array(XS).nullish()}).passthrough(),ex=zod.z.object({Health:Qt.nullish(),Damage:Qt.nullish(),Armor:Qt.nullish(),AttackSpeed:Qt.nullish(),CritChance:Qt.nullish(),CritDamage:Qt.nullish(),Dodge:Qt.nullish()}).passthrough(),Vp=zod.z.object({StatMapping:$S.nullish(),Combat:ZS.nullish(),Formula:ex.nullish()}).passthrough(),tx=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),Ei=zod.z.object({Kind:QS.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:Wi.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),_p=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(Ei).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Np=zod.z.object({PriceOptions:ue.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Re.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),ix=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:tx.nullish(),Entry:_p.nullish(),Creation:Np.nullish(),Settings:Vp.nullish()}).passthrough(),sx=zod.z.object({Rules:zod.z.record(zod.z.string(),ix).nullish(),Defaults:Vp.nullish(),EntryDefaults:_p.nullish(),CreationDefaults:Np.nullish()}).passthrough(),na=zod.z.object({InstantBattle:sx.nullish()}).passthrough(),jp=na;var nx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},ra=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),rx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},oa=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),ox={Burn:"Burn",Ledger:"Ledger"},ax=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Mn={Item:"Item",VirtualCurrency:"VirtualCurrency"},aa=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),lx=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish()}).passthrough(),On=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(Ei).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),la=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish(),Sink:ax.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),lx).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),ux=zod.z.object({AllowedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedItemIDs:zod.z.array(zod.z.string()).nullish(),AllowUnstackableWithState:zod.z.boolean().nullish(),AllowedCurrencyIDs:zod.z.array(zod.z.string()).nullish(),DeniedCurrencyIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),cx=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Re.nullish(),BuyLimits:Re.nullish(),ListingFeeOptions:ue.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),px=zod.z.object({Enabled:zod.z.boolean().nullish(),MinDurationHours:zod.z.number().nullish(),MaxDurationHours:zod.z.number().nullish(),AntiSnipeWindowSeconds:zod.z.number().nullish(),AntiSnipeExtensionSeconds:zod.z.number().nullish(),MaxAntiSnipeExtensions:zod.z.number().nullish(),MinBidStepPercent:zod.z.number().nullish(),MinBidStepAbsolute:j.nullish(),BidLimits:Re.nullish()}).passthrough(),hx=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Re.nullish(),FillLimits:Re.nullish()}).passthrough(),dx=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Re.nullish()}).passthrough(),mx=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),ua=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),PricePolicy:On.nullish(),Commission:la.nullish(),Tradability:ux.nullish(),Listings:cx.nullish(),Auctions:px.nullish(),BuyOrders:hx.nullish(),DirectTrades:dx.nullish(),Matching:mx.nullish()}).passthrough(),Wp=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:j.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:c.nullish()}).passthrough(),fx=zod.z.object({BidAxisType:li.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:j.nullish(),CurrentBid:j.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(Wp).nullish()}).passthrough(),wn=zod.z.object({LastAt:c.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),gx=zod.z.object({Create:wn.nullish(),Buy:wn.nullish(),Sell:wn.nullish(),Bid:wn.nullish()}).passthrough(),yx=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Rx=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:yx.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),At=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:ra.nullish(),Status:oa.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Oe.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:aa.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),GoodsInstances:zod.z.array(Rx).nullish(),Price:ce.nullish(),Auction:fx.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),Cx=zod.z.object({GoodsType:aa.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(ra,j).nullish()}).passthrough(),Kp=zod.z.object({Definitions:ua.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),ca=zod.z.object({Offers:zod.z.array(At).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Qp=zod.z.object({Groups:zod.z.array(Cx).nullish()}).passthrough(),Hp=zod.z.object({Offer:At.nullish()}).passthrough(),at=zod.z.object({OfferID:zod.z.string().nullish(),Status:oa.nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:ce.nullish()}).passthrough(),qi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:At.nullish(),Resources:M.nullish(),Matched:zod.z.boolean().nullish(),Settlement:at.nullish()}).passthrough(),$p=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:j.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish()}).passthrough(),Un=zod.z.object({MyOffers:zod.z.array(At).nullish(),MyBids:zod.z.array(At).nullish(),MyBuyOrders:zod.z.array(At).nullish(),IncomingTrades:zod.z.array(At).nullish(),OutgoingTrades:zod.z.array(At).nullish(),Claimables:zod.z.array(At).nullish(),DrainedRefunds:zod.z.array(Wp).nullish(),Limits:gx.nullish()}).passthrough(),Sx=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:ra.nullish(),FinalStatus:oa.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:aa.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),PricePaid:ce.nullish(),CommissionTaken:ce.nullish(),CompletedAt:c.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),Jp=zod.z.object({Entries:zod.z.array(Sx).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),ke={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 xx="Marketplace",Zp={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"]},En=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Zp,{schema:Un,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(xx,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,s=20){if(!e)return u("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let o=await this.ctx.api.marketplace.getOffersByItem(n);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let s=this.ctx.authedRequest();if(!s)return a;s.ItemID=e,s.ContinuationToken=t,s.PageSize=i;let n=await this.ctx.api.marketplace.getBuyOrders(s);return n.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",n.data),n}getMyState(e,t){return this.ctx.cache.read(Zp,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,o,p){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let d=this.ctx.authedRequest();if(!d)return a;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.PriceBundle=s,d.DurationHours=n,d.ItemInstanceIDs=o,d.SelectedOptionID=p;let R=await this.ctx.api.marketplace.createListing(d);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,s,n,o,p={}){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");let d=this.ctx.authedRequest();if(!d)return a;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.BidAxisType=s,d.BidCurrencyID=p.bidCurrencyID,d.BidCatalogID=p.bidCatalogID,d.BidItemID=p.bidItemID,d.StartingBid=n,d.DurationHours=o,d.ItemInstanceIDs=p.itemInstanceIDs,d.SelectedOptionID=p.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(d);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return u("client","OfferID is required.");if(!t||t<=0)return u("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,s,n){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return a;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=s,o.DurationHours=n;let p=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,s,n){if(!e)return u("client","TargetUserID is required.");if(!t)return u("client","CatalogID is required.");if(!i)return u("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return a;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=s,o.RequestedBundle=n;let p=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return u("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(i);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return u("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=Mn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Mn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):u("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var qn=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return u("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let s=await this.ctx.api.multiplayer.createRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.RoomID=e,s.TargetUserID=t,s.Ban=i;let n=await this.ctx.api.multiplayer.kickMember(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",n.data),n}async unbanMember(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return a;i.Page=e,i.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(i);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,i,s){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");if(!i)return u("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let o=await this.ctx.api.multiplayer.sendSignal(n);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(i);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,i){if(!e)return u("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.RoomID=e,s.Ready=t,s.MemberState=i;let n=await this.ctx.api.multiplayer.setMemberState(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",n.data),n}};var Yp=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Ln=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):a}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return u("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):a}async getCreatorProfile(e,t,i){if(!e)return u("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):a}async publish(e){if(!e.files||e.files.length===0)return u("client","At least one file is required.");let t=new Map,i=e.files.map((d,R)=>{if("sourceAssetUrl"in d)return {Role:d.role,ContentType:d.contentType,SourceAssetUrl:d.sourceAssetUrl};let V=Xp(d.data,d.contentType);return t.set(R,V),{Role:d.role,ContentType:d.contentType,Size:V.size}}),s=e.thumbnail?Xp(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let o=n.data.Uploads??[];for(let d=0;d<o.length;d++){let R=o[d];if(!R||R.ServerCopy||!R.Url)continue;let V=t.get(d);if(!V)return u("client",`No bytes for file #${d+1}.`);let re=await this.putBytes(R.Url,V,R.ContentType??V.type);if(!re.ok)return re}let p=n.data.ThumbnailUpload;if(p?.Url&&s){let d=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!d.ok)return d}return this.publishUploaded({ContentID:n.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID})}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):a}async publishUploaded(e){if(!e.ContentID)return u("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return a;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let s=await this.ctx.api.workshop.updateContent(i);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getMyContent(s)):a}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let s=await this.ctx.api.workshop.acquire(i);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let s of t.data.Files??[])if(s.Url)try{let n=await this.ctx.fetchImpl(s.Url);if(!n.ok)return u("connection",`Download failed (HTTP ${n.status}).`);i.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await n.arrayBuffer()});}catch(n){return u("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${Yp}`)}return F({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):a}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):a}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?F(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${Yp}`)}}contentRequest(e){if(!e)return u("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):a}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function Xp(r,e){return r instanceof Blob?r:typeof r=="string"?new Blob([new TextEncoder().encode(r)],{type:e}):r instanceof Uint8Array?new Blob([r.slice().buffer],{type:e}):new Blob([r],{type:e})}var bx={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},Dx=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Px={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},eh=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),Ix={Everyone:"Everyone",Owner:"Owner",Server:"Server"},th=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),vx={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},Tx=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),Ax={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},kx=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),zx={Count:"Count",Sum:"Sum"},wx=zod.z.enum(["Count","Sum"]).catch("Count"),Mx={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Ox=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Ux={Strict:"Strict",Loose:"Loose"},Ex=zod.z.enum(["Strict","Loose"]).catch("Strict"),qx=zod.z.object({Kind:kx,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),Lx=zod.z.object({Type:eh,ItemType:eh.nullish(),Ref:qx.nullish(),Required:zod.z.boolean().optional(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),MaxItems:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish(),Unique:zod.z.boolean().optional(),UniqueIgnoreCase:zod.z.boolean().optional(),Indexed:zod.z.boolean().optional(),Visibility:th.optional(),ClientWritable:zod.z.boolean().nullish(),Immutable:zod.z.boolean().optional(),Description:zod.z.string().nullish(),AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxFileBytes:zod.z.number().nullish()}),Bx=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Bn=zod.z.object({Mode:Tx,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),Gx=zod.z.object({Read:zod.z.array(Bn).nullish(),Create:zod.z.array(Bn).nullish(),Update:zod.z.array(Bn).nullish(),Delete:zod.z.array(Bn).nullish()}),pa=zod.z.object({Cost:ce.nullish(),Grant:ce.nullish()}),Fx=zod.z.object({ID:zod.z.string(),SortKey:zod.z.string(),PartitionField:zod.z.string().nullish(),PageSize:zod.z.number().optional(),MaxItems:zod.z.number().optional(),PublishItems:zod.z.boolean().optional()}),Vx=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Namespace:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Enabled:zod.z.boolean().nullish(),Kind:Dx,Mode:Ex.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),Lx).nullish(),SortKeys:zod.z.array(Bx).nullish(),Access:Gx.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:Ox.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:wx,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:th.optional()})).nullish(),Economy:zod.z.object({OnCreate:pa.nullish(),OnUpdate:pa.nullish(),OnDelete:pa.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:zod.z.array(Fx).nullish(),AnonymousSearch:zod.z.boolean().nullish(),Integrations:zod.z.object({QuestMetricOnCreate:zod.z.string().nullish(),QuestMetricOnUpdate:zod.z.string().nullish(),QuestMetricOnDelete:zod.z.string().nullish(),AnalyticsEventOnCreate:zod.z.string().nullish(),AnalyticsEventOnUpdate:zod.z.string().nullish(),AnalyticsEventOnDelete:zod.z.string().nullish(),TriggerOnCreate:zod.z.string().nullish(),TriggerOnUpdate:zod.z.string().nullish(),TriggerOnDelete:zod.z.string().nullish()}).nullish(),Moderation:zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish()}).nullish()}),ih=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),Vx).default({})}),_x=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),sh=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),Ri=zod.z.object({Collection:zod.z.string(),ItemID:zod.z.string(),OwnerUserID:zod.z.string().nullish(),Data:zod.z.record(zod.z.string(),zod.z.unknown()).default({}),Version:zod.z.number(),CreatedAt:zod.z.string(),UpdatedAt:zod.z.string(),ExpireAt:zod.z.string().nullish(),Expanded:zod.z.record(zod.z.string(),zod.z.unknown()).nullish(),Files:zod.z.record(zod.z.string(),_x).nullish()}),ha=zod.z.object({Item:Ri}),nh=zod.z.object({Items:zod.z.array(Ri).default([]),Missing:zod.z.array(zod.z.string()).default([])}),da=zod.z.object({Items:zod.z.array(Ri).default([]),NextCursor:zod.z.string().nullish()}),rh=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),ma=zod.z.object({Item:Ri,AlreadyExists:zod.z.boolean().optional(),Economy:M.nullish()}),oh=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:M.nullish()}),ah=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),lh=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:Ri.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),uh=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),ch=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),ph=zod.z.object({Version:zod.z.string(),Collection:zod.z.string(),View:zod.z.string(),SortKey:zod.z.string().nullish(),PageSize:zod.z.number(),UpdatedAt:zod.z.string(),BaseUrl:zod.z.string(),Partitions:zod.z.record(zod.z.string(),zod.z.object({Segment:zod.z.string(),Pages:zod.z.number(),Total:zod.z.number()})).default({})}),hh=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(Ri).default([])}),Nx={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 jx=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,fh=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,ga=100,dh=25,mh=100;function Wx(r,e,t){return {Field:r,Op:e,Value:t}}var Gn=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(a)}get(e,t,i={}){let s=tt(e)??Li(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.get({...n,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let s=tt(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(o=>fh.test(o)))];return n.length?n.length>mh?Promise.resolve(u("client",`At most ${mh} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(u("client","At least one valid item id is required."))}query(e,t={},i={}){let s=tt(e)??fa(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],o=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:o,Limit:t.Limit??ga},i);if(!p.ok)return p;if(n.push(...p.data.Items),o=p.data.NextCursor??void 0,!o||n.length>=s)return F(n.slice(0,s))}}count(e,t={}){let i=tt(e)??fa(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,i={}){let s=tt(e)??(i.itemID?Li(i.itemID):null);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.create({...n,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,s={}){let n=tt(e)??Li(t);return n?Promise.resolve(n):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=tt(e)??Li(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.delete({...n,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(u("client","Operations are empty."));if(e.length>dh)return Promise.resolve(u("client",`At most ${dh} operations per batch.`));let t=e.map(i=>tt(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let s=tt(e);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.getCounter({...n,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,s){let n=tt(e);return n?Promise.resolve(n):t?s>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(u("client","File size must be positive.")):Promise.resolve(u("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,n,i.size);if(!o.ok)return o;let p=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||n);return p.ok?o:p}async getPublicViews(e){let t=tt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return F(i);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,i={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let n=s.data.Views[t];if(!n)return u("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(n,ph);if(!o.ok)return o;let p=o.data.Partitions[i.partition??""],d=Math.max(1,i.page??1);if(!p||d>p.Pages)return F({pointer:o.data,page:{Page:d,HasMore:false,Items:[]}});let R=await this.fetchJson(`${o.data.BaseUrl}${p.Segment}/page-${d}.json`,hh);return R.ok?F({pointer:o.data,page:R.data}):R}getPublic(e,t){let i=tt(e)??Li(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=tt(e)??fa(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(a)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?F(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return u("connection","Internet Connection Error")}if(!i.ok)return u("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return u("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?F(n.data):u("server","CDN answer has an unexpected shape.")}};function tt(r){return jx.test(r??"")?null:u("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function Li(r){return fh.test(r??"")?null:u("client",`Item id '${r}' is invalid.`)}function fa(r){return r.Limit!=null&&(r.Limit<1||r.Limit>ga)?u("client",`Limit must be 1..${ga}.`):(r.Where?.length??0)>8?u("client","At most 8 filters per query."):null}var ya={Open:"Open",Declared:"Declared"},Kx=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),Qx=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),gh=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Kx).nullish(),Dimensions:zod.z.array(Qx).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),Gt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Ct={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Fn=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Hx={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},$x=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),yh=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array($x).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Ra={LogEvents:"LogEvents"};function Rh(r,e=0){let t=r??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let p=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let p=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let n=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(n)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(n[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function Ch(r){let e=typeof navigator>"u"?void 0:navigator,t=Rh(e?.userAgent??"",e?.maxTouchPoints??0),i={};r.appVersion&&(i.AppVersion=r.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let s=r.locale||e?.language;return s&&(i.Language=s),i}var Jx=25,Zx=3e4,Sh=1800*1e3,xh=500,Yx=5,Xx=1e3,eb=3600*1e3,bh="idos_analytics_queue",Ca="idos_analytics_pending",Sa="idos_analytics_opt_out",Dh="idos_analytics_first_open",Ph="idos_analytics_last_activity",Ih="idos_analytics_last_context",vh="idos_analytics_owner",Vn=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Fn.test(e)?u("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):tb(e)?u("client",`Event name "${e}" uses a reserved prefix (${Ct.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return u("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Gt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return F(null);if(this.config()?.Enabled===false)return this.clear(),F(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return F(null);this.pending={BatchID:B(),Events:this.queue.splice(0,Ct.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=Yx)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Sa);return}this.write(Sa,"1"),this.clear();}get isEnabled(){return this.read(Sa)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(vh);e&&t&&t!==e&&this.clear(),e&&this.write(vh,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Zx),typeof window<"u"&&(window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide)),this.beginAutomatic(),this.flush();}async stop(){this.started&&(this.started=false,this.automaticDone=false,this.timer&&clearInterval(this.timer),this.drainTimer&&clearTimeout(this.drainTimer),this.timer=null,this.drainTimer=null,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null,typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),await this.flush());}beginAutomatic(){if(this.automaticDone||!this.started)return;if(this.config()?.Enabled!==true){this.stopWaitingForConfig??=this.ctx.emitter.on("title:publicConfigurationReceived",()=>this.beginAutomatic());return}this.automaticDone=true,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null;let e=Number(this.read(Ph)??"0");this.read(Dh)||(this.write(Dh,new Date().toISOString()),this.enqueue(Gt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Ih);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Gt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Gt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Ih,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Sh)&&this.enqueue(Gt.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=Sh&&this.enqueue(Gt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,s){if(!this.isEnabled||this.disabledByServer)return F(null);let n=this.config();if(n?.Enabled===false)return F(null);if(s&&n?.AutomaticEvents===false)return F(null);if(n?.Events?.[e]?.Blocked)return u("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===ya.Declared.toLowerCase()&&!n.Events?.[e])return u("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return u("client","value must be a finite number.");let o=ib(t);if(o.error)return u("client",o.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(p.Params=o.params),i!==void 0&&(p.Value=i),this.queue.push(p),this.queue.length>xh&&this.queue.splice(0,this.queue.length-xh),this.touch(),this.persist(),this.started&&this.queue.length>=Jx&&this.flush(),F(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},Xx));}dropStale(){let e=Date.now()-(Ct.maxEventAgeMs-eb);this.queue=this.queue.filter(t=>{let i=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(i)||i>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=Ch({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(bh);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(Ca);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(bh,this.queue),this.pending?this.writeJson(Ca,this.pending):this.remove(Ca);}touch(){this.write(Ph,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.platform.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.platform.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.platform.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function tb(r){let e=r.toLowerCase();return Ct.reservedPrefixes.some(t=>e.startsWith(t))}function ib(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>Ct.maxParams)return {error:`Too many parameters: ${e.length}, max ${Ct.maxParams}.`};let t={};for(let i of e){if(!Fn.test(i))return {error:`Invalid parameter name "${i}".`};let s=r[i];typeof s=="string"?t[i]=s.length>Ct.maxStringValueLength?s.slice(0,Ct.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var sb="idos_experiments",_n=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let o=this.views.get(s);(!o||o.VariantID!==n.VariantID||o.Status!==n.Status)&&i.push(n);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${sb}:${this.ctx.settings.titleID}`}};function Ft(r,e,t,i){let n=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var L=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Ft(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var Nn=class extends L{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Ra.LogEvents,e,yh,{silent:true})}};var nb=zod.z.object({VariantID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Weight:zod.z.number().nullish(),IsControl:zod.z.boolean().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},ob=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),ab=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Variants:zod.z.array(nb).nullish(),Salt:zod.z.string().nullish(),LayerID:zod.z.string().nullish(),StickyAssignment:zod.z.boolean().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Goals:zod.z.array(ob).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),Th=zod.z.object({Experiments:zod.z.record(zod.z.string(),ab).nullish()}).passthrough(),lb={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},ub=zod.z.object({ExperimentID:zod.z.string().nullish(),VariantID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ah=zod.z.object({Experiments:zod.z.array(ub).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),xa={GetExperiments:"GetExperiments"};var jn=class extends L{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(xa.GetExperiments,e,Ah)}};var kh=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:c.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:c,PlayAccess:Bt.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:c.nullish()}),zh=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:c,RefreshToken:zod.z.string(),RefreshTokenExpiration:c.nullish(),PlayAccess:Bt.nullish()}),cb=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),wh=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().nullish(),PlatformFallback:zod.z.boolean().nullish(),AndroidClientID:zod.z.string().nullish(),IosClientID:zod.z.string().nullish(),DesktopClientID:zod.z.string().nullish()}).passthrough().nullish(),Apple:zod.z.object({Enabled:zod.z.boolean().nullish(),BundleID:zod.z.string().nullish(),ServiceID:zod.z.string().nullish()}).passthrough().nullish(),PlayAccessMode:Ui.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:zod.z.boolean().nullish(),NativeSso:cb.nullish()}).passthrough(),Mh=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:c.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:Bt.nullish()}).passthrough(),Oh=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:c.nullish(),PlayAccess:Bt.nullish()}).passthrough(),Uh=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Ue=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:c.nullish()}),Eh=zod.z.object({Message:zod.z.string(),ExpiresAt:c}),Ee={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var Wn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Ft(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,kh,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ee.RefreshSession),e,zh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ee.GetAuthOptions),e,wh,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Ft(this.ctx.settings.titleID,"Authentication",Ee.LinkWallet,e.UserID??""),e,Mh,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Ft(this.ctx.settings.titleID,"Authentication",Ee.UnlinkWallet,e.UserID??""),e,Oh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ee.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ee.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ee.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ee.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ee.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ee.LoginWithSsoCode,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ee.RegisterWithEmail),e,Uh,{ticket:null})}confirmEmailRegistration(e){return this.login(Ee.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ee.ResendVerificationCode),e,Ue,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ee.RequestWalletChallenge),e,Eh,{ticket:null})}loginWithWallet(e){return this.login(Ee.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ee.ForgotPassword),e,Ue,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ee.ResetPassword),e,Ue,{ticket:null})}};var pb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},qh=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),hb=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),Lh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),hb).nullish(),MissingKeyMode:qh.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),db=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),Bh=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:db.nullish()}).passthrough(),Kn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},mb=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),Gh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:qh.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(mb).nullish()}).passthrough(),Fh=zod.z.object({RequestedLocale:zod.z.string().nullish(),Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),NotModified:zod.z.boolean().nullish(),Entries:zod.z.record(zod.z.string(),zod.z.string()).nullish(),FallbackLocale:zod.z.string().nullish(),FallbackVersion:zod.z.number().nullish()}).passthrough();var ba=zod.z.object({TitleConfigVersion:zod.z.string().nullish(),TitleConfigUrl:zod.z.string().nullish(),User:zod.z.unknown().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish(),Localization:Bh.nullish(),Views:zod.z.array(zod.z.object({Name:zod.z.string(),Key:zod.z.string().nullish(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(r=>r),Vh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(r=>r),_h=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),User:zod.z.unknown().nullish()}).passthrough().transform(r=>r),Nh=zod.z.object({}).passthrough().transform(r=>r),jh=zod.z.object({}).passthrough().transform(r=>r),Wh=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:c.nullish(),LastActiveAt:c.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),Kh=zod.z.object({Username:zod.z.string()}),lt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Qn=class extends L{constructor(e){super(e,"User");}getClientState(e){return this.send(lt.GetClientState,e,ba)}getClientStateExcept(e){return this.send(lt.GetClientStateExcept,e,ba)}getStateVersions(e){return this.send(lt.GetStateVersions,e,Vh)}getUserState(e){return this.send(lt.GetUserState,e,_h)}getInventory(e){return this.send(lt.GetInventory,e,Nh)}getEventTokens(e){return this.send(lt.GetEventTokens,e,jh)}getUsageTime(e){return this.send(lt.GetUsageTime,e,Wh)}addUsageTime(e){return this.send(lt.AddUsageTime,e,Ue,{silent:true})}deleteUserAccount(e){return this.send(lt.DeleteUserAccount,e,Ue)}changeUsername(e){return this.send(lt.ChangeUsername,e,Kh)}};var Hn=class extends L{constructor(e){super(e,"Currency");}convert(e){return this.send(vn.Convert,e,pp)}cryptoConvert(e){return this.send(vn.CryptoConvert,e,hp)}};var fb=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),Da=zod.z.object({ServerTimeUtc:c,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:M.nullish(),FodderConsumed:zod.z.array(fb).nullish()}),Qh=zod.z.array(ve(Da)),$n={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},gb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},yb=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Rb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Cb=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Sb=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),xb=zod.z.object({Networks:zod.z.record(zod.z.string(),Sb).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),bb=zod.z.object({FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),Db=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),UseRequirements:zod.z.record(zod.z.string(),zod.z.number()).nullish(),AllowedCharacterIDs:zod.z.array(zod.z.string()).nullish(),AllowedSlotIDs:zod.z.array(zod.z.string()).nullish(),IdleRateBonus:zod.z.number().nullish()}).passthrough(),Pb=zod.z.object({ValuationMode:yb.nullish(),WeightCurve:Fe.nullish(),Selection:Cb.nullish()}).passthrough(),Ib=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Fe.nullish(),FlatBonusCurve:Fe.nullish(),PercentBonusCurve:Fe.nullish(),PowerCurve:Fe.nullish(),Fodder:Pb.nullish()}).passthrough(),vb=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),Tb=zod.z.object({ItemID:zod.z.string(),CatalogID:zod.z.string(),ItemClass:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsStackable:zod.z.boolean().nullish(),IsTradable:zod.z.boolean().nullish(),Weight:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),NFT:xb.nullish(),Stats:bb.nullish(),Equipment:Db.nullish(),Upgrade:Ib.nullish(),Metadata:vb.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),Ab=zod.z.object({Items:zod.z.record(zod.z.string(),Tb).nullish()}).passthrough(),Jn=zod.z.object({Catalogs:zod.z.record(zod.z.string(),Ab).nullish()}).passthrough();var Zn=class extends L{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send($n.UpgradeLevel,e,Da)}upgradeLevelsBatch(e){return this.send($n.UpgradeLevelsBatch,e,Qh)}};var Yn=class extends L{constructor(e){super(e,"Store");}purchase(e){return this.send(Wt.Purchase,e,ho)}purchaseBatch(e){return this.send(Wt.PurchaseBatch,e,$l)}getDefinitions(e){return this.send(Wt.GetDefinitions,e,Rs)}getUserState(e){return this.send(Wt.GetUserState,e,Jl)}getStorefront(e){return this.send(Wt.GetStorefront,e,Cs)}};var kb={Apple:"Apple",Google:"Google"},Xn=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),er=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),Xn).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(r=>r),zb=zod.z.object({PremiumID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Tier:zod.z.number().nullish(),DurationDays:zod.z.number().nullish(),TrialDurationDays:zod.z.number().nullish(),PriceOptions:ue.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Pa=zod.z.object({Definitions:zod.z.record(zod.z.string(),zb).nullish()}).passthrough(),Hh=zod.z.object({Premium:Pa.nullish()}),$h=zod.z.object({ServerTimeUtc:c.nullish(),Premium:er.nullish()}),tr=zod.z.object({ServerTimeUtc:c.nullish(),Premium:er.nullish(),Subscription:Xn.nullish(),Resources:M.nullish()}),Ht={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var wb={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},Mb=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Jh=zod.z.object({StartUtc:c.nullish(),EndUtc:c.nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Ia=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),Ob=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),Ub=zod.z.object({Rewards:K.nullish(),Rules:K.nullish(),Refund:K.nullish()}).passthrough(),Eb=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:Mb.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:Jh.nullish(),Refund:Ia.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:Ob.nullish(),Presets:Ub.nullish()}).passthrough(),qb=zod.z.object({StoreID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),PackageName:zod.z.string().nullish(),VerificationMode:zod.z.string().nullish(),PlayPublicKey:zod.z.string().nullish(),RequireCertificateChain:zod.z.boolean().nullish(),SecretName:zod.z.string().nullish(),IssuerID:zod.z.string().nullish(),KeyID:zod.z.string().nullish(),AcknowledgePurchases:zod.z.boolean().nullish(),NotificationPackageName:zod.z.string().nullish()}).passthrough(),Lb=zod.z.object({Rewards:H.nullish()}).passthrough(),Bb=zod.z.object({Rules:Jh.nullish()}).passthrough(),Gb=zod.z.object({Refund:Ia.nullish()}).passthrough(),Fb=zod.z.object({Rewards:zod.z.record(zod.z.string(),Lb).nullish(),Rules:zod.z.record(zod.z.string(),Bb).nullish(),Refund:zod.z.record(zod.z.string(),Gb).nullish()}).passthrough(),Vb=zod.z.object({MaxPurchaseAgeDays:zod.z.number().nullish(),AllowSandbox:zod.z.boolean().nullish(),RequirePackageMatch:zod.z.boolean().nullish(),MaxReceiptsPerBatch:zod.z.number().nullish(),RefundCheckHorizonDays:zod.z.number().nullish(),RejectCrossUserReceipts:zod.z.boolean().nullish()}).passthrough(),_b=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),Eb).nullish(),Stores:zod.z.record(zod.z.string(),qb).nullish(),Presets:Fb.nullish(),Validation:Vb.nullish(),Refund:Ia.nullish()}).passthrough(),Zh=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:c.nullish(),LastPurchasedAt:c.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Yh=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:c.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:c.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:c.nullish()}).passthrough(),Nb=zod.z.object({Products:zod.z.record(zod.z.string(),Zh).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Yh).nullish(),LastRefundCheckAt:c.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:c.nullish(),LastPurchaseAt:c.nullish()}).passthrough(),jb=zod.z.object({ProductID:zod.z.string(),Available:zod.z.boolean(),Owned:zod.z.boolean(),Blocked:zod.z.boolean(),Reason:zod.z.string().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Xh=zod.z.object({ServerTimeUtc:c,Purchase:_b.nullish(),Availability:zod.z.array(jb).nullish()}),ed=zod.z.object({ServerTimeUtc:c,Purchase:Nb.nullish()}),Wb={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},Kb=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),va=zod.z.object({ServerTimeUtc:c,Store:ji.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:Kb.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),ProductState:Zh.nullish(),Premium:er.nullish(),Subscription:Xn.nullish(),SubscriptionMirror:Yh.nullish()}).passthrough(),td=zod.z.object({ServerTimeUtc:c,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:c.nullish()}).passthrough(),id=ft(va),$t={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var ir=class extends L{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send($t.GetDefinitions,e,Xh)}getUserState(e){return this.send($t.GetUserState,e,ed)}validatePurchase(e){return this.send($t.ValidatePurchase,e,va)}validatePurchasesBatch(e){return this.send($t.ValidatePurchasesBatch,e,id)}createTelegramInvoice(e){return this.send($t.CreateTelegramInvoice,e,td)}};var Qb=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),sd=zod.z.object({Reward:H.nullish(),Weight:zod.z.number().nullish(),AmountRange:Qb.nullish()}).passthrough(),Ci=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(sd).nullish()}).passthrough(),Si=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(sd).nullish()}).passthrough(),Hb=zod.z.object({RewardSlots:zod.z.array(Ci).nullish()}).passthrough(),$b=zod.z.object({PityRules:zod.z.array(Si).nullish()}).passthrough(),sr=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),Hb).nullish(),PityPresets:zod.z.record(zod.z.string(),$b).nullish()}).passthrough();var Jb=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),nd=zod.z.object({ServerTimeUtc:c,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:zod.z.array(M).nullish(),TriggeredPity:zod.z.array(Jb).nullish()}),Zb=zod.z.object({RewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),Yb=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:j.nullish()}).passthrough(),Xb=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ue.nullish(),RewardSlots:zod.z.array(Ci).nullish(),PityRules:zod.z.array(Si).nullish(),Presets:Zb.nullish(),RewardMultiplier:Ki.nullish(),SupplyLimits:zod.z.array(Yb).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),eD=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Ta=zod.z.object({Definitions:zod.z.record(zod.z.string(),Xb).nullish(),RewardPools:sr.nullish(),Settings:eD.nullish()}).passthrough(),rd=zod.z.object({LootboxDefinitions:Ta.nullish()}),nr={GetDefinitions:"GetDefinitions",Open:"Open"};var rr=class extends L{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(nr.GetDefinitions,e,rd)}open(e){return this.send(nr.Open,e,nd)}};var tD=zod.z.object({}).passthrough().transform(r=>r),iD=zod.z.object({}).passthrough().transform(r=>r),sD=zod.z.object({}).passthrough().transform(r=>r),nD=zod.z.object({}).passthrough().transform(r=>r),rD=zod.z.object({}).passthrough().transform(r=>r),od=zod.z.object({ServerTimeUtc:c,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:tD,Resources:M.nullish(),Inventory:Q.nullish()}),ad=zod.z.object({ServerTimeUtc:c,AccrualID:zod.z.string(),AccruedSeconds:j.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:iD,Resources:M.nullish(),Inventory:Q.nullish()}),ld=zod.z.object({ServerTimeUtc:c,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:sD,Resources:M.nullish(),Inventory:Q.nullish()}),ud=zod.z.object({ServerTimeUtc:c,ClaimID:zod.z.string(),ClaimState:nD,Resources:M.nullish(),Inventory:Q.nullish()}),cd=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:j.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),oD=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),aD=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:H.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Bi=zod.z.object({Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Aa=zod.z.object({Availability:K.nullish()}).passthrough(),lD=zod.z.object({Availability:zod.z.record(zod.z.string(),Bi).nullish()}).passthrough(),uD=zod.z.object({CalendarID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Days:zod.z.array(aD).nullish(),IsLooping:zod.z.boolean().nullish(),MissBehavior:zod.z.string().nullish(),ResetByDays:zod.z.number().nullish(),MissThresholdMultiplier:zod.z.number().nullish(),ClaimMode:zod.z.string().nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),Availability:Bi.nullish(),Presets:Aa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),cD=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),pD=zod.z.object({BaseRatePerSecond:zod.z.number().nullish(),PowerCoefficient:zod.z.number().nullish(),BoardRankCoefficient:zod.z.number().nullish(),EquipmentBonusEnabled:zod.z.boolean().nullish(),EquipmentCharacterID:zod.z.string().nullish(),PremiumMultipliers:zod.z.array(cD).nullish()}).passthrough(),hD=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Bi.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),dD=zod.z.object({AccrualID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rate:pD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:hD.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),mD=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:H.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),fD=zod.z.object({ComebackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(mD).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Bi.nullish(),Presets:Aa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),gD=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxClaimsPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish(),TotalClaimLimit:zod.z.number().nullish()}).passthrough(),yD=zod.z.object({ClaimID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Mode:zod.z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:zod.z.array(gD).nullish(),Availability:Bi.nullish(),Presets:Aa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),ka=zod.z.object({TierRewards:oD.nullish(),MilestoneRewardMultiplier:Ki.nullish(),DailyCalendars:zod.z.record(zod.z.string(),uD).nullish(),IdleAccruals:zod.z.record(zod.z.string(),dD).nullish(),Comebacks:zod.z.record(zod.z.string(),fD).nullish(),Claims:zod.z.record(zod.z.string(),yD).nullish(),Presets:lD.nullish()}).passthrough(),pd=zod.z.object({RewardDefinitions:ka.nullish()}),hd=zod.z.object({Rewards:rD.nullish()}),kt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var or=class extends L{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(kt.GetRewardDefinitions,e,pd)}getUserRewardsState(e){return this.send(kt.GetUserRewardsState,e,hd)}getMilestoneRewardMultiplier(e){return this.send(kt.GetMilestoneRewardMultiplier,e,cd)}claimDailyReward(e){return this.send(kt.ClaimDailyReward,e,od)}collectIdleAccrual(e){return this.send(kt.CollectIdleAccrual,e,ad)}claimComebackReward(e){return this.send(kt.ClaimComebackReward,e,ld)}claimReward(e){return this.send(kt.ClaimReward,e,ud)}};var ar=class extends L{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(nt.GetTutorialDefinitions,e,kl)}getUserTutorialState(e){return this.send(nt.GetUserTutorialState,e,$i)}startFlow(e){return this.send(nt.StartFlow,e,wt)}reportStepShown(e){return this.send(nt.ReportStepShown,e,wt)}completeStep(e){return this.send(nt.CompleteStep,e,wt)}completeStepsBatch(e){return this.send(nt.CompleteStepsBatch,e,Ml)}skipStep(e){return this.send(nt.SkipStep,e,wt)}skipFlow(e){return this.send(nt.SkipFlow,e,wt)}claimFlowReward(e){return this.send(nt.ClaimFlowReward,e,wl)}resetFlow(e){return this.send(nt.ResetFlow,e,wt)}};var RD={Open:"Open",Application:"Application"},CD=zod.z.enum(["Open","Application"]).catch("Open"),SD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},dd=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),xD={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},za=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),bD={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var Jt={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},DD=zod.z.object({CampaignID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IsRunning:zod.z.boolean().nullish()}).passthrough(),md=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:CD.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:dd.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(DD).nullish()}).passthrough(),PD=zod.z.object({Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),CountedMetrics:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ReachedMilestones:zod.z.array(zod.z.string()).nullish(),CappedBySubmissionLimit:zod.z.boolean().nullish(),CappedByCreatorLimit:zod.z.boolean().nullish(),NotPaidAsCopy:zod.z.boolean().nullish()}).passthrough(),ID=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:za.nullish(),CurrencyID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),Granted:zod.z.number().nullish(),Paid:zod.z.number().nullish(),Overpaid:zod.z.number().nullish(),Claimable:zod.z.number().nullish(),BySubmission:zod.z.record(zod.z.string(),PD).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),vD=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:za.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),fd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(ID).nullish(),Payouts:zod.z.array(vD).nullish()}).passthrough(),gd=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:za.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),TD=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),AD=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),Signature:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(TD).nullish()}).passthrough(),kD=zod.z.object({Kind:zod.z.string().nullish(),Target:zod.z.string().nullish(),Required:zod.z.number().nullish(),Actual:zod.z.number().nullish(),Passed:zod.z.boolean().nullish()}).passthrough(),yd=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:dd.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(kD).nullish()}).passthrough(),zD=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),wD=zod.z.object({ProgramID:zod.z.string().nullish(),Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(zD).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Rd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:zod.z.number().nullish(),NetAmountNative:zod.z.number().nullish(),BurnAmountNative:zod.z.number().nullish(),AmountUsd:zod.z.number().nullish(),ExpiresAt:zod.z.string().nullish(),EvmSignature:AD.nullish(),SolanaSignature:wD.nullish(),StateDelta:yi.nullish()}).passthrough();var lr=class extends L{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(Jt.GetCommunityMarketingState,e,md)}getEarnings(e){return this.send(Jt.GetEarnings,e,fd)}claim(e){return this.send(Jt.Claim,e,gd)}checkJoinEligibility(e){return this.send(Jt.CheckJoinEligibility,e,yd)}withdrawCryptoReward(e){return this.send(Jt.WithdrawCryptoReward,e,Rd)}};var ur=class extends L{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Ke.GetChatDefinitions,e,fu)}getChannels(e){return this.send(Ke.GetChannels,e,zs)}poll(e){return this.send(Ke.Poll,e,gu)}getHistory(e){return this.send(Ke.GetHistory,e,yu)}getConversations(e){return this.send(Ke.GetConversations,e,Su)}sendMessage(e){return this.send(Ke.SendMessage,e,Ru)}openDirectChannel(e){return this.send(Ke.OpenDirectChannel,e,Cu)}markRead(e){return this.send(Ke.MarkRead,e,fi)}joinChannel(e){return this.send(Ke.JoinChannel,e,fi)}leaveChannel(e){return this.send(Ke.LeaveChannel,e,fi)}reportMessage(e){return this.send(Ke.ReportMessage,e,xu)}ignoreUser(e){return this.send(Ke.IgnoreUser,e,fi)}unignoreUser(e){return this.send(Ke.UnignoreUser,e,fi)}};var cr=class extends L{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(gi.GetPushConfig,e,Pu)}subscribePush(e){return this.send(gi.SubscribePush,e,So)}unsubscribePush(e){return this.send(gi.UnsubscribePush,e,Ue)}getPushSubscriptions(e){return this.send(gi.GetPushSubscriptions,e,Iu)}};var pr=class extends L{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send(Kn.GetLocalizationManifest,e,Gh)}getLocalizationTable(e){return this.send(Kn.GetLocalizationTable,e,Fh)}};var hr=class extends L{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(pt.GetQuestDefinitions,e,Hi)}getUserQuestState(e){return this.send(pt.GetUserQuestState,e,yl)}refreshQuestCycles(e){return this.send(pt.RefreshQuestCycles,e,Ue)}claimQuestReward(e){return this.send(pt.ClaimQuestReward,e,eo)}claimQuestRewardsBatch(e){return this.send(pt.ClaimQuestRewardsBatch,e,Sl)}claimMilestoneReward(e){return this.send(pt.ClaimMilestoneReward,e,to)}claimMilestoneRewardsBatch(e){return this.send(pt.ClaimMilestoneRewardsBatch,e,xl)}claimGroupCompletionReward(e){return this.send(pt.ClaimGroupCompletionReward,e,Rl)}addQuestProgress(e){return this.send(pt.AddQuestProgress,e,Cl)}};var dr=class extends L{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ot.GetActiveEvents,e,Ls)}getDefinitions(e){return this.send(ot.GetDefinitions,e,qs)}getUserLteState(e){return this.send(ot.GetUserLteState,e,ku)}grantTokens(e){return this.send(ot.GrantTokens,e,M)}spendTokens(e){return this.send(ot.SpendTokens,e,Do)}claimMilestone(e){return this.send(ot.ClaimMilestone,e,Po)}claimMilestonesBatch(e){return this.send(ot.ClaimMilestonesBatch,e,Io)}claimAllMilestones(e){return this.send(ot.ClaimAllMilestones,e,Io)}spendTokensBatch(e){return this.send(ot.SpendTokensBatch,e,zu)}grantTokensBatch(e){return this.send(ot.GrantTokensBatch,e,wu)}};var mr=class extends L{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ve.GetDefinitions,e,js)}getLeaderboard(e){return this.send(Ve.GetLeaderboard,e,ki)}getMyProgress(e){return this.send(Ve.GetMyProgress,e,Gs)}submitScore(e){return this.send(Ve.SubmitScore,e,Fs)}submitScoreFromSource(e){return this.send(Ve.SubmitScoreFromSource,e,Fs)}claimCycleReward(e){return this.send(Ve.ClaimCycleReward,e,Vs)}claimMilestone(e){return this.send(Ve.ClaimMilestone,e,_s)}getFriendsLeaderboard(e){return this.send(Ve.GetFriendsLeaderboard,e,ki)}getLeaderboardsBatch(e){return this.send(Ve.GetLeaderboardsBatch,e,Uu)}getProgressBatch(e){return this.send(Ve.GetProgressBatch,e,Ns)}claimCycleRewardsBatch(e){return this.send(Ve.ClaimCycleRewardsBatch,e,Eu)}claimMilestonesBatch(e){return this.send(Ve.ClaimMilestonesBatch,e,qu)}submitScoresBatch(e){return this.send(Ve.SubmitScoresBatch,e,Lu)}claimAllRewardsBatch(e){return this.send(Ve.ClaimAllRewardsBatch,e,Bu)}getOverviewBatch(e){return this.send(Ve.GetOverviewBatch,e,Gu)}};var fr=class extends L{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Ut.GetDefinitions,e,Qs)}getActiveSeason(e){return this.send(Ut.GetActiveSeason,e,Ks)}getUserState(e){return this.send(Ut.GetUserState,e,vo)}grantStatusTokens(e){return this.send(Ut.GrantStatusTokens,e,Nu)}claimTierReward(e){return this.send(Ut.ClaimTierReward,e,To)}claimTierRewardsBatch(e){return this.send(Ut.ClaimTierRewardsBatch,e,ju)}};var gr=class extends L{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Ht.GetDefinitions,e,Hh)}getUserState(e){return this.send(Ht.GetUserState,e,$h)}activateTrial(e){return this.send(Ht.ActivateTrial,e,tr)}purchaseItemOrCurrency(e){return this.send(Ht.PurchaseWithResources,e,tr)}purchaseRealMoney(e){return this.send(Ht.PurchaseRealMoney,e,tr)}};var yr=class extends L{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(_e.GetCharacterDefinitions,e,Zs)}getUserCharacters(e){return this.send(_e.GetUserCharacters,e,Ju)}unlockCharacter(e){return this.send(_e.UnlockCharacter,e,wo)}upgradeStatLevel(e){return this.send(_e.UpgradeStatLevel,e,ko)}upgradeCharacterLevel(e){return this.send(_e.UpgradeCharacterLevel,e,zo)}equipItems(e){return this.send(_e.EquipItems,e,Zu)}unequipItems(e){return this.send(_e.UnequipItems,e,Yu)}unequipAllCharacters(e){return this.send(_e.UnequipAllCharacters,e,Xu)}unlockCharactersBatch(e){return this.send(_e.UnlockCharactersBatch,e,nc)}upgradeCharacterLevelsBatch(e){return this.send(_e.UpgradeCharacterLevelsBatch,e,rc)}upgradeStatLevelsBatch(e){return this.send(_e.UpgradeStatLevelsBatch,e,oc)}unlockSkin(e){return this.send(_e.UnlockSkin,e,ec)}equipSkin(e){return this.send(_e.EquipSkin,e,tc)}unequipSkin(e){return this.send(_e.UnequipSkin,e,ic)}getCharacterSkins(e){return this.send(_e.GetCharacterSkins,e,sc)}};var Rr=class extends L{constructor(e){super(e,"Match");}createMatch(e){return this.send(Rt.CreateMatch,e,Lp)}updateMatch(e){return this.send(Rt.UpdateMatch,e,Bp)}cancelMatch(e){return this.send(Rt.CancelMatch,e,Gp)}instantBattle(e){return this.send(Rt.InstantBattle,e,Fp)}saveStrategy(e){return this.send(Rt.SaveStrategy,e,Ue)}getMyMatches(e){return this.send(Rt.GetMyMatches,e,sa)}getAvailableMatches(e){return this.send(Rt.GetAvailableMatches,e,sa)}getDefinitions(e){return this.send(Rt.GetDefinitions,e,jp)}};var MD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Cd=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),OD={None:"None",Min:"Min",Average:"Average",Max:"Max"},UD=zod.z.enum(["None","Min","Average","Max"]).catch("None"),ED={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},qD=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),LD={Clamp:"Clamp",Reject:"Reject"},BD=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),GD=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),FD=zod.z.object({Index:zod.z.number().nullish(),BurnedItemIDs:zod.z.array(zod.z.string()).nullish(),RolledCollectionID:zod.z.string().nullish(),UsedCollections:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Output:Zr.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(GD).nullish()}),Sd=zod.z.object({ServerTimeUtc:c,Type:Cd.nullish(),CraftID:zod.z.string(),CraftedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),InputRarity:zod.z.string().nullish(),OutputRarity:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:zod.z.array(FD).nullish()}),VD=zod.z.object({CraftID:zod.z.string().nullish(),Type:Cd.nullish(),CatalogID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),InputRarityID:zod.z.string().nullish(),OutputRarityID:zod.z.string().nullish(),RequiredItemCount:zod.z.number().nullish(),PriceOptions:ue.nullish(),OutputLevelMode:UD.nullish(),InputSelection:qD.nullish(),OutputLevelOverflow:BD.nullish()}).passthrough(),wa=zod.z.object({Definitions:zod.z.record(zod.z.string(),VD).nullish()}).passthrough(),xd=zod.z.object({ServerTimeUtc:c.nullish(),CraftDefinitions:wa.nullish()}),Cr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Sr=class extends L{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Cr.GetDefinitions,e,xd)}craft(e){return this.send(Cr.Craft,e,Sd)}};var _D=2e5,xr=class extends L{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,tn,{timeoutMs:_D,autoRetry:false})}readGeneration(e,t){return this.send(e,t,tn,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Ge.GetDefinitions,e,fc)}generateText(e){return this.generate(Ge.GenerateText,e)}getText(e){return this.readGeneration(Ge.GetText,e)}generateImage(e){return this.generate(Ge.GenerateImage,e)}editImage(e){return this.generate(Ge.EditImage,e)}getImage(e){return this.readGeneration(Ge.GetImage,e)}generateVideo(e){return this.generate(Ge.GenerateVideo,e)}getVideo(e){return this.readGeneration(Ge.GetVideo,e)}generateAudio(e){return this.generate(Ge.GenerateAudio,e)}getAudio(e){return this.readGeneration(Ge.GetAudio,e)}generateMusic(e){return this.generate(Ge.GenerateMusic,e)}getMusic(e){return this.readGeneration(Ge.GetMusic,e)}generateThreeD(e){return this.generate(Ge.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Ge.GetThreeD,e)}listGenerations(e){return this.send(Ge.ListGenerations,e,mc)}getGeneration(e){return this.readGeneration(Ge.GetGeneration,e)}};var ND={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},jD=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),bd=zod.z.object({}).passthrough().transform(r=>r),xi=zod.z.object({CollectibleID:zod.z.string(),Rarity:zod.z.number().nullish(),IsSpecial:zod.z.boolean().nullish(),IsDuplicate:zod.z.boolean().nullish(),CollectionCurrencyConverted:zod.z.number().nullish()}),Dd=zod.z.object({GrantedCollectibles:zod.z.array(xi).nullish(),DuplicateCollectibles:zod.z.array(xi).nullish(),CollectionCurrencyEarned:j.nullish()}),Pd=zod.z.object({OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(Dd).nullish(),GrantedCollectibles:zod.z.array(xi).nullish(),DuplicateCollectibles:zod.z.array(xi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Id=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(Dd).nullish(),GrantedCollectibles:zod.z.array(xi).nullish(),DuplicateCollectibles:zod.z.array(xi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),vd=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ma=zod.z.object({SetID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Td=zod.z.array(ve(Ma)),Ad=zod.z.object({Resources:M.nullish(),Inventory:Q.nullish()}),WD=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:Oe.nullish(),OfferedCollectibleID:zod.z.string().nullish(),OfferedCollectibleIsSpecial:zod.z.boolean().nullish(),ReceiverUserID:zod.z.string().nullish(),RequestedCollectibleID:zod.z.string().nullish(),RequestedCollectibleIsSpecial:zod.z.boolean().nullish(),Status:jD.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RespondedAtUtc:c.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),kd=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:c.nullish(),Resources:M.nullish()}),zd=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),wd=zod.z.object({OfferID:zod.z.string(),ReceivedCollectibleID:zod.z.string().nullish(),ReceivedIsSpecial:zod.z.boolean().nullish(),SentCollectibleID:zod.z.string().nullish(),SentCollectibleIsSpecial:zod.z.boolean().nullish(),Transfer:zod.z.unknown().nullish()}),Md=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),Oa=zod.z.object({Offers:zod.z.array(WD).nullish()}),KD=zod.z.object({CollectibleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rarity:zod.z.number().nullish(),HasSpecialVersion:zod.z.boolean().nullish(),SortOrder:zod.z.number().nullish()}).passthrough(),QD=zod.z.object({SetID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SortOrder:zod.z.number().nullish(),Collectibles:zod.z.array(KD).nullish(),SetCompletionReward:H.nullish()}).passthrough(),HD=zod.z.object({CollectionID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SeasonChainID:zod.z.string().nullish(),Sets:zod.z.array(QD).nullish(),GrandPrize:H.nullish()}).passthrough(),Od=zod.z.object({BonusRewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),$D=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:ue.nullish(),BonusRewardSlots:zod.z.array(Ci).nullish(),PityRules:zod.z.array(Si).nullish(),Presets:Od.nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectibleCount:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),GuaranteeMaxRarity:zod.z.boolean().nullish(),RarityWeights:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ColorTier:zod.z.number().nullish()}).passthrough(),JD=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),ZD=zod.z.object({CollectionChestID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectionCurrencyCost:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),MinCollectibleCount:zod.z.number().nullish(),MaxCollectibleCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),BonusRewardSlots:zod.z.array(Ci).nullish(),PityRules:zod.z.array(Si).nullish(),Presets:Od.nullish(),Tier:zod.z.number().nullish()}).passthrough(),YD=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),XD=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),br=zod.z.object({Collections:zod.z.record(zod.z.string(),HD).nullish(),PackTypes:zod.z.record(zod.z.string(),$D).nullish(),CollectionChests:zod.z.array(ZD).nullish(),DuplicateConversions:zod.z.array(JD).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(YD).nullish(),RewardPools:sr.nullish(),Settings:XD.nullish()}).passthrough(),Ne={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var Dr=class extends L{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ne.GetDefinitions,e,br)}getUserState(e){return this.send(Ne.GetUserState,e,bd)}openPack(e){return this.send(Ne.OpenPack,e,Pd)}openCollectionChest(e){return this.send(Ne.OpenCollectionChest,e,Id)}useCollectibleJoker(e){return this.send(Ne.UseCollectibleJoker,e,vd)}claimSetReward(e){return this.send(Ne.ClaimSetReward,e,Ma)}claimSetRewardsBatch(e){return this.send(Ne.ClaimSetRewardsBatch,e,Td)}claimGrandPrize(e){return this.send(Ne.ClaimGrandPrize,e,Ad)}sendTradeOffer(e){return this.send(Ne.SendTradeOffer,e,kd)}cancelTradeOffer(e){return this.send(Ne.CancelTradeOffer,e,zd)}acceptTradeOffer(e){return this.send(Ne.AcceptTradeOffer,e,wd)}declineTradeOffer(e){return this.send(Ne.DeclineTradeOffer,e,Md)}getMyTradeOffers(e){return this.send(Ne.GetMyTradeOffers,e,Oa)}getIncomingTradeOffers(e){return this.send(Ne.GetIncomingTradeOffers,e,Oa)}};var Pr=class extends L{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ht.GetDefinitions,e,on)}getActiveEvent(e){return this.send(ht.GetActiveEvent,e,Rc)}getUserState(e){return this.send(ht.GetUserState,e,rn)}getGroupState(e){return this.send(ht.GetGroupState,e,Lo)}joinOrCreateGroup(e){return this.send(ht.JoinOrCreateGroup,e,Lo)}spin(e){return this.send(ht.Spin,e,Sc)}claimObjectReward(e){return this.send(ht.ClaimObjectReward,e,Bo)}claimGrandPrize(e){return this.send(ht.ClaimGrandPrize,e,Bo)}leaveGroup(e){return this.send(ht.LeaveGroup,e,xc)}};var Ir=class extends L{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(yt.GetDefinition,e,Mc)}getUserState(e){return this.send(yt.GetUserState,e,Oc)}getActiveDeals(e){return this.send(yt.GetActiveDeals,e,un)}dismissDeal(e){return this.send(yt.DismissDeal,e,Ec)}executeNode(e){return this.send(yt.ExecuteNode,e,Uc)}recordShow(e){return this.send(yt.RecordShow,e,qc)}claimMilestone(e){return this.send(yt.ClaimMilestone,e,Lc)}claimMilestonesBatch(e){return this.send(yt.ClaimMilestonesBatch,e,Bc)}};var eP=zod.z.object({}).passthrough().transform(r=>r),tP=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:Re.nullish()}).passthrough(),Ua=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:zod.z.record(zod.z.string(),Le).nullish(),SpendRewards:zod.z.array(tP).nullish()}).passthrough(),Ud=zod.z.object({ReferralDefinitions:Ua.nullish()}).passthrough(),Ed=zod.z.object({Referral:eP.nullish(),InviteUrl:zod.z.string().nullish()}).passthrough(),qd=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Ea=zod.z.object({RewardID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Ld=ft(Ea),Zt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch"};var vr=class extends L{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Zt.GetDefinitions,e,Ud)}getUserState(e){return this.send(Zt.GetUserState,e,Ed)}activateReferralCode(e){return this.send(Zt.ActivateReferralCode,e,qd)}claimInviteReward(e){return this.send(Zt.ClaimInviteReward,e,Ea)}claimInviteRewardsBatch(e){return this.send(Zt.ClaimInviteRewardsBatch,e,Ld)}};var Tr=class extends L{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(et.GetDefinitions,e,Nc)}getMessages(e){return this.send(et.GetMessages,e,jc)}getUnreadCount(e){return this.send(et.GetUnreadCount,e,hn)}readMessages(e){return this.send(et.ReadMessages,e,Vo)}claimReward(e){return this.send(et.ClaimReward,e,dn)}claimRewardsBatch(e){return this.send(et.ClaimRewardsBatch,e,dn)}claimAll(e){return this.send(et.ClaimAll,e,dn)}deleteMessages(e){return this.send(et.DeleteMessages,e,Vo)}sendGift(e){return this.send(et.SendGift,e,Wc)}sendTransfer(e){return this.send(et.SendTransfer,e,Kc)}getGiftStatus(e){return this.send(et.GetGiftStatus,e,Qc)}};var Ar=class extends L{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Ce.GetFriendsList,e,wi)}getIncomingRequests(e){return this.send(Ce.GetIncomingRequests,e,wi)}getOutgoingRequests(e){return this.send(Ce.GetOutgoingRequests,e,wi)}getRecommendedFriends(e){return this.send(Ce.GetRecommendedFriends,e,wi)}sendFriendRequest(e){return this.send(Ce.SendFriendRequest,e,Mi)}acceptFriendRequest(e){return this.send(Ce.AcceptFriendRequest,e,Mi)}declineFriendRequest(e){return this.send(Ce.DeclineFriendRequest,e,Mi)}removeFriend(e){return this.send(Ce.RemoveFriend,e,Mi)}getInbox(e){return this.send(Ce.GetInbox,e,$c)}markInboxSeen(e){return this.send(Ce.MarkInboxSeen,e,Oi)}getInboxUnread(e){return this.send(Ce.GetInboxUnread,e,Oi)}follow(e){return this.send(Ce.Follow,e,Lt)}unfollow(e){return this.send(Ce.Unfollow,e,Lt)}getFollowers(e){return this.send(Ce.GetFollowers,e,fn)}getFollowing(e){return this.send(Ce.GetFollowing,e,fn)}block(e){return this.send(Ce.Block,e,Lt)}unblock(e){return this.send(Ce.Unblock,e,Lt)}getBlocked(e){return this.send(Ce.GetBlocked,e,fn)}react(e){return this.send(Ce.React,e,Lt)}unreact(e){return this.send(Ce.Unreact,e,Lt)}getMyReactions(e){return this.send(Ce.GetMyReactions,e,Zc)}getEntityStates(e){return this.send(Ce.GetEntityStates,e,Jc)}addComment(e){return this.send(Ce.AddComment,e,gn)}editComment(e){return this.send(Ce.EditComment,e,gn)}deleteComment(e){return this.send(Ce.DeleteComment,e,Xc)}getComments(e){return this.send(Ce.GetComments,e,Yc)}report(e){return this.send(Ce.Report,e,ep)}};var iP={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Yt=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),sP=zod.z.object({BoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ue.nullish(),Effect:Yt.nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),kr=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),qa=zod.z.object({Availability:K.nullish(),Effects:K.nullish()}).passthrough(),nP=zod.z.object({ScheduledBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Effects:zod.z.array(Yt).nullish(),Availability:kr.nullish(),Presets:qa.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rP=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(Yt).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),oP=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Phases:zod.z.array(rP).nullish(),Availability:kr.nullish(),Presets:qa.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),aP=zod.z.object({TriggeredBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Sources:zod.z.array(st).nullish(),Effects:zod.z.array(Yt).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:kr.nullish(),Presets:qa.nullish()}).passthrough(),lP=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),uP=zod.z.object({Effects:zod.z.array(Yt).nullish()}).passthrough(),cP=zod.z.object({Availability:zod.z.record(zod.z.string(),kr).nullish(),Effects:zod.z.record(zod.z.string(),uP).nullish()}).passthrough(),pP=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),lP).nullish()}).passthrough(),zr=zod.z.object({Definitions:zod.z.record(zod.z.string(),sP).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),nP).nullish(),BoostChains:zod.z.record(zod.z.string(),oP).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),aP).nullish(),Settings:pP.nullish(),Presets:cP.nullish()}).passthrough(),Bd=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:Yt.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:c.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:c.nullish()}).passthrough();var Gd=zod.z.object({ServerTimeUtc:c.nullish(),Active:zod.z.record(zod.z.string(),Bd).nullish()}),Fd=zod.z.object({ServerTimeUtc:c.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:Bd.nullish(),Resources:M.nullish()}),hP={Scheduled:"Scheduled",Chain:"Chain"},dP=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),Effects:zod.z.array(Yt).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Vd=zod.z.object({ServerTimeUtc:c.nullish(),Windows:zod.z.array(dP).nullish()}),Xt={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var wr=class extends L{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(Xt.GetDefinitions,e,zr)}getActive(e){return this.send(Xt.GetActive,e,Gd)}getActiveWindows(e){return this.send(Xt.GetActiveWindows,e,Vd)}activate(e){return this.send(Xt.Activate,e,Fd)}cleanupExpired(e){return this.send(Xt.CleanupExpired,e,Ue)}};var Mr=class extends L{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(dt.GetUserCustomDataDefinitions,e,Sn)}getMyUserCustomData(e){return this.send(dt.GetMyUserCustomData,e,np)}getPublicUserCustomDataOf(e){return this.send(dt.GetPublicUserCustomDataOf,e,Ko)}setPrivateData(e){return this.send(dt.SetPrivateData,e,Qo)}setPublicData(e){return this.send(dt.SetPublicData,e,Qo)}deleteKey(e){return this.send(dt.DeleteKey,e,Ue)}batchSet(e){return this.send(dt.BatchSet,e,rp)}batchDelete(e){return this.send(dt.BatchDelete,e,op)}batchGetPublicUserCustomDataOf(e){return this.send(dt.BatchGetPublicUserCustomDataOf,e,ap)}};var mP={Static:"Static",Runtime:"Runtime"},fP={Public:"Public",Private:"Private"},gP=zod.z.enum(["Client","Server","System"]).catch("Client"),yP=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),RP=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:c.nullish(),Version:zod.z.number().nullish(),LastWriter:gP.nullish(),ExpiresAt:c.nullish()}).passthrough(),_d=zod.z.record(zod.z.string(),RP),La=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:_d.nullish(),Runtime:_d.nullish(),NotModified:zod.z.boolean().nullish()}),CP=zod.z.object({KeyID:zod.z.string(),Scope:zod.z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:zod.z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:yP.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Or=zod.z.object({Keys:zod.z.record(zod.z.string(),CP).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),Gi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Ur=class extends L{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Gi.GetTitleCustomDataDefinitions,e,Or)}getPublicTitleData(e){return this.send(Gi.GetPublicTitleData,e,La)}getPublicTitleDataKeys(e){return this.send(Gi.GetPublicTitleDataKeys,e,La)}};var SP={Fast:"Fast",Sequential:"Sequential"},xP={Instant:"Instant",Timed:"Timed"};var bP={Hit:"Hit",Blocked:"Blocked"},DP=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),PP=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:H.nullish()}).passthrough();var IP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:H.nullish()}).passthrough(),vP=zod.z.object({Reward:H.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough();zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(IP).nullish(),Rate:vP.nullish()}).passthrough();zod.z.object({PlayedCount:zod.z.number().nullish(),RewardsClaimedCount:zod.z.number().nullish(),InstantClaimsCount:zod.z.number().nullish(),EarlyClaimsCount:zod.z.number().nullish(),LateClaimsCount:zod.z.number().nullish(),AdViewsTotal:zod.z.number().nullish(),StatRewardClaimsCount:zod.z.number().nullish(),StatReportsClampedCount:zod.z.number().nullish(),StatReportsUnknownMetricCount:zod.z.number().nullish()}).passthrough();var Nd=zod.z.object({}).passthrough().transform(r=>r),jd=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),je=zod.z.object({Operation:M.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),TP=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),AP=zod.z.object({ShieldChance:zod.z.number().nullish(),DamagedBuildingChance:zod.z.number().nullish(),RankMultiplierMin:zod.z.number().nullish(),RankMultiplierMax:zod.z.number().nullish(),RankOffsetMin:zod.z.number().nullish(),RankOffsetMax:zod.z.number().nullish(),StageLevelSpread:zod.z.number().nullish()}).passthrough(),kP=zod.z.object({CostMatrixTemplatesByID:zod.z.record(zod.z.string(),zod.z.array(zod.z.array(zod.z.number()))).nullish(),PerBoardGrowth:zod.z.number().nullish(),VisualTemplateCycle:zod.z.array(zod.z.string()).nullish(),EconomyScaledResources:ce.nullish(),ScaleRaidStealWithEconomy:zod.z.boolean().nullish(),ScaleAttackRewardWithEconomy:zod.z.boolean().nullish(),AttackValueFromCostMatrix:zod.z.boolean().nullish(),AttackBlockedRewardFactor:zod.z.number().nullish(),ScaleVictimLossWithEconomy:zod.z.boolean().nullish(),ScaleVictimLossWithTier:zod.z.boolean().nullish(),SynthesizedBuildingSlots:zod.z.number().nullish(),SynthesizedBuildingMaxLevel:zod.z.number().nullish(),DifficultyGrowthPerBoard:zod.z.number().nullish()}).passthrough(),zP=zod.z.object({CostMatrix:zod.z.array(zod.z.array(zod.z.number())).nullish(),PerBoardGrowth:zod.z.number().nullish(),EconomyScale:zod.z.number().nullish(),ScaledResources:ce.nullish()}).passthrough(),Wd=zod.z.object({SlotIndex:zod.z.number().nullish(),Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxLevel:zod.z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),wP=zod.z.object({Index:zod.z.number().nullish(),Type:zod.z.string().nullish(),CustomTypeID:zod.z.string().nullish(),RandomActionAttackWeight:zod.z.number().nullish(),RandomActionRaidWeight:zod.z.number().nullish(),ChanceTableID:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),MP=zod.z.object({Tiles:zod.z.record(zod.z.string(),wP).nullish()}).passthrough(),OP=zod.z.object({Weight:zod.z.number().nullish(),Bonus:je.nullish(),Tag:zod.z.string().nullish()}).passthrough(),UP=zod.z.object({Weight:zod.z.number().nullish(),Tag:zod.z.string().nullish(),MinBonusCells:zod.z.number().nullish(),MaxBonusCells:zod.z.number().nullish(),BonusPool:zod.z.array(OP).nullish(),GuaranteedBonus:je.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),EP=zod.z.object({Variants:zod.z.array(UP).nullish()}).passthrough(),qP=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:je.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),LP=zod.z.object({Outcomes:zod.z.array(qP).nullish()}).passthrough(),Kd=zod.z.object({PerAdMultiplierRange:jd.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),BP=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:je.nullish()}).passthrough(),GP=zod.z.object({Tiers:zod.z.array(BP).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:je.nullish()}).passthrough(),FP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:je.nullish()}).passthrough(),VP=zod.z.object({Reward:je.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),_P=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(FP).nullish(),Rate:VP.nullish()}).passthrough(),Qd=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),_P).nullish()}).passthrough(),NP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:je.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ue.nullish(),Multipliers:Kd.nullish(),Gradation:GP.nullish(),RunStats:Qd.nullish()}).passthrough(),jP=zod.z.object({Choices:zod.z.array(NP).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),WP=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:je.nullish(),Tag:zod.z.string().nullish()}).passthrough(),KP=zod.z.object({OnPassStart:je.nullish(),OnTileLanding:zod.z.record(zod.z.string(),je).nullish(),OnAttack:zod.z.record(zod.z.string(),je).nullish(),OnRaid:zod.z.record(zod.z.string(),je).nullish(),OnBuild:je.nullish(),OnStageComplete:je.nullish(),OnAttackBonusDrops:zod.z.array(WP).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),LP).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),jP).nullish()}).passthrough(),Hd=zod.z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Wd).nullish(),HeistGridBonusConfig:EP.nullish(),StageOperations:KP.nullish(),TileLandingMultiplier:jd.nullish(),EconomyOverride:zP.nullish()}).passthrough(),QP=zod.z.object({Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BoardTemplateID:zod.z.string().nullish(),Buildings:zod.z.array(Wd).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:Hd.nullish()}).passthrough(),HP=zod.z.object({AttackCooldownSeconds:zod.z.number().nullish(),RaidCooldownSeconds:zod.z.number().nullish(),MaxRecentTargets:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),LiveOpponentPoolSize:zod.z.number().nullish(),LiveOpponentPoolCacheSeconds:zod.z.number().nullish(),MaxLiveCandidateReads:zod.z.number().nullish(),VictimImmunitySeconds:zod.z.number().nullish()}).passthrough(),$P=zod.z.object({Enabled:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),MaxPerCatchUp:zod.z.number().nullish(),Chance:zod.z.number().nullish(),AttackWeight:zod.z.number().nullish(),RaidWeight:zod.z.number().nullish(),MinBoardStageLevel:zod.z.number().nullish(),RaidLossMultiplier:zod.z.number().nullish()}).passthrough(),Er=zod.z.object({RollCurrencyID:zod.z.string().nullish(),ShieldCurrencyID:zod.z.string().nullish(),RaidMode:zod.z.string().nullish(),AllowedRollMultipliers:zod.z.array(zod.z.number()).nullish(),BoardTemplatesByID:zod.z.record(zod.z.string(),MP).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),Hd).nullish(),StagesByLevel:zod.z.record(zod.z.string(),QP).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:kP.nullish(),Dice:TP.nullish(),Bots:AP.nullish(),Targeting:HP.nullish(),BotRaids:$P.nullish()}).passthrough(),JP=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:c.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),GrandPrize:H.nullish()}).passthrough(),qr=zod.z.object({Board:Er.nullish(),CommunityChest:JP.nullish()}).passthrough(),$d=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),ce).nullish()}).passthrough(),ZP=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Oe.nullish(),TargetBuildingStates:zod.z.array(DP).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:$d.nullish()}).passthrough(),YP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:je.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ue.nullish(),Multipliers:Kd.nullish(),RunStats:Qd.nullish()}).passthrough(),XP=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(YP).nullish()}).passthrough(),eI=zod.z.object({GroupID:zod.z.string().nullish(),Delta:j.nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),Jd=zod.z.object({UsedMultiplier:zod.z.number().nullish(),Steps:zod.z.number().nullish(),DiceValues:zod.z.array(zod.z.number()).nullish(),OldPosition:zod.z.number().nullish(),NewPosition:zod.z.number(),CyclesCompletedDelta:j.nullish(),LandedTileType:zod.z.string().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:ZP.nullish(),SpecialModeOffer:XP.nullish(),CommunityChestContribution:eI.nullish()}).passthrough(),Zd=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:bt.nullish()}).passthrough(),Ba=zod.z.object({Status:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),FoundSymbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(PP).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:bt.nullish(),RaidRewardPreview:$d.nullish()}).passthrough(),Yd=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish()}).passthrough(),Xd=zod.z.object({Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish()}).passthrough(),em=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),tI=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),tm=zod.z.object({FinalMultiplier:zod.z.number().nullish(),AdViewsUsed:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),IsEarlyClaim:zod.z.boolean().nullish(),ReachedTierIndex:zod.z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(tI).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),iI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},im=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),sI={Active:"Active",Left:"Left",Replaced:"Replaced"},nI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),rI=zod.z.object({CurrentProgress:j.nullish(),MaxProgress:j.nullish()}).passthrough(),oI=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Oe.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:j.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),ml).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:nI.nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),sm=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(oI).nullish(),SharedProgress:rI.nullish(),Status:im.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:zod.z.number().nullish()}).passthrough(),aI=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:im.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:c.nullish()}).passthrough(),lI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(aI).nullish()}).passthrough(),nm=zod.z.object({ServerTimeUtc:c.nullish(),UserState:lI.nullish(),ActiveGroup:sm.nullish(),SecondsRemaining:j.nullish()}),rm=zod.z.object({ServerTimeUtc:c.nullish(),Group:sm.nullish(),SecondsRemaining:j.nullish()}),Ga=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),om=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),qe={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var uI={Mesh:"Mesh",Host:"Host"},Fa=zod.z.enum(["Mesh","Host"]).catch("Mesh"),cI={ServerRelay:"ServerRelay",P2P:"P2P"},Va=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),pI={Public:"Public",Private:"Private"},hI=zod.z.enum(["Public","Private"]).catch("Public"),dI={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},mI=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),am=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),fI=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),lm=zod.z.object({SystemState:fI.nullish(),DefaultTopology:Fa.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:Va.nullish(),AllowCreatorChatOverride:zod.z.boolean().nullish(),MaxPlayersPerRoom:zod.z.number().nullish(),RoomTtlSeconds:zod.z.number().nullish(),MaxRoomLifetimeSeconds:zod.z.number().nullish(),HeartbeatIntervalMs:zod.z.number().nullish(),MemberTimeoutMs:zod.z.number().nullish(),MaxSignalPayloadBytes:zod.z.number().nullish(),MaxChatTextLength:zod.z.number().nullish(),RoomLogCap:zod.z.number().nullish(),VoiceEnabled:zod.z.boolean().nullish(),RecordVoices:zod.z.boolean().nullish(),IceServers:zod.z.array(am).nullish()}).passthrough(),gI=zod.z.object({UserID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),Ready:zod.z.boolean().nullish(),State:zod.z.record(zod.z.string(),zod.z.string()).nullish(),JoinedAt:zod.z.number().nullish(),IsHost:zod.z.boolean().nullish(),LastSeenMs:zod.z.number().nullish()}).passthrough(),yI=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:Fa.nullish(),ChatMode:Va.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),RI=zod.z.object({Seq:zod.z.number().nullish(),Type:mI.nullish(),FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Payload:zod.z.string().nullish(),Ts:zod.z.number().nullish()}).passthrough(),Fi=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:Fa.nullish(),ChatMode:Va.nullish(),Visibility:hI.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),Members:zod.z.array(gI).nullish(),IceServers:zod.z.array(am).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),um=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),cm=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),_a=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),pm=zod.z.object({Rooms:zod.z.array(yI).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),hm=zod.z.object({Envelopes:zod.z.array(RI).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Lr=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),He={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 Na=zod.z.object({TitleCustomData:Or.nullish(),Character:Zs.nullish(),Item:Jn.nullish(),Currency:Tn.nullish(),Store:Rs.nullish(),Lootbox:Ta.nullish(),Quest:Hi.nullish(),TimedEvent:qs.nullish(),Leaderboard:js.nullish(),Season:Qs.nullish(),Reward:ka.nullish(),Collection:br.nullish(),Craft:wa.nullish(),DealOffer:Go.nullish(),Premium:Pa.nullish(),TimedBoost:zr.nullish(),CoopEvent:on.nullish(),GameLoop:qr.nullish(),Match:na.nullish(),Experiment:Th.nullish(),Blockchain:Zo.nullish(),Marketplace:ua.nullish(),Multiplayer:lm.nullish(),UserCustomData:Sn.nullish(),Referral:Ua.nullish(),Localization:Lh.nullish(),Analytics:gh.nullish(),Social:tp.nullish(),PlatformBridge:ip.nullish()}).passthrough();var ei={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Br=class extends L{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(ei.GetTitlePublicConfiguration,e,Na)}getTitlePublicConfigurationExcept(e){return this.send(ei.GetTitlePublicConfigurationExcept,e,Na)}getCurrencyDefinitions(e){return this.send(ei.GetCurrencyDefinitions,e,Tn)}getItemDefinitions(e){return this.send(ei.GetItemDefinitions,e,Jn)}getServerTime(e){return this.send(ei.GetServerTime,e,Ue)}};var Gr=class extends L{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(qe.GetGameLoops,e,qr)}getBoardDefinition(e,t=false){return this.send(qe.GetBoardDefinition,e,Er,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(qe.GetBoardDefinitionForLevel,e,Er,{silent:t})}getUserBoardState(e){return this.send(qe.GetUserBoardState,e,Nd)}boardLoopRoll(e){return this.send(qe.BoardLoopRoll,e,Jd)}boardLoopAttack(e){return this.send(qe.BoardLoopAttack,e,Zd)}boardLoopRaid(e){return this.send(qe.BoardLoopRaid,e,Ba)}boardLoopRaidFast(e){return this.send(qe.BoardLoopRaidFast,e,Ba)}boardLoopBuild(e){return this.send(qe.BoardLoopBuild,e,Yd)}boardSpecialChoose(e){return this.send(qe.BoardSpecialChoose,e,Xd)}boardSpecialApplyMultiplier(e){return this.send(qe.BoardSpecialApplyMultiplier,e,em)}boardSpecialClaim(e){return this.send(qe.BoardSpecialClaim,e,tm)}getCommunityChestState(e){return this.send(qe.GetCommunityChestState,e,nm)}joinOrCreateCommunityChest(e){return this.send(qe.JoinOrCreateCommunityChest,e,rm)}claimCommunityChestMilestone(e){return this.send(qe.ClaimCommunityChestMilestone,e,Ga)}claimCommunityChestGrandPrize(e){return this.send(qe.ClaimCommunityChestGrandPrize,e,Ga)}leaveCommunityChest(e){return this.send(qe.LeaveCommunityChest,e,om)}};var SI={Live:"Live",Latest:"Latest",Specific:"Specific"},xI={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},bI=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),DI={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"},PI=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),II=zod.z.object({Level:bI,Message:zod.z.string().nullish(),Data:Et.nullish()}),vI=zod.z.object({Error:PI,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),dm=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Et.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(II).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:vI.nullish()}),ja={Execute:"Execute"};var Fr=class extends L{constructor(e){super(e,"CloudCode");}execute(e){return this.send(ja.Execute,e,dm)}};var Vr=class extends L{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Qe.GetDefinitions,e,Pp)}getUserState(e){return this.send(Qe.GetUserState,e,Ip)}depositToken(e){return this.send(Qe.DepositToken,e,vp)}depositNFT(e){return this.send(Qe.DepositNFT,e,Tp)}requestTokenWithdrawal(e){return this.send(Qe.RequestTokenWithdrawal,e,Ap)}requestNFTWithdrawal(e){return this.send(Qe.RequestNFTWithdrawal,e,kp)}getTransactionHistory(e){return this.send(Qe.GetTransactionHistory,e,zp)}retryWithdrawal(e){return this.send(Qe.RetryWithdrawal,e,wp)}confirmWithdrawal(e){return this.send(Qe.ConfirmWithdrawal,e,Mp)}donateToDeveloper(e){return this.send(Qe.DonateToDeveloper,e,ta)}donateToUsersPool(e){return this.send(Qe.DonateToUsersPool,e,ta)}getPlayAccess(e){return this.send(Qe.GetPlayAccess,e,bp)}confirmPlayAccess(e){return this.send(Qe.ConfirmPlayAccess,e,Bt)}};var _r=class extends L{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(ke.GetDefinitions,e,Kp)}getGroupedOffers(e){return this.send(ke.GetGroupedOffers,e,Qp)}getOffersByItem(e){return this.send(ke.GetOffersByItem,e,ca)}getOffer(e){return this.send(ke.GetOffer,e,Hp)}getBuyOrders(e){return this.send(ke.GetBuyOrders,e,ca)}getMyState(e){return this.send(ke.GetMyState,e,Un)}getHistory(e){return this.send(ke.GetHistory,e,Jp)}createListing(e){return this.send(ke.CreateListing,e,qi)}cancelListing(e){return this.send(ke.CancelListing,e,at)}buy(e){return this.send(ke.Buy,e,at)}marketBuy(e){return this.send(ke.MarketBuy,e,at)}marketSell(e){return this.send(ke.MarketSell,e,at)}createAuction(e){return this.send(ke.CreateAuction,e,qi)}placeBid(e){return this.send(ke.PlaceBid,e,$p)}claimAuction(e){return this.send(ke.ClaimAuction,e,at)}createBuyOrder(e){return this.send(ke.CreateBuyOrder,e,qi)}cancelBuyOrder(e){return this.send(ke.CancelBuyOrder,e,at)}fillBuyOrder(e){return this.send(ke.FillBuyOrder,e,at)}createDirectTrade(e){return this.send(ke.CreateDirectTrade,e,qi)}respondDirectTrade(e){return this.send(ke.RespondDirectTrade,e,at)}cancelDirectTrade(e){return this.send(ke.CancelDirectTrade,e,at)}claimBack(e){return this.send(ke.ClaimBack,e,at)}};var Nr=class extends L{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(He.CreateRoom,e,Fi)}joinRoom(e){return this.send(He.JoinRoom,e,Fi)}leaveRoom(e,t=false){return this.send(He.LeaveRoom,e,_a,{keepalive:t})}listRooms(e){return this.send(He.ListRooms,e,pm)}getRoom(e){return this.send(He.GetRoom,e,Fi)}closeRoom(e){return this.send(He.CloseRoom,e,_a)}poll(e){return this.send(He.Poll,e,hm)}sendSignal(e){return this.send(He.SendSignal,e,Lr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(He.ClaimHost,e,Fi)}kickMember(e){return this.send(He.KickMember,e,um)}unbanMember(e){return this.send(He.UnbanMember,e,cm)}sendChat(e){return this.send(He.SendChat,e,Lr)}setMemberState(e){return this.send(He.SetMemberState,e,Lr)}};var TI={Free:"Free",Price:"Price",Holding:"Holding"},Wa=zod.z.enum(["Free","Price","Holding"]).catch("Free"),AI={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},kI=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),zI={All:"All",Any:"Any"},wI=zod.z.enum(["All","Any"]).catch("All"),MI={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},OI=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),UI={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},EI=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),qI={Purchase:"Purchase",Free:"Free",Holding:"Holding"},fm=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),LI={New:"New",Popular:"Popular",MostLiked:"MostLiked"},BI={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},GI=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),FI=zod.z.object({Type:li.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),MinLevel:zod.z.number().nullish()}).passthrough(),VI=zod.z.object({Requirements:zod.z.array(FI).nullish(),Match:wI.nullish(),Mode:kI.nullish()}).passthrough(),_I=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Wa.nullish(),Price:ce.nullish(),Holding:VI.nullish()}).passthrough(),NI=zod.z.object({AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxBytes:zod.z.number().nullish(),MaxCount:zod.z.number().nullish(),Required:zod.z.boolean().nullish()}).passthrough(),jI=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),NI).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(Wa).nullish(),PricePolicy:On.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ue.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),WI=zod.z.object({Allowed:zod.z.array(Ei).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),KI=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),QI=zod.z.object({MaxTitleLength:zod.z.number().nullish(),MaxDescriptionLength:zod.z.number().nullish(),MaxTags:zod.z.number().nullish(),MaxTagLength:zod.z.number().nullish(),MaxMetadataKeys:zod.z.number().nullish(),MaxMetadataValueLength:zod.z.number().nullish(),MaxAccessOptions:zod.z.number().nullish(),ThumbnailMaxBytes:zod.z.number().nullish()}).passthrough(),HI=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Order:zod.z.number().nullish()}).passthrough(),$I=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),ContentTypes:zod.z.record(zod.z.string(),jI).nullish(),PricePolicy:On.nullish(),Commission:la.nullish(),HoldingPolicy:WI.nullish(),Moderation:KI.nullish(),Limits:QI.nullish(),Featured:zod.z.array(HI).nullish()}).passthrough(),JI=zod.z.object({Acquisitions:zod.z.number().nullish(),Downloads:zod.z.number().nullish(),Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),ReportCount:zod.z.number().nullish()}).passthrough(),ti=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:Oe.nullish(),Title:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Metadata:zod.z.record(zod.z.string(),zod.z.string()).nullish(),ThumbnailUrl:zod.z.string().nullish(),Visibility:OI.nullish(),Access:zod.z.array(_I).nullish(),Status:EI.nullish(),ModerationNote:zod.z.string().nullish(),Stats:JI.nullish(),Revision:zod.z.number().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),PublishedAt:c.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),ZI=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Wa.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),gm=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Order:zod.z.number().nullish()}).passthrough(),ym=zod.z.object({Definitions:$I.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish(),CanPublish:zod.z.record(zod.z.string(),zod.z.boolean()).nullish(),Collections:zod.z.array(gm).nullish()}).passthrough(),jr=zod.z.object({Items:zod.z.array(ti).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Rm=zod.z.object({Content:ti.nullish(),AccessState:zod.z.array(ZI).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Cm=zod.z.object({Collection:gm.nullish(),Items:zod.z.array(ti).nullish()}).passthrough(),Sm=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:Oe.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(ti).nullish()}).passthrough(),mm=zod.z.object({Role:zod.z.string().nullish(),Index:zod.z.number().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish(),ServerCopy:zod.z.boolean().nullish()}).passthrough(),xm=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(mm).nullish(),ThumbnailUpload:mm.nullish(),ExpiresAt:c.nullish()}).passthrough(),bm=zod.z.object({Content:ti.nullish(),Resources:M.nullish()}).passthrough(),Ka=zod.z.object({Content:ti.nullish()}).passthrough(),Dm=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:fm.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:ce.nullish()}).passthrough(),YI=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),Pm=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:GI.nullish(),Files:zod.z.array(YI).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:c.nullish()}).passthrough(),XI=zod.z.object({ContentID:zod.z.string().nullish(),Source:fm.nullish(),OptionID:zod.z.string().nullish(),PricePaid:ce.nullish(),AcquiredAt:c.nullish(),Content:ti.nullish()}).passthrough(),Im=zod.z.object({Licenses:zod.z.array(XI).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),We={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 Wr=class extends L{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(We.GetDefinitions,e,ym)}browse(e){return this.send(We.Browse,e,jr)}getContent(e){return this.send(We.GetContent,e,Rm)}getCollection(e){return this.send(We.GetCollection,e,Cm)}getCreatorProfile(e){return this.send(We.GetCreatorProfile,e,Sm)}beginUpload(e){return this.send(We.BeginUpload,e,xm)}publish(e){return this.send(We.Publish,e,bm)}updateContent(e){return this.send(We.UpdateContent,e,Ka)}unpublish(e){return this.send(We.Unpublish,e,Ka)}getMyContent(e){return this.send(We.GetMyContent,e,jr)}acquire(e){return this.send(We.Acquire,e,Dm)}getDownload(e){return this.send(We.GetDownload,e,Pm)}getMyLicenses(e){return this.send(We.GetMyLicenses,e,Im)}getMyFavorites(e){return this.send(We.GetMyFavorites,e,jr)}};var Kr=class extends L{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,ih,"defs")}get(e){return this.sendKeyed("Get",e,ha,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,nh,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,da,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,rh,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,ma,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,ma,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,oh,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,lh,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,ah,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,uh,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,sh,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,ch,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,ha,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,da,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Qr=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=Xa(e),this.emitter=new Pi,this.platform=e.platform??new ri,this.clientPlatform=e.clientPlatform??hl(),this.acquisition=new _t(this.platform),this.acquisition.capture(),this.playtime=new Ii(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear();}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new ts({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 rs(this.emitter),this.cache=new as(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new ls(this.platform.storage,this.settings.titleID),this.api={authentication:new Wn(this),user:new Qn(this),currency:new Hn(this),item:new Zn(this),store:new Yn(this),purchase:new ir(this),lootbox:new rr(this),reward:new or(this),quest:new hr(this),tutorial:new ar(this),communityMarketing:new lr(this),chat:new ur(this),push:new cr(this),localization:new pr(this),timedEvent:new dr(this),leaderboard:new mr(this),season:new fr(this),premium:new gr(this),character:new yr(this),match:new Rr(this),craft:new Sr(this),ai:new xr(this),collection:new Dr(this),coopEvent:new Pr(this),dealOffer:new Ir(this),referral:new vr(this),mailbox:new Tr(this),social:new Ar(this),timedBoost:new wr(this),userCustomData:new Mr(this),titleCustomData:new Ur(this),title:new Br(this),gameLoop:new Gr(this),cloudCode:new Fr(this),blockchain:new Vr(this),marketplace:new _r(this),multiplayer:new Nr(this),workshop:new Wr(this),dataCollections:new Kr(this),analytics:new Nn(this),experiment:new jn(this)},this.userService=new ds(this),this.cache.attachState(this.userService),this.auth=new us(this),this.currency=new fs(this),this.item=new gs(this),this.store=new Ss(this),this.purchase=new xs(this),this.checkout=new Ds(this),this.lootbox=new Ps(this),this.reward=new Is(this),this.quest=new Es(this),this.tutorial=new Ts(this),this.communityMarketing=new As(this),this.chat=new ws(this),this.push=new Ms(this),this.localization=new Us(this),this.timedEvent=new Bs(this),this.leaderboard=new Ws(this),this.season=new Hs(this),this.premium=new $s(this),this.character=new Ys(this),this.match=new Xs(this),this.craft=new en(this),this.ai=new sn(this),this.collection=new nn(this),this.coopEvent=new an(this),this.dealOffer=new cn(this),this.referral=new pn(this),this.mailbox=new mn(this),this.social=new yn(this),this.timedBoost=new Rn(this),this.userCustomData=new xn(this),this.titleCustomData=new bn(this),this.title=new Dn(this),this.gameLoop=new Pn(this),this.cloudCode=new In(this),this.blockchain=new kn(this),this.marketplace=new En(this),this.multiplayer=new qn(this),this.workshop=new Ln(this),this.dataCollections=new Gn(this),this.analytics=new Vn(this),this.experiments=new _n(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.platform.getFullURL(),RelatedEntityID:B()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var Hr=class{ctx;constructor(e){this.ctx=new Qr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Ft(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},zod.z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function tv(r){return new Hr(r)}var vm="idos_sso",Tm="state",Qa="idos:sso:state",iv="https://idosgames.com/sso/",sv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],nv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function rv(){if(typeof window>"u")return false;let{origin:r}=window.location;return sv.includes(r)||nv.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function ov(){if(typeof window>"u")return null;let r=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!r)return null;let e=new URLSearchParams(r),t=e.get(vm);if(!t)return null;let i=e.get(Tm)??"",s=pv();return dv(e),hv(),s&&i!==s?null:{code:t,state:i}}function av(r){if(typeof window>"u")return;let e=r.returnTo??lv(),t=uv();cv(t);let i=new URL(r.ssoUrl??iv);i.searchParams.set("title",r.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function lv(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function uv(){let r=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(r);else for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*256);return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function cv(r){try{window.sessionStorage.setItem(Qa,r);}catch{}}function pv(){try{return window.sessionStorage.getItem(Qa)}catch{return null}}function hv(){try{window.sessionStorage.removeItem(Qa);}catch{}}function dv(r){r.delete(vm),r.delete(Tm);let e=r.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var mv={EMAIL_SENDER_NOT_CONFIGURED:"Sign-in by e-mail is unavailable in this game right now. Try another way to sign in.",INVALID_VERIFICATION_CODE:"That code is not right. Check the e-mail and try again.",VERIFICATION_CODE_ATTEMPTS_EXCEEDED:"Too many wrong attempts. Ask for a new code.",INCORRECT_EMAIL_OR_PASSWORD:"Wrong e-mail or password.",INCORRECT_EMAIL:"That does not look like an e-mail address.",PASSWORD_LENGTH_INVALID:"The password must be 8 to 100 characters long.",TOO_MANY_FAILED_ATTEMPTS:"Too many attempts. Please try again a little later.",RATE_LIMIT_EXCEEDED:"Too many requests. Please try again in a moment.",APPLE_EMAIL_MISSING:"Apple did not share an e-mail address. Try again and allow it, or use another way to sign in.",INVALID_WALLET_SIGNATURE:"The signature does not match the wallet. Please try again.",WALLET_CHALLENGE_EXPIRED:"The request expired. Please try again.",WALLET_CHANGES_TOO_FREQUENT:"Too many wallets were changed this week. Try again in a few days.",WALLET_UNLINK_COOLDOWN:"This wallet was unlinked from another account less than 7 days ago. Try again after the 7 days.",PLAY_ACCESS_GUEST_DISABLED:"Guest play is off in this game. Sign in to link a crypto wallet.",PLAY_ACCESS_WALLET_LOGIN_ONLY:"This game can only be entered with a crypto wallet or your iDos Games account.",PLAY_ACCESS_WALLET_USED_BY_ANOTHER_ACCOUNT:"This wallet already plays with another account.",PLAY_ACCESS_WALLET_REQUIRED:"Link a crypto wallet to play.",PLAY_ACCESS_WALLET_NETWORK_NOT_GATED:"This wallet's network is not accepted here. Link a wallet of the required network.",PLAY_ACCESS_REQUIRED:"Check your balance to continue.",PLAY_ACCESS_CHECK_FAILED:"Could not check your balance right now. Please try again in a moment."};function fv(r,e="Something went wrong. Please try again."){return r?mv[r]??r:e}function gv(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function yv(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function Rv(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function km(r,e,t,i=1){if(!r)return e;let s=r.Base??e,n=Math.max(0,t-i),o;switch(r.Shape??"Flat"){case "PerStep":o=s+(r.PerStep??0)*n;break;case "PerStepRate":o=s*(1+(r.PerStepRate??0)*n);break;case "Geometric":o=s*Math.pow(1+(r.GrowthRate??0),n);break;case "Table":o=s*Am(r,t,1);break;case "TableAbsolute":o=Am(r,t,s);break;default:o=s;break}return Number.isNaN(o)?s:(r.MinResult!=null&&o<r.MinResult&&(o=r.MinResult),r.MaxResult!=null&&o>r.MaxResult&&(o=r.MaxResult),o)}function Cv(r,e,t=1){return km(r,1,e,t)}function Sv(r){if(!r)return false;switch(r.Shape??"Flat"){case "PerStep":return (r.PerStep??0)!==0;case "PerStepRate":return (r.PerStepRate??0)!==0;case "Geometric":return (r.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return zm(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function xv(r){if(Number.isNaN(r)||r<=0)return 0;if(!Number.isFinite(r))return Number.MAX_SAFE_INTEGER;let e=Math.round(r);return Math.abs(r-e)<=1e-9*Math.max(1,Math.abs(r))?e:Math.ceil(r)}function zm(r){if(!r)return [];let e=[];for(let t of r)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function Am(r,e,t){let i=zm(r.Points);if(i.length===0)return t;let s=null,n=null,o=null;for(let p of i)(o===null||p.AtStep>o.AtStep)&&(o=p),p.AtStep<=e&&(s===null||p.AtStep>=s.AtStep)&&(s=p),p.AtStep>e&&(n===null||p.AtStep<n.AtStep)&&(n=p);if(s===null)return t;if(n===null){let p=r.TailGrowthRate??0;return p===0?o.Value:o.Value*Math.pow(1+p,e-o.AtStep)}switch(r.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+p*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let d=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+d*(n.Value-s.Value)}let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,p)}default:return s.Value}}var bv={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Ha=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),Dv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Pv=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),Iv=zod.z.object({PlacementID:zod.z.string().nullish(),Type:Ha.nullish(),Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),CreditsRewarded:zod.z.number().nullish(),AllowedProviderIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),vv=zod.z.object({DefaultCreditsPerView:zod.z.number().nullish(),MaxCreditsBalance:zod.z.number().nullish(),DailyCreditEarnCap:zod.z.number().nullish(),DailyViewCap:zod.z.number().nullish(),MinSecondsBetweenViews:zod.z.number().nullish()}).passthrough(),Tv=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),Av=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:Pv.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),kv=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),zv=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),wv=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),DisableInterstitials:zod.z.boolean().nullish(),DisableBanners:zod.z.boolean().nullish(),DisableAppOpen:zod.z.boolean().nullish()}).passthrough(),Mv=zod.z.object({RequirePersonalizedAdsConsent:zod.z.boolean().nullish(),RequireTrackingConsent:zod.z.boolean().nullish(),CurrentPolicyVersion:zod.z.string().nullish(),RegulatedRegions:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ov=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),Uv=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:Ha.nullish()}).passthrough(),Ev={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},qv=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Lv=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:qv.nullish(),Enabled:zod.z.boolean().nullish(),Priority:zod.z.number().nullish(),AndroidAppID:zod.z.string().nullish(),IosAppID:zod.z.string().nullish(),WebAppID:zod.z.string().nullish(),Units:zod.z.record(zod.z.string(),Uv).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),Iv).nullish(),Providers:zod.z.record(zod.z.string(),Lv).nullish(),RewardedVideo:vv.nullish(),Interstitial:Tv.nullish(),Banner:Av.nullish(),AppOpen:kv.nullish(),FrequencyCapping:zv.nullish(),PremiumAdReductions:zod.z.array(wv).nullish(),Consent:Mv.nullish(),Verification:Ov.nullish()}).passthrough();var Bv=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),Gv=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:c.nullish(),LastCompletedAt:c.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),Fv=zod.z.object({Date:c.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),Vv=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:c.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),_v=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:c.nullish(),ConsentRevokedAt:c.nullish()}).passthrough(),Nv=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:Ha.nullish(),IssuedAt:c.nullish(),ExpiresAt:c.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),jv=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:c.nullish()}).passthrough();zod.z.object({Credits:Bv.nullish(),Placements:zod.z.record(zod.z.string(),Gv).nullish(),Daily:Fv.nullish(),Session:Vv.nullish(),LastImpressionAt:c.nullish(),LastInterstitialAt:c.nullish(),LastRewardedAt:c.nullish(),LastAppOpenAt:c.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:c.nullish(),Consent:_v.nullish(),PendingRequests:zod.z.record(zod.z.string(),Nv).nullish(),FraudFlags:jv.nullish(),UpdatedAt:c.nullish()}).passthrough();var wm="idos_device_id",$r=class{storage;constructor(e=new si){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(wm);return e||(e="noop-device",this.storage.setString(wm,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};var $a={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},Wv=30*6e4,Kv=/^[a-z0-9]{8}-preview\.idos\.games$/,Ja="idos:platformSignIn:declined:";function Qv(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(Kv.test(window.location.hostname.toLowerCase()))return false;let r=window.location.ancestorOrigins?.[0];if(r&&!Pt.includes(r))try{let e=new URL(r).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}async function Hv(r){let e=await Ai($a.request,$a.response,{titleID:r},{answerTimeoutMs:Wv}),t=e.data.code;return e.ok&&typeof t=="string"&&t.length>0?{code:t}:{error:e.error??"no_code"}}function $v(r){try{window.localStorage.setItem(Ja+r,"1");}catch{}}function Jv(r){try{window.localStorage.removeItem(Ja+r);}catch{}}function Zv(r){try{return window.localStorage.getItem(Ja+r)==="1"}catch{return false}}
|
|
1
|
+
'use strict';var zod=require('zod'),jt=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var jt__default=/*#__PURE__*/_interopDefault(jt);var Pi=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,s=>{i(),t(s);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let s of [...i])s(t);}removeAllListeners(){this.listeners.clear();}};function Mm(){let r=new Map;return {get:e=>r.get(e)??null,set:(e,t)=>{r.set(e,t);},remove:e=>{r.delete(e);}}}function Za(){return Om()??Mm()}function Om(){try{let r=globalThis.localStorage;if(!r)return null;let e="__idos_probe__";return r.setItem(e,"1"),r.removeItem(e),{get:t=>{try{return r.getItem(t)}catch{return null}},set:(t,i)=>{try{r.setItem(t,i);}catch{try{r.removeItem(t);}catch{}}},remove:t=>{try{r.removeItem(t);}catch{}}}}catch{return null}}var Ya="https://api.idosgames.com";function Xa(r){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??Ya).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??Za(),locale:r.locale??Um(),appVersion:r.appVersion??""}}function Um(){try{return globalThis.navigator?.language??""}catch{return ""}}var ii=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},si=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,t){this.map.set(e,t);}remove(e){this.map.delete(e);}};function ni(){return globalThis.Telegram?.WebApp??null}function B(){return crypto.randomUUID()}var el="idos_device_id",ri=class{storage;constructor(e=new ii){this.storage=e;}getPlatform(){return ni()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=ni()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=ni()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(el);return e||(e=B(),this.storage.setString(el,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=ni();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=ni();if(t?.openInvoice){t.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let t=globalThis;typeof t.showAd=="function"&&await t.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var Jr="idos_acq",tl=["gclid","fbclid","ttclid","msclkid","yclid"],Em=["ref","r"],qm=["ref_","ref-","ref=","r_","r-"];var _t=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();Lm(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=Fm(this.platform.getDeviceModel());return s&&(i.OsVersion=s),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(Jr);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let i=nl(sl(t));if(i)return i}return Vi(t)}readFromEnvironment(){let e={},t=sl(this.platform.getFullURL());Vt(e,"UtmSource",t.get("utm_source")),Vt(e,"UtmMedium",t.get("utm_medium")),Vt(e,"UtmCampaign",t.get("utm_campaign")),Vt(e,"UtmTerm",t.get("utm_term")),Vt(e,"UtmContent",t.get("utm_content")),Vt(e,"ClaimToken",t.get("idos_click"));for(let R of tl){let V=t.get(R);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",s=Gm(i);if(s){for(let R of Bm)Vt(e,R,s.get(rl[R])??null);for(let R of tl){let V=s.get(R);if(V){e.ClickID=V;break}}}let n=Vi(s?s.get("ref")??s.get("r")??"":i),o=nl(t),p=n||o;p&&(e.ReferralCode=p,e.ChannelHint=n?"telegram":"query");let d=this.platform.getReferrer?.();return d&&(e.Referrer=d),e}read(){try{let e=this.platform.storage.getString(Jr);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.platform.storage.setString(Jr,JSON.stringify(e));}catch{}}};function Lm(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function Vt(r,e,t){t&&(r[e]=t);}var il="a1_",rl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Bm=Object.keys(rl);function Gm(r){let e=(r||"").trim();if(!e.startsWith(il))return null;let t=e.slice(il.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,d=>d.charCodeAt(0)),o=new TextDecoder().decode(n),p=new URLSearchParams(o);return [...p.keys()].length>0?p:null}catch{return null}}function sl(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function nl(r){for(let e of Em){let t=r.get(e);if(t)return Vi(t)}return null}function Vi(r){let e=(r||"").trim();if(!e)return null;for(let t of qm)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Fm(r){let e=r||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var ol="idos_usage_pending",al="idos_usage_session",ll="idos_usage_closed_session",ul="idos_usage_new_session",cl="idos_usage_last_activity",Ii=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=typeof document<"u"&&document.visibilityState==="hidden",this.timer=setInterval(()=>this.tick(),200*1e3),window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();}};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,i=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,i,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(ol),this.currentSessionSeconds=this.readNumber(al),this.pendingClosedSessionSeconds=this.readNumber(ll),this.isNewSessionPending=this.readNumber(ul)!==0;let e=this.readNumber(cl);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(ol,this.pendingSeconds),this.writeNumber(al,this.currentSessionSeconds),this.writeNumber(ll,this.pendingClosedSessionSeconds),this.writeNumber(ul,this.isNewSessionPending?1:0),this.writeNumber(cl,Date.now());}readNumber(e){let t=this.ctx.platform.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.platform.storage.setString(e,String(Math.floor(t)));}catch{}}};var ut={Virtual:"Virtual",Crypto:"Crypto"},ai=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),_i={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase"},li=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase"]).catch("Item"),mt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Ni=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),Vm={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},ji=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),_m={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Wi=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Nm={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},vi=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),we={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function hl(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return pl(e);let t=r.cordova?.platformId;return t?pl(t):r.navigator?.userAgent??""?mt.Web:mt.Unknown}function pl(r){let e=r.toLowerCase();return e==="android"?mt.Android:e==="ios"?mt.Ios:e==="web"?mt.Web:mt.Unknown}function F(r){return {ok:true,data:r}}function u(r,e){return {ok:false,reason:r,error:e}}var a=u("unauthorized","Not logged in.");function jm(r){return r.ok}function Wm(r){return !r.ok}var j=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="string"?Number(r):r;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(r)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="number"?String(r):r.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(r)}`}),zod.z.NEVER):t}),c=zod.z.string();var Zr=zod.z.object({Type:li.nullish(),CurrencyID:zod.z.string().nullish(),Amount:j.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),Km=zod.z.object({Type:Wi.nullish(),EntityID:zod.z.string()}),Qm=zod.z.object({Address:Km.nullish(),Amount:j.nullish(),Source:zod.z.string().nullish()}),ce=zod.z.object({Entries:zod.z.array(Zr).nullish(),EventTokens:zod.z.array(Qm).nullish()}),dl=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:ce.nullish()}),H=zod.z.object({Standard:ce.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(dl).nullish()}),xt=zod.z.object({Standard:ce.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(dl).nullish()}),M=zod.z.object({Grant:H.nullish(),Consume:xt.nullish()}),bt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:ce.nullish()});var Hm=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),$m={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Jm=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),Z=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:Hm.nullish(),Tutorial:Jm.nullish(),Platforms:zod.z.array(Ni).nullish()}).passthrough();var Re=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var Zm=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Ym=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Xm=zod.z.object({AnchorUtc:zod.z.string().nullish(),MaxCycles:zod.z.number().nullish(),PauseBetweenPhasesSec:zod.z.number().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish()}).passthrough();zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();var ef=zod.z.object({Reset:zod.z.string().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:zod.z.string().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();zod.z.object({SourceType:zod.z.string().nullish(),TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var st=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:Re.nullish()}).passthrough(),ge=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:Ym.nullish(),Chain:Xm.nullish(),Cyclic:ef.nullish(),ActivationTriggers:zod.z.array(st).nullish(),Relative:Zm.nullish()}).passthrough();var tf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},sf=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),nf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},rf=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),of=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Fe=zod.z.object({Base:zod.z.number().nullish(),Shape:sf.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(of).nullish(),Interpolation:rf.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var af=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:H.nullish()}).passthrough(),lf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),Yr=zod.z.object({Bundles:zod.z.array(af).nullish(),Multipliers:zod.z.array(lf).nullish()}).passthrough();var uf=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Ki=zod.z.object({Source:uf.nullish(),SourceKey:zod.z.string().nullish(),Curve:Fe.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:ce.nullish(),ExcludeRewards:ce.nullish()}).passthrough(),ml=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),Le=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:Yr.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),ui=zod.z.object({Milestones:zod.z.record(zod.z.string(),Le).nullish()}).passthrough();var K=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var cf=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Nt=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxBalance:zod.z.number().nullish(),MaxPerGrant:zod.z.number().nullish(),DailyEarnCap:zod.z.number().nullish(),BurnOnEventEnd:zod.z.boolean().nullish(),BurnConversion:cf.nullish()}).passthrough();var pf=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),fl=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:pf.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Q=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),fl).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var ve=r=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:r.nullish()}),ft=r=>zod.z.object({ServerTimeUtc:c,Items:zod.z.array(ve(r)),Resources:M.nullish(),Inventory:Q.nullish()});var hf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},gl=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),df=zod.z.object({}).passthrough().transform(r=>r),mf=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:c.nullish(),CycleEndUtc:c.nullish(),PointsTotalEarned:j.nullish(),PointsCurrent:j.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:Le.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Xr=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:j.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:gl}),yl=zod.z.object({State:df.nullish(),PointsTracks:zod.z.record(zod.z.string(),mf).nullish()}),eo=zod.z.object({ServerTimeUtc:c,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:gl.nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),to=zod.z.object({ServerTimeUtc:c,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:j.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),NextMilestone:Le.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Rl=zod.z.object({ServerTimeUtc:c,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Cl=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(Xr).nullish()}),Sl=zod.z.array(ve(eo)),xl=zod.z.array(ve(to)),ff={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},gf=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),yf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Rf=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),bl=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:gf.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(st).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),io=zod.z.object({Milestones:K.nullish(),Linking:K.nullish(),Availability:K.nullish(),Reward:K.nullish(),Objectives:K.nullish()}).passthrough(),Cf=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Dl=zod.z.object({CycleIDs:zod.z.array(zod.z.string()).nullish(),GroupID:zod.z.string().nullish(),PhaseIDs:zod.z.array(zod.z.string()).nullish(),RequiredQuestIDs:zod.z.array(zod.z.string()).nullish(),PrerequisiteMode:Rf.nullish()}).passthrough(),Pl=zod.z.object({Schedule:ge.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Il=zod.z.object({Grant:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Sf=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Cf.nullish(),Linking:Dl.nullish(),Availability:Pl.nullish(),Objectives:zod.z.record(zod.z.string(),bl).nullish(),Reward:Il.nullish(),Presets:io.nullish()}).passthrough(),xf=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),bf=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:Z.nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),Presets:io.nullish(),PointsToken:Nt.nullish()}).passthrough(),Df=zod.z.object({Milestones:zod.z.record(zod.z.string(),ui).nullish(),Linking:zod.z.record(zod.z.string(),Dl).nullish(),Availability:zod.z.record(zod.z.string(),Pl).nullish(),Reward:zod.z.record(zod.z.string(),Il).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),bl)).nullish()}).passthrough(),Pf=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ge.nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),Gate:Z.nullish(),PointsToken:Nt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),xf).nullish(),Phases:zod.z.record(zod.z.string(),bf).nullish(),Presets:io.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Hi=zod.z.object({Cycles:zod.z.record(zod.z.string(),Pf).nullish(),Quests:zod.z.record(zod.z.string(),Sf).nullish(),Presets:Df.nullish()}).passthrough(),pt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var If={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},vf=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Tf={Never:"Never",OnRequest:"OnRequest",Always:"Always"},Af=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),kf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},zf=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),wf={GameLoop:"GameLoop"},Mf={Raid:"Raid",Attack:"Attack"},Of=zod.z.object({Title:zod.z.string().nullish(),TitleKey:zod.z.string().nullish(),Body:zod.z.string().nullish(),BodyKey:zod.z.string().nullish(),AnchorID:zod.z.string().nullish(),HighlightTarget:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),UiHint:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Uf=zod.z.object({Mode:vf.nullish(),Triggers:zod.z.array(st).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),Ef=zod.z.object({Grant:H.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),qf=zod.z.object({TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),RandomActionType:zod.z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),Lf=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:qf.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),Bf=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),so=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:Of.nullish(),Completion:Uf.nullish(),Effects:Ef.nullish(),Script:Lf.nullish(),Policy:Bf.nullish()}).passthrough(),Gf=zod.z.object({DisplayName:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),Description:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),vl=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:st.nullish()}).passthrough(),Tl=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:Af.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Al=zod.z.object({Grant:H.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),Ff=zod.z.object({Availability:K.nullish(),Policy:K.nullish(),Reward:K.nullish(),Steps:K.nullish()}).passthrough(),Vf=zod.z.object({FlowID:zod.z.string().nullish(),Identity:Gf.nullish(),Availability:vl.nullish(),Policy:Tl.nullish(),Steps:zod.z.record(zod.z.string(),so).nullish(),Reward:Al.nullish(),Presets:Ff.nullish()}).passthrough(),_f=zod.z.object({BlockingFlowIDs:zod.z.array(zod.z.string()).nullish(),BlockedModules:zod.z.array(zod.z.string()).nullish(),BlockedActions:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),BlockBeforeStart:zod.z.boolean().nullish(),SkipLiftsBlock:zod.z.boolean().nullish()}).passthrough(),Nf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:_f.nullish()}).passthrough(),jf=zod.z.object({Availability:zod.z.record(zod.z.string(),vl).nullish(),Policy:zod.z.record(zod.z.string(),Tl).nullish(),Reward:zod.z.record(zod.z.string(),Al).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),so)).nullish()}).passthrough(),kl=zod.z.object({Flows:zod.z.record(zod.z.string(),Vf).nullish(),Settings:Nf.nullish(),Presets:jf.nullish()}).passthrough(),Wf=zod.z.object({}).passthrough().transform(r=>r),zl=zod.z.object({FlowID:zod.z.string(),Status:zf,CurrentStepID:zod.z.string().nullish(),CurrentStep:so.nullish(),TotalSteps:zod.z.number(),CompletedSteps:zod.z.number(),CanSkip:zod.z.boolean(),RewardClaimed:zod.z.boolean(),RewardPending:zod.z.boolean(),VariantID:zod.z.string().nullish()}).passthrough(),$i=zod.z.object({State:Wf.nullish(),Flows:zod.z.array(zl).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),wt=zod.z.object({Flow:zl.nullish()}).passthrough(),wl=zod.z.object({FlowID:zod.z.string().nullish(),Granted:M.nullish()}).passthrough(),Ml=zod.z.array(ve(wt)),Ol=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),nt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Ji(r){return Array.isArray(r)?r.filter(e=>e!==null).map(Ji):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,Ji(t)])):r}var Zi=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var Yi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Ul(r){return r===429||r>=500&&r<=599}function Xi(r,e=Math.random){let t=Math.min(500*Math.pow(2,r-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Mt(r){return new Promise(e=>setTimeout(e,r))}var El=15e3;async function ql(r){try{let t=JSON.parse(await r.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(r.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Ll(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function Bl(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var no=15,Gl=1e3,es=class{constructor(e=no,t=()=>Date.now(),i=Mt){this.perSecond=e;this.now=t;this.wait=i;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=Gl;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Gl-(e-this.starts[0])+5);}}};var Kf=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function pi(r){if(!r)return null;let e=Kf.exec(r);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new jt__default.default(i),o=new jt__default.default(s),p=o.minus(jt__default.default.max(n,0));return p.lte(0)?null:{currencyID:t,required:o.toNumber(),available:n.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var Qf=12e3,Hf=new Set(["RelatedEntityID"]);function $f(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[i,s]of Object.entries(e))Hf.has(i)||(t[i]=s);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var Jf=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(Xr).nullish(),TutorialProgress:zod.z.array(Ol).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),ts=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Yi;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new Zi(e.throttleMs),this.pacer=new es(e.maxRequestsPerSecond??no),this.clientPlatform=e.clientPlatform??mt.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,s={}){let n=s.throttleKey??$f(e,t);if(!this.throttler.tryAcquire(n))return u("throttled","Throttled");if(!this.inflight.add(n))return u("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,p=JSON.stringify(t),d=s.ticket??null,R=s.silent??!1,V=s.timeoutMs??Qf,re=s.autoRetry??!0,Se=!1,ae=!1,me=0;for(;;){let St;s.keepalive||await this.pacer.take();try{St=await this.doFetch(o,p,d,V,s.keepalive??!1);}catch{if(re&&me<3){me++,await Mt(Xi(me));continue}return this.connectionFailure("Internet Connection Error",R)}let Je=St.status;if(Je>=200&&Je<300){let ne=!ae&&this.cryptoTopUpHandler!==null,Ie=await this.parseSuccess(St,i,R,e,ne);if(!Ie.ok&&ne){let pe=pi(Ie.error);if(pe){if(ae=!0,await this.runTopUp(pe))continue;R||this.emitter.emit("error:global",Ie.error);}}return Ie}if(Je===401){if(!Se&&this.sessionRefreshHandler){Se=!0;let ne=null;try{ne=await this.sessionRefreshHandler();}catch{ne=null;}if(ne){d=ne;continue}}return this.emitter.emit("auth:unauthorized",void 0),u("unauthorized","Unauthorized")}if(Ul(Je)){let ne=Je===429?await ql(St):null;if(ne!==null&&ne>El)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ne/1e3)} s`,R);if(re&&me<3){me++,await Mt(ne!==null?Ll(ne):Je===429?Bl(me):Xi(me));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Je})`,R)}let bi="";try{bi=await St.text();}catch{}if(Je===409&&/operation in progress/i.test(bi)&&re&&me<3){me++,await Mt(Xi(me));continue}return this.handleWebError(bi,Je,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let o=new AbortController,p=setTimeout(()=>{o.abort();},s);try{let d={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(d.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:d,signal:o.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,i,s,n=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",i)}let p;try{p=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",i)}let d=Jf.safeParse(p);if(!d.success)return this.globalError("Malformed response envelope",i);if(!d.data.Success){let ae=d.data.Error??"Server returned Success=false",me=n&&pi(ae);return !i&&!me&&this.emitter.emit("error:global",ae),u("server",ae)}let R=d.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:d.data.StateEpoch??null,versions:R});let V=d.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let re=d.data.TutorialProgress;re&&re.length>0&&this.emitter.emit("tutorial:systemProgress",re);let Se=t.safeParse(d.data.Data);if(!Se.success){let ae=t.safeParse(Ji(d.data.Data));ae.success&&(Se=ae);}if(!Se.success){let ae=`Validation error (${s}): ${Se.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",ae),i||this.emitter.emit("error:global",ae),u("validation",ae)}return F(Se.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),u("server","PLAY_ACCESS_REQUIRED");s=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),u("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),u("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),u("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function hi(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function Ti(r){return `${hi(r)}T00:00:00.000Z`}function Fl(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Vl(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function ao(r,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;r.InventoryV2??={};let n=r.InventoryV2,o=i.toISOString(),p=new Map,d=new Map,R=new Map,V=new Map,re=new Map,Se=new Map,ae=new Map,me=new Map,St=e.Grant?.PremiumTiers??[],Je=St.length;for(let ne=0;;ne++){let Ie,pe;if(ne===0)Ie=e.Grant?.Standard?.Entries,pe=false;else if(ne-1<Je)Ie=St[ne-1]?.Resources?.Entries,pe=false;else if(ne===1+Je)Ie=e.Consume?.Standard?.Entries,pe=true;else break;if(Ie)for(let le of Ie){if(le.Type==null)continue;let he=Math.max(0,le.Amount??0);if(!(he<=0))switch(le.Type){case "VirtualCurrency":{if(!le.CurrencyID)continue;let de=pe?d:p;de.set(le.CurrencyID,(de.get(le.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!le.CurrencyID)continue;let de=pe?V:R;de.set(le.CurrencyID,(de.get(le.CurrencyID)??new jt__default.default(0)).plus(he));break}case "Item":{if(!le.ItemID)continue;let de=Yf(t,le.CatalogID,le.ItemID),be=(de?de.IsStackable??true:true)?pe?Se:re:pe?me:ae;be.set(le.ItemID,(be.get(le.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||d.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let ne of new Set([...p.keys(),...d.keys()])){let Ie=p.get(ne)??0,pe=d.get(ne)??0,le=Ie-pe,he=n.VirtualCurrencies[ne];he?(he.Amount+=le,he.UpdatedAt=o,he.Daily&&hi(he.Daily.PeriodStartUtc)===hi(i)?(he.Daily.Earned+=Ie,he.Daily.Spent+=pe):he.Daily={PeriodStartUtc:Ti(i),Earned:Ie,Spent:pe}):n.VirtualCurrencies[ne]={Amount:le,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Ti(i),Earned:Ie,Spent:pe}};}}if(s.ccChanged=R.size>0||V.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let ne of new Set([...R.keys(),...V.keys()])){let Ie=R.get(ne)??new jt__default.default(0),pe=V.get(ne)??new jt__default.default(0),le=Ie.minus(pe),he=n.CryptoCurrencies[ne];he?(he.Amount=new jt__default.default(he.Amount).plus(le).toString(),he.UpdatedAt=o):n.CryptoCurrencies[ne]={Amount:le.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(s.itemsChanged=re.size>0||Se.size>0||ae.size>0||me.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let ne=n.UnstackableItems,Ie=new Set([...re.keys(),...Se.keys(),...ae.keys(),...me.keys()]);for(let pe of Ie){let le=(re.get(pe)??0)-(Se.get(pe)??0),he=(ae.get(pe)??0)-(me.get(pe)??0),de=le+he,it=n.Items[pe];it?(le!==0&&(it.StackableAmount+=le),he!==0&&(it.UnstackableAmount+=he),de!==0&&(it.TotalAmount+=de)):n.Items[pe]={StackableAmount:Math.max(0,le),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,de)};}for(let[pe,le]of me){if(le<=0)continue;let he=Object.values(ne).filter(de=>de.ItemID===pe&&de.EquippedSlot==null&&(de.ExpiresAt==null||new Date(de.ExpiresAt)>i)).sort(Zf).slice(0,le).map(de=>de.ItemInstanceID);for(let de of he)delete ne[de];}for(let[pe,le]of ae){let he=Xf(t,pe);for(let de=0;de<le;de++){let it=B();ne[it]={ItemInstanceID:it,ItemID:pe,CatalogID:he,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let bi=r.EventToken;for(let ne=0;;ne++){let Ie,pe;if(ne===0)Ie=e.Grant?.Standard?.EventTokens,pe=false;else if(ne-1<Je)Ie=St[ne-1]?.Resources?.EventTokens,pe=false;else if(ne===1+Je)Ie=e.Consume?.Standard?.EventTokens,pe=true;else break;if(!(!Ie||Ie.length===0))for(let le of Ie){let he=le.Address;if(!he||he.Type==null)continue;let de=le.Amount??0;if(de<=0)continue;let it=eg(bi,he.Type);if(!it)continue;let be=it[he.EntityID];be||(be={},it[he.EntityID]=be),be.Balance??={Current:0,TotalEarned:0,TotalSpent:0},be.Daily??={Date:Ti(i),TotalEarned:0},be.Meta??={};let Di=le.Source&&le.Source.length>0?le.Source:"CustomAction";pe?(be.Balance.Current-=de,be.Balance.TotalSpent+=de):(be.Balance.Current+=de,be.Balance.TotalEarned+=de,hi(be.Daily.Date)!==hi(i)&&(be.Daily={Date:Ti(i),TotalEarned:0}),be.Daily.TotalEarned+=de,be.Daily.EarnedBySource??={},be.Daily.EarnedBySource[Di]=(be.Daily.EarnedBySource[Di]??0)+de,be.Daily.TriggersBySource??={},be.Daily.TriggersBySource[Di]=(be.Daily.TriggersBySource[Di]??0)+1,be.Daily.LastTriggerBySource??={},be.Daily.LastTriggerBySource[Di]=o,be.Meta.JoinedAtUtc||(be.Meta.JoinedAtUtc=o),be.Meta.LastEarnedAtUtc=o),s.tokensChanged=true;}}return s}function Zf(r,e){return r.AcquiredAt!==e.AcquiredAt?r.AcquiredAt<e.AcquiredAt?-1:1:r.ItemInstanceID===e.ItemInstanceID?0:r.ItemInstanceID<e.ItemInstanceID?-1:1}function Yf(r,e,t){let i=r?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function Xf(r,e){let t=r?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function eg(r,e){switch(e){case "TimedEvent":return r.TimedEvent??={};case "Quest":return r.Quest??={};case "Leaderboard":return r.Leaderboard??={};case "CoopEvent":return r.CoopEvent??={};case "Season":return r.Season??={};default:return null}}function _l(r,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let d of Object.values(s))d?.ItemID&&o.add(d.ItemID);for(let d of n){let R=r[d]?.ItemID;R&&o.add(R);}if(o.size===0)return i;let p=d=>n.has(d)||d in s;if(e){for(let[d,R]of Object.entries(e))d in r||p(d)||R&&o.has(R.ItemID)&&i.drop.push(d);for(let[d,R]of Object.entries(r))d in e||p(d)||R&&o.has(R.ItemID)&&(i.restore[d]=R);}return i}function lo(r,e){return r===e||r.startsWith(`${e}:`)}var ss=class r{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){r.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];r.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){r.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=ao(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,o={...n.InventoryV2?.UnstackableItems??{}},p=ao(n,e,i,s),d=_l(o,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],re=d.drop.length>0||Object.keys(d.restore).length>0||R.length>0||V.length>0;if(re){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let Se=n.InventoryV2.UnstackableItems;for(let ae of d.drop)delete Se[ae];for(let[ae,me]of Object.entries(d.restore))Se[ae]=me;for(let[ae,me]of R)Se[ae]=me;for(let ae of V)delete Se[ae];}this.emitResourceChanges(p,re);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof jt__default.default?t:new jt__default.default(t),p=s===void 0?new jt__default.default(0):s instanceof jt__default.default?s:new jt__default.default(s),d=i??new Date().toISOString(),R=n[e];R?(R.Amount=new jt__default.default(R.Amount).plus(o).toString(),p.isZero()||(R.Frozen=new jt__default.default(R.Frozen??0).plus(p).toString()),R.UpdatedAt=d):n[e]={Amount:o.toString(),Frozen:p.toString(),CreatedAt:d,UpdatedAt:d},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=Fl(i)):n.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let o of t)o.RuleID&&(s.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let o=n.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(lo(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((s?n!==s:!lo(n,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let o of n)o.Type!==e||o.TimedEventID!==t||s&&o.TokenEntityID&&o.TokenEntityID!==s||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let s=false;for(let n of Object.values(i))for(let o of Object.values(n.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,p={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")o.Private??={},o.Private[t]=p;else if(e==="Public")o.Public??={},o.Public[t]=p;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!n.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var ns=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var rs=class{user;config;constructor(e){this.user=new ss(e),this.config=new ns;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function tg(r){return r}var ig=0,sg=1500,ng=3,as=class{constructor(e,t,i=null,s="",n="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=n;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return F(void 0);let i=Date.now(),s=[],n=[];for(let d of new Set(e)){let R=this.rules.get(d);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(d,R));continue}(t?.force||!this.state.isStateFresh(d,t?.maxAgeMs))&&n.push(d);}let p=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(F(void 0))])).find(d=>!d.ok);return p&&!p.ok?p:F(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},ig),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(s=>i=s);try{let s=this.state?await this.state.readStateSlice(e):F(void 0),n=s.ok?F(void 0):s;for(let o of t)o(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=os(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(s,i?.maxAgeMs);if(R)return F(R.data);let V=this.loginFailures.get(s);if(V)return this.loginFailures.delete(s),V;let re=this.inflight.get(s);if(re)return re}let n=this.generation.get(s)??0,o=Date.now(),d=t().then(R=>{if(!R.ok)return R;let V=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:uo(e,R.data,V)}),R;let re=this.entries.get(s);if(re&&re.storedAt>=o)return R;let Se=uo(e,R.data,V);return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:Math.min(Se??1/0,V+sg)}),R}).finally(()=>{this.inflight.get(s)===d&&this.inflight.delete(s);});return this.inflight.set(s,d),d}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let s=t.Key?t.Key:void 0,n=os(i.view,s);if(!t.Success){this.loginFailures.set(n,u("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(n),i.apply(o.data,s),this.put(i.view,o.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=Nl({Name:s,Key:t});this.used.get(n)?.n!==this.session&&(this.used.set(n,{Name:s,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>ng||this.used.set(Nl(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(os(e,t))?.data}put(e,t,i){this.register(e);let s=os(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:uo(e,t,n)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(s=>t.has(s))&&this.invalidate(i);}};function os(r,e){return e===void 0?r.key:`${r.key}|${e}`}function Nl(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function uo(r,e,t){let i=r.expiresAt?.(e)??null,s=r.ttlMs!==void 0?t+r.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var ls=class{constructor(e,t){this.storage=e;this.authTypeKey=`Saved_AuthType_${t}`,this.emailKey=`Saved_Auth_Email_${t}`,this.passwordKey=`Saved_Auth_Password_${t}`,this.refreshTokenKey=`Saved_Auth_RefreshToken_${t}`;}storage;authTypeKey;emailKey;passwordKey;refreshTokenKey;get lastAuthType(){let e=this.storage.getString(this.authTypeKey);return rg(e)?e:we.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 rg(r){return r!==null&&Object.values(we).includes(r)}var og=8,ag=100,lg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,jl=["GameLoop"];function ug(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var us=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=we.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let s=this.authContext;if(!s)return a;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(n);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return a;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(i);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(we.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return u("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(we.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let s=await this.ctx.api.authentication.loginWithEmail(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(we.Email);return n.ok&&this.keepEmailCredentials(e,t),n}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let s=await this.ctx.api.authentication.registerWithEmail(i);return s.ok?(this.pendingRegistration={email:e,password:t},F({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(we.Email);return n.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,n}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?F(void 0):i}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let i=await this.ctx.api.authentication.loginWithGoogle(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(we.Google)):i}async loginWithApple(e,t){if(!e?.trim())return u("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(we.Apple)):s}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=i,s.Platform=this.ctx.platform.getPlatform(),s.Device=this.ctx.platform.getDeviceModel(),s.DeviceID=this.ctx.platform.getDeviceID();let n=await this.ctx.api.authentication.loginWithWallet(s);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(we.Wallet)):n}async loginWithSsoCode(e){if(!e)return u("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(we.iDosGames)):i}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=i,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==we.None?e:we.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let s=await this.ctx.api.authentication.refreshSession(i);return s.ok?(this.applyRefresh(s.data),"ok"):(ug(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case we.Email:return this.loginWithEmail(t,i);case we.Device:case we.None:return this.loginWithDeviceID();case we.Telegram:return this.loginWithTelegram();default:return Promise.resolve(u("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;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!==we.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===we.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&&lg.test(e)}static isValidPasswordLength(e){return e.length>=og&&e.length<=ag}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.sessionAuthType=we.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e){let t=await this.ctx.userService.getClientStateExcept(jl,jl);return t.ok&&(this.sessionAuthType=e,this.rememberSession?(this.ctx.authStore.saveAuthType(e),this.ctx.authStore.saveRefreshToken(this.sessionRefreshToken)):this.ctx.authStore.clear(),this.ctx.emitter.emit("auth:loggedIn",void 0)),t}};var cg="idos:cfg",di=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Wl(t)}`:e&&e.length>0?`f:${Wl(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${cg}:${this.titleId}:${e}`}};function Wl(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var Kl="idos:loc",mi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[s,n]of Object.entries(t))typeof n=="number"&&n>0&&(i[s]=n);return i}catch{return {}}}async noteVersion(e,t){let i=await this.readVersions();i[e]!==t&&(i[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(i)));}keyOf(e){return `${Kl}:${this.titleId}:${e}`}versionsKey(){return `${Kl}:${this.titleId}:versions`}};var pg="idos:sec",cs=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let i=JSON.parse(t);return !i||typeof i!="object"||i.v!==e||!i.s||typeof i.s!="object"?{}:i.s}catch{return {}}}async write(e,t){try{let i={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(i));}catch{}}keyOf(){return `${pg}:${this.titleId}`}};var hg="idos:state",ps=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,s){if(!(!e||!t))try{let n={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}keyOf(e){return `${hg}:${this.titleId}:${e}`}};function dg(r,e){if(!r)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return r;let i={};for(let[s,n]of Object.entries(r))t.has(s.toLowerCase())||(i[s]=n);return i}function co(r,e,t,i){let s={...r??{}};if(!e||!t||!i)return s;for(let[n,o]of Object.entries(t))i[n]===o&&n in e&&(s[n]=e[n]);return s}function mg(r){return {...r??{}}}function po(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var hs=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let s=this.confirmedAt[e];return s===void 0?false:t===void 0||i-s<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=dg(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,o]of Object.entries(t)){let p=this.versions[n];p!==o&&(p!==void 0&&o===p+1?(this.versions[n]=o,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=mg(t);let s=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=s;this.dirty=true;let n=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&n.add(o);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,o]of Object.entries(t??{}))this.versions[n]!==o&&s.push(n),this.versions[n]=o,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Ql=u("server","Title configuration is unavailable (CDN and API both failed)."),ds=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),RelatedEntityID:B()}:null}get configCache(){return this.cache??=new di(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new mi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new cs(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new hs(new ps(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return a;let t=di.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let o=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return o==null?Ql:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,o),await this.applyClientState(n.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=co(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=po(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,i,s){let n=e.TitleConfigVersion;if(i&&n&&i.v===n)return i.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return n&&await this.configCache.write(t,n,p),p}let o=await this.fetchConfigFromApi(s);return o!=null?(n&&await this.configCache.write(t,n,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return a;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=di.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let p=await this.ctx.api.user.getClientStateExcept(i);if(!p.ok)return p;let d=await this.resolveTitleConfig(p.data,s,n,{ExcludeFields:t??[]});return d==null?Ql:(this.finishStateHandshake(p.data,o),await this.restoreSections(p.data.TitleConfigVersion,d),await this.applyClientState(p.data,d,e,t),this.ctx.cache.acceptLoginViews(p.data.Views),await this.applyLocalization(p.data.Localization),await this.flushState(o),p)}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,s={};for(let[n,o]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=o);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,o)=>{i[n]!=null||o==null||(s[n]=o,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let o=n.Entries??{},p=n.Version??0,d=n.Locale??e;return p>0&&await this.localizationCache.write(d,p,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):a}async getUserState(e){let t=this.baseRequest();if(!t)return a;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=co(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let o=i.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([R,V])=>o[R]!==V||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,p);let d=po(s.data);return d&&(this.stateStore.afterSliceRead(d,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let s=this.baseRequest();if(!s)return a;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=i;let n=await this.ctx.api.user.addUsageTime(s);return n.ok&&this.ctx.emitter.emit("user:usageTimeAdded",n.data),n}async deleteUserAccount(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return a;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,s){let n=i?.includes("GameLoop")===true,o=s?.includes("GameLoop")===true,p=n?this.ctx.data.user.state?.GameLoop:void 0,d=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let R=this.ctx.data.user.state;n&&R&&R.GameLoop==null&&(R.GameLoop=p);let V=this.ctx.data.config.titlePublicConfiguration;o&&V&&V.GameLoop==null&&(V.GameLoop=d),this.ctx.emitter.emit("user:clientStateReceived",e);}};var fs=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,s,n,o){if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(n<=0)return u("client","Amount must be positive.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===ut.Crypto||i===ut.Crypto)return u("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return a;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${s}_${B()}`},d=await this.ctx.api.currency.convert(p);if(d.ok){let R=d.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.SourceID,Amount:R.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.TargetID,Amount:R.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return d}async cryptoConvert(e,t,i,s,n,o){let p=n instanceof jt__default.default?n:new jt__default.default(n);if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(p.lte(0))return u("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===ut.Virtual&&i===ut.Virtual)return u("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ut.Virtual&&!p.isInteger())return u("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return a;let d={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:p.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${s}_${B()}`},R=await this.ctx.api.currency.cryptoConvert(d);if(R.ok){let V=R.data,re=[],Se=[];if(V.SourceType===ut.Virtual&&re.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===ut.Virtual&&Se.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),re.length>0||Se.length>0){let ae={Consume:re.length>0?{Standard:{Entries:re}}:null,Grant:Se.length>0?{Standard:{Entries:Se}}:null};this.ctx.data.user.applyResourceOperation(ae,this.ctx.data.config.itemDefinitions);}V.SourceType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new jt__default.default(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new jt__default.default(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return R}};var gs=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let s=e.trim();if(!s)return u("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${s}_${B()}`};t&&t.length>0&&(n.FodderInstanceIDs=[...t]);let o=await this.ctx.api.item.upgradeLevel(n);return o.ok&&(this.ctx.data.user.patchEquippedItemLevel(o.data.ItemInstanceID??s,o.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",o.data)),o}async upgradeLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let s of i.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var Hl=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:xt.nullish(),AllowedPlatforms:zod.z.array(Ni).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ue=zod.z.record(zod.z.string(),Hl),fg=zod.z.object({Store:ji,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var ho=zod.z.object({ServerTimeUtc:c,OfferID:zod.z.string(),Count:zod.z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),$l=zod.z.array(ve(ho)),gg=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:c,LastPurchasedAt:c}),yg=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:c}),Jl=zod.z.object({Purchases:zod.z.record(zod.z.string(),gg).nullish(),Rotations:zod.z.record(zod.z.string(),yg).nullish()}).passthrough().transform(r=>r),Dt=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ys=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Rg={Fixed:"Fixed",Title:"Title",Player:"Player"},Cg=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:Z.nullish()}).passthrough(),Zl=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(Cg).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),Sg=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Rotation:K.nullish()}).passthrough(),xg=zod.z.object({SlotID:zod.z.string().nullish(),Identity:Dt.nullish(),Availability:ys.nullish(),Rotation:Zl.nullish(),Presets:Sg.nullish()}).passthrough(),bg=zod.z.object({Identity:K.nullish(),Availability:K.nullish()}).passthrough(),Dg=zod.z.object({SectionID:zod.z.string().nullish(),Identity:Dt.nullish(),Availability:ys.nullish(),Slots:zod.z.record(zod.z.string(),xg).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:bg.nullish()}).passthrough(),Yl=zod.z.object({Sections:zod.z.record(zod.z.string(),Dg).nullish()}).passthrough(),Pg=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Layout:K.nullish()}).passthrough(),Ig=zod.z.object({StoreID:zod.z.string().nullish(),Identity:Dt.nullish(),Availability:ys.nullish(),Layout:Yl.nullish(),Presets:Pg.nullish()}).passthrough(),Xl=zod.z.object({Options:ue.nullish(),CompareAt:zod.z.record(zod.z.string(),xt).nullish()}).passthrough(),eu=zod.z.object({Grant:H.nullish()}).passthrough(),tu=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),vg=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish(),Availability:K.nullish()}).passthrough(),Tg=zod.z.object({OfferID:zod.z.string().nullish(),Identity:Dt.nullish(),Pricing:Xl.nullish(),Reward:eu.nullish(),Availability:tu.nullish(),Presets:vg.nullish()}).passthrough(),Ag=zod.z.object({Identity:zod.z.record(zod.z.string(),Dt).nullish(),Availability:zod.z.record(zod.z.string(),ys).nullish(),Layout:zod.z.record(zod.z.string(),Yl).nullish(),Rotation:zod.z.record(zod.z.string(),Zl).nullish(),Pricing:zod.z.record(zod.z.string(),Xl).nullish(),Reward:zod.z.record(zod.z.string(),eu).nullish(),OfferAvailability:zod.z.record(zod.z.string(),tu).nullish()}).passthrough(),Rs=zod.z.object({Stores:zod.z.record(zod.z.string(),Ig).nullish(),StoreOffers:zod.z.record(zod.z.string(),Tg).nullish(),Presets:Ag.nullish()}).passthrough(),kg=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:c.nullish()}).passthrough(),zg=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:xt.nullish(),CompareAtCost:xt.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),wg=zod.z.object({OfferID:zod.z.string(),Identity:Dt.nullish(),PriceOptions:zod.z.array(zg).nullish(),Rewards:H.nullish(),State:kg.nullish()}).passthrough(),Mg=zod.z.object({SlotID:zod.z.string(),Identity:Dt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:c.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:wg.nullish()}).passthrough(),Og=zod.z.object({SectionID:zod.z.string(),Identity:Dt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(Mg).nullish()}).passthrough(),Ug=zod.z.object({StoreID:zod.z.string(),Identity:Dt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:c.nullish(),Sections:zod.z.array(Og).nullish()}).passthrough(),Cs=zod.z.object({ServerTimeUtc:c,Stores:zod.z.array(Ug).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Wt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront"},Eg="OFFER_NOT_IN_ROTATION";var iu="Store",su={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=null;for(let t of r.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},Ss=class{constructor(e){this.ctx=e;e.cache.bindLoginView(su,{schema:Cs,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return u("client","OfferID is required.");if(t<1)return u("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return a;let n={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,RelatedEntityID:`store_buy_${e}_${s.userID}_${B()}`},o=await this.ctx.api.store.purchase(n);if(o.ok){let p=o.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return o}async purchaseBatch(e){if(!e||e.length===0)return u("client","purchases is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||!n.Data.OfferID||(this.ctx.data.user.patchStorePurchase(n.Data.OfferID,n.Data.Count,n.Data.ServerTimeUtc),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(iu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(iu,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(su,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=s.RefreshesAtUtc;n&&(e===null||Date.parse(n)<Date.parse(e))&&(e=n);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var xs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?F(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return u("client","Receipt is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},n=await this.ctx.api.purchase.validatePurchase(s);return n.ok&&this.applyValidation(n.data),n}async buyWithTelegramStars(e,t){if(!e)return u("client","productID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(i);return s.ok&&t?.open!==false&&this.ctx.platform.openInvoice(s.data.InvoiceLink),s}async validatePurchasesBatch(e){if(!e||e.length===0)return u("client","receipts is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let s of i.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Pt=["https://idosgames.com","https://www.idosgames.com"];function nu(r){return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r.endsWith(".localhost")}function bs(r){if(Pt.includes(r))return true;if(typeof window>"u"||!nu(window.location.hostname))return false;try{return nu(new URL(r).hostname)}catch{return false}}var ru="IDOS_PLATFORM_WALLET_ACK",ou="PLATFORM_WALLET_UNAVAILABLE",qg=5e3,Lg=18e4;function Bg(){let r=[...Pt],e=window.location.ancestorOrigins?.[0];return e&&!r.includes(e)&&bs(e)&&r.push(e),r}function Gg(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ai(r,e,t,i={}){let s={ok:false,error:ou,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(s);let n=window.parent;if(!n)return Promise.resolve(s);let o=Gg(),p=i.answerTimeoutMs??Lg;return new Promise(d=>{let R=false,V,re=ae=>{R||(R=true,window.removeEventListener("message",Se),clearTimeout(V),d(ae));},Se=ae=>{if(!bs(ae.origin))return;let me=ae.data;if(!(!me||me.requestId!==o)){if(me.type===ru){clearTimeout(V),V=setTimeout(()=>re({ok:false,error:"TIMEOUT",data:{}}),p);return}me.type===e&&re({ok:me.ok===true,error:typeof me.error=="string"?me.error:void 0,data:me});}};V=setTimeout(()=>re(s),qg),window.addEventListener("message",Se);for(let ae of Bg())try{n.postMessage({type:r,requestId:o,...t},ae);}catch{}})}var mo={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},Fg=15*6e4,Vg=/^[a-z0-9]{8}-preview\.idos\.games$/;function fo(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !Vg.test(window.location.hostname.toLowerCase())}async function go(r){let e=await Ai(mo.request,mo.response,{titleID:r.titleID,userID:r.userID,currencyID:r.currencyID,amount:r.amount},{answerTimeoutMs:Fg});return e.ok?{ok:true}:{ok:false,error:e.error}}var au=3,_g=700,Ds=class{constructor(e){this.ctx=e;fo()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return pi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await go({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return i.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:i.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=au;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===au)break;await Mt(_g);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===_i.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==_i.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let n=this.cryptoBalance(i.CurrencyID);return n>=s?null:{currencyID:i.CurrencyID,required:s,available:n,missing:s-n}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var lu="Lootbox",Ps=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(lu,e);if(t){let n={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(lu,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s){if(!e)return u("client","LootboxID is required.");if(t<1)return u("client","Count must be at least 1.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,RelatedEntityID:`lootbox_${e}_${i??"default"}_${B()}`},o=await this.ctx.api.lootbox.open(n);if(o.ok){let p=o.data;p.TriggeredPity&&p.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,p.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",p);}return o}};var yo="Reward";function Ro(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Is=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Reward",{needsServer:()=>!t&&Object.values(e.cache.configSection(yo)?.Comebacks??{}).some(i=>i?.TrackPresenceOnRead===true),refresh:async()=>{let i=await this.getUserRewardsState();return i.ok&&(t=true),i}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(yo,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(yo,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${B()}`},s=await this.ctx.api.reward.claimDailyReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchDailyCalendarState(n.CalendarID,n.DailyState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",n);}return s}async collectIdleAccrual(e){if(!Ro(e))return u("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${B()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let s=i.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return i}async claimComebackReward(e){if(!Ro(e))return u("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${B()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return i}async claimReward(e){if(!Ro(e))return u("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${B()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return i}};var vs="Tutorial",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"]},Ts=class{constructor(e){this.ctx=e;e.cache.bindLoginView(uu,{schema:$i,apply:i=>this.applyUserTutorialState(i)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(vs)?.Flows??{}).length>0,refresh:async()=>{let i=await this.getUserTutorialState();return i.ok&&(t=true),i}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(vs,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(vs,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}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 a;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${B()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return u("client","FlowID is required.");if(!t||t.length===0)return u("client","stepIDs is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${B()}`},n=await this.ctx.api.tutorial.completeStepsBatch(s);return n.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",n.data)),n}async skipStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.skipStep(i))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${B()}`},s=await this.ctx.api.tutorial.claimFlowReward(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let s=e?.trim();if(!s)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},o=await t(n);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,s){let n=e?.trim(),o=t?.trim();if(!n)return u("client","FlowID is required.");if(!o)return u("client","StepID is required.");if(!this.ctx.auth.context)return a;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:o};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let d=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(p);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,o,d,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(vs)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}};var As=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return a;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return u("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return u("client","campaignID is required.");if(!t)return u("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return a;s.CampaignID=e,s.WalletAddress=t,i&&(s.Amount=i);let n=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return n.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",n.data),n}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Oe=zod.z.object({Username:zod.z.string().nullish(),Country:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Premium:zod.z.boolean().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BoardRank:zod.z.number().nullish()}).passthrough();var Ng={Global:"Global",Announcement:"Announcement",Group:"Group"},pu=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),jg={None:"None",Language:"Language",Region:"Region"},Wg=zod.z.enum(["None","Language","Region"]).catch("None"),Kg={Anyone:"Anyone",Friends:"Friends"},Qg=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),Hg={Reject:"Reject",Mask:"Mask"},$g=zod.z.enum(["Reject","Mask"]).catch("Reject"),Jg={Player:"Player",Publisher:"Publisher",System:"System"},Zg=zod.z.enum(["Player","Publisher","System"]).catch("Player"),Yg={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Xg=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),hu=zod.z.object({Gate:Z.nullish(),Schedule:ge.nullish()}).passthrough(),du=zod.z.object({Gate:Z.nullish(),Limits:Re.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),mu=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),ey=zod.z.object({Availability:K.nullish(),Write:K.nullish(),Retention:K.nullish()}).passthrough(),ty=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:Xg.nullish(),Type:pu.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:Wg.nullish(),Capacity:zod.z.number().nullish(),Availability:hu.nullish(),Write:du.nullish(),Retention:mu.nullish(),Presets:ey.nullish()}).passthrough(),iy=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Qg.nullish(),Limits:Re.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),sy=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:$g.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Re.nullish()}).passthrough(),ny=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),ry=zod.z.object({Availability:zod.z.record(zod.z.string(),hu).nullish(),Write:zod.z.record(zod.z.string(),du).nullish(),Retention:zod.z.record(zod.z.string(),mu).nullish()}).passthrough(),fu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),ty).nullish(),Direct:iy.nullish(),Moderation:sy.nullish(),Polling:ny.nullish(),Presets:ry.nullish()}).passthrough(),oy=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),cu=zod.z.object({LastAt:zod.z.string().nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:zod.z.string().nullish(),TotalCount:zod.z.number().nullish(),LastTextHash:zod.z.string().nullish()}).passthrough();zod.z.object({MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish(),Ignored:zod.z.array(zod.z.string()).nullish(),Channels:zod.z.record(zod.z.string(),oy).nullish(),Limits:zod.z.record(zod.z.string(),cu).nullish(),ReportLimits:cu.nullish()}).passthrough();var Co=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),ks=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:Oe.nullish(),AuthorType:Zg.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),ay=zod.z.object({ChannelID:zod.z.string().nullish(),RoomID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Type:pu.nullish(),CanWrite:zod.z.boolean().nullish(),WriteBlockedReason:zod.z.string().nullish(),SlowModeSeconds:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),zs=zod.z.object({Channels:zod.z.array(ay).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),ly=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(ks).nullish(),NextCursor:Co.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),gu=zod.z.object({Rooms:zod.z.array(ly).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),yu=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(ks).nullish(),NextBefore:Co.nullish()}).passthrough(),Ru=zod.z.object({Message:ks.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),Cu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Oe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),uy=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Oe.nullish(),LastMessage:ks.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Su=zod.z.object({Conversations:zod.z.array(uy).nullish()}).passthrough(),fi=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Co.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),xu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),Ke={GetChatDefinitions:"GetChatDefinitions",GetChannels:"GetChannels",Poll:"Poll",GetHistory:"GetHistory",GetConversations:"GetConversations",SendMessage:"SendMessage",OpenDirectChannel:"OpenDirectChannel",MarkRead:"MarkRead",JoinChannel:"JoinChannel",LeaveChannel:"LeaveChannel",ReportMessage:"ReportMessage",IgnoreUser:"IgnoreUser",UnignoreUser:"UnignoreUser"};var bu="Chat",Du={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Du,{schema:zs,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(bu,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(bu,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(Du,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let s of i.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return i}async getHistory(e,t,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),i&&(s.Limit=i),this.ctx.api.chat.getHistory(s)):a}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return a;s.ChannelID=e,s.Text=t,i&&(s.Locale=i);let n=await this.ctx.api.chat.sendMessage(s);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Text=t;let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):a}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):a}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(i);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):a}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):a}async reportMessage(e,t,i,s){let n=this.ctx.authedRequest();return n?(n.RoomID=e,n.MessageID=t,n.Reason=i,s&&(n.Comment=s),this.ctx.api.chat.reportMessage(n)):a}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):a}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):a}resetCursors(){this.cursors.clear();}};var cy={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},py=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),hy={Player:"player",Title:"title",Creator:"creator"},gi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Pu=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),dy=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),So=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:py.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(dy).nullish()}).passthrough(),Iu=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(So).nullish()}).passthrough(),It={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var my="IDOS_PLATFORM_PUSH_REQUEST",fy="IDOS_PLATFORM_PUSH_RESPONSE",gy=12e4;function vu(r){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,n=d=>{s||(s=true,window.removeEventListener("message",o),clearTimeout(p),i(d));},o=d=>{let R=d?.data;!R||R.type!==fy||R.requestId!==t||Pt.includes(d.origin)&&n(R.ok===true);},p=setTimeout(()=>n(false),gy);window.addEventListener("message",o);for(let d of Pt)try{e.postMessage({type:my,requestId:t,titleID:r},d);}catch{}})}var Ms=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return It.Unsupported;if(this.isEmbedded())return It.Embedded;if(!this.isSupported())return It.Unsupported;let t=Notification.permission;return t==="denied"?It.Blocked:t!=="granted"?It.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?It.Subscribed:It.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return u("client","Push notifications are not available for this title.");if(this.isEmbedded())return await vu(this.ctx.settings.titleID)?F({Where:"portal",Subscription:null}):u("client","The portal did not complete the subscription.");if(!this.isSupported())return u("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return u("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:yy(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return a;let d=o.toJSON();p.PushEndpoint=d.endpoint,p.PushP256dh=d.keys?.p256dh,p.PushAuth=d.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(p);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),F({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return a;if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return u("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):a}async unsubscribeByHash(e){if(!e)return u("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return a;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function yy(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var Os=Object.freeze({}),Us=class{constructor(e){this.ctx=e;}ctx;table={...Os};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new mi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),s=this.lookup(i)??this.lookup(e);return s===void 0?this.onMissing(e):t?Ry(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Os},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return a;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:o}=i.data,p=null;if(o){let d=await this.loadTableFromApi(o);d.ok&&(p=d.data.table);}return this.table=n,this.fallbackTable=p,this.currentFallbackLocale=o,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:o,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):a}reset(){this.table={...Os},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:B()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return a;t.Locale=e;let i=await this.cache.read(Tu(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,o=n.Locale??Tu(e),p=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:R?.t??{...Os},fallbackLocale:n.FallbackLocale??null}}}let d=n.Entries??{};return p>0&&await this.cache.write(o,p,d),{ok:true,data:{locale:o,table:d,fallbackLocale:n.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function Ry(r,e){return r.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function Tu(r){return r.trim().replace(/_/g,"-").toLowerCase()}var xo="Quest",Cy={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:r=>{let e=Date.now(),t=null,i=[...Object.values(r.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(r.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},Es=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(xo)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(s)){let p=Date.parse(n[o]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=i&&t<p)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true,{forceRefresh:true});return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(xo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(xo,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(Cy,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let s=i.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let i=e.trim();if(!i)return u("client","QuestID is required.");if(!this.ctx.auth.context)return a;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${B()}`},o=await this.ctx.api.quest.claimQuestReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return u("client","quests is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchQuestStatus(n.Data.QuestID,n.Data.CycleID,"Claimed"),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return u("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${B()}`},o=await this.ctx.api.quest.claimMilestoneReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchMilestoneClaimed(n.Data.CycleID,n.Data.MilestoneID),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return u("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${B()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return u("client","MetricID is required.");if(t<0)return u("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},n=await this.ctx.api.quest.addQuestProgress(s);return n.ok&&(this.ctx.data.user.patchQuestProgressUpdates(n.data.Updates),this.ctx.emitter.emit("quest:progressAdded",n.data)),n}};var Au=zod.z.object({}).passthrough().transform(r=>r);var Sy=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),xy=zod.z.object({Schedule:zod.z.array(Sy).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),by=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:c.nullish(),NextBonusStartUtc:c.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),Dy=zod.z.object({Milestones:K.nullish()}).passthrough(),bo=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Category:zod.z.string().nullish(),Token:Nt.nullish(),TokenSources:zod.z.array(st).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),Presets:Dy.nullish(),BonusWindow:xy.nullish()}).passthrough(),Py=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:bo.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Iy=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:ge.nullish(),Content:bo.nullish(),Events:zod.z.array(Py).nullish(),Gate:Z.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),vy=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),Ty=zod.z.object({Milestones:zod.z.record(zod.z.string(),ui).nullish()}).passthrough(),qs=zod.z.object({Definitions:zod.z.record(zod.z.string(),Iy).nullish(),Settings:vy.nullish(),Presets:Ty.nullish()}).passthrough(),Ay=zod.z.object({Type:vi,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:bo.nullish(),Progress:Au.nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:Le.nullish(),BonusWindow:by.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Ls=zod.z.object({ActiveEvents:zod.z.array(Ay).nullish()}).passthrough(),ku=zod.z.object({Tokens:zod.z.record(zod.z.string(),Au).nullish()}),Do=zod.z.object({Type:vi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Po=zod.z.object({Type:vi.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:M.nullish(),Inventory:Q.nullish()}),ky=zod.z.object({Type:vi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Io=zod.z.array(ve(Po)),zu=zod.z.array(ve(Do)),wu=zod.z.array(ve(ky)),ot={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Mu="TimedEvent",Ou={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:r=>{let e=null;for(let t of r.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Bs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ou,{schema:Ls,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(Ou,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(Mu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Mu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,s,n,o,p=1){if(!t)return u("client","LteID is required.");if(!i)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let d={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:o,RollMultiplier:p},R=await this.ctx.api.timedEvent.grantTokens(d);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return u("client","LteID is required.");if(i<=0)return u("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},n=await this.ctx.api.timedEvent.spendTokens(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",n.data)),n}async claimMilestone(e,t,i){if(!t||!i)return u("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let o=n.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return a;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return u("client","spends is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return u("client","grants is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let s=i.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var zy=zod.z.object({UserID:zod.z.string(),Score:j.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:c.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:Oe.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),ki=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:j.nullish(),CycleEndUtc:c.nullish(),TopUsers:zod.z.array(zy).nullish(),BracketID:zod.z.string().nullish()}),wy=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:c.nullish(),ClaimDeadlineUtc:c.nullish(),MilestoneTokensEarned:j.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Gs=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:j.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:j.nullish(),MilestoneTokensEarned:j.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:Le.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(wy).nullish()}),Fs=zod.z.object({LeaderboardID:zod.z.string(),NewScore:j,CycleVersion:zod.z.number()}),Vs=zod.z.object({ServerTimeUtc:c,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),_s=zod.z.object({ServerTimeUtc:c,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Uu=zod.z.array(ve(ki)),Ns=zod.z.array(ve(Gs)),Eu=zod.z.array(ve(Vs)),qu=zod.z.array(ve(_s)),Lu=zod.z.array(ve(Fs)),My=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:ve(Vs).nullish(),Milestones:zod.z.array(ve(_s)).nullish()}),Bu=zod.z.array(My),Oy=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:ve(ki).nullish(),Progress:ve(Gs).nullish()}),Gu=zod.z.array(Oy),Uy=zod.z.string(),Fu=zod.z.object({Rank:zod.z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:Yr.nullish()}).passthrough(),Ey=zod.z.object({RankRewards:zod.z.array(Fu).nullish()}).passthrough(),qy=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Ly=zod.z.object({Milestones:K.nullish(),RankRewards:K.nullish()}).passthrough(),By=zod.z.object({LeaderboardID:zod.z.string(),DisplayName:zod.z.string().nullish(),ScoreDisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsEnabled:zod.z.boolean().nullish(),ScoreAggregation:Uy.nullish(),Schedule:ge.nullish(),ChainEvents:zod.z.array(qy).nullish(),Gate:Z.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(Fu).nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),Presets:Ly.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(st).nullish()}).passthrough(),Gy=zod.z.object({Milestones:zod.z.record(zod.z.string(),ui).nullish(),RankRewards:zod.z.record(zod.z.string(),Ey).nullish()}).passthrough(),js=zod.z.object({Definitions:zod.z.record(zod.z.string(),By).nullish(),Presets:Gy.nullish()}).passthrough(),Ve={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 Vu="Leaderboard",_u={key:"leaderboard.progress",login:"LeaderboardProgress",ttlMs:5*6e4,dependsOn:["Leaderboard","EventToken"],invalidateOn:["leaderboard:scoreSubmitted","leaderboard:scoresSubmittedBatch","leaderboard:cycleRewardClaimed","leaderboard:cycleRewardsClaimedBatch","leaderboard:milestoneClaimed","leaderboard:milestonesClaimedBatch","leaderboard:allRewardsClaimedBatch"]},Ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(_u,{schema:Ns,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Vu,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Vu,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return u("client","LeaderboardID is required.");if(t<=0)return u("client","Score must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(i);if(s.ok){let n=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),n.NewScore,t,n.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",n);}return s}async submitScoreFromSource(e,t,i,s,n=1){if(!e)return u("client","LeaderboardID is required.");if(!t)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},p=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(p.ok){let d=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),d.NewScore,d.NewScore,d.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",d);}return p}async claimCycleReward(e){if(!e)return u("client","LeaderboardID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return i}async claimMilestone(e,t,i){if(!e||!t)return u("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let o=n.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return n}async getFriendsLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(u("client","leaderboardIDs is required.")):this.ctx.cache.read(_u,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return u("client","scores is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of s.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let s of i.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var vo=zod.z.object({}).passthrough().transform(r=>r),Ks=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>Ku).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:j.nullish(),UserState:vo.nullish(),NextTier:zod.z.lazy(()=>Wu).nullish()}).passthrough(),Nu=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:j.nullish(),NewStatusTokens:j.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),To=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),ju=ft(To);var Wu=zod.z.object({Tier:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredTokens:j.nullish(),TierReachedReward:H.nullish()}).passthrough(),Ku=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:j.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(Wu).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var Fy=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ge.nullish(),Seasons:zod.z.array(Ku).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:Z.nullish()}).passthrough(),Qs=zod.z.object({Chains:zod.z.record(zod.z.string(),Fy).nullish()}).passthrough(),Ut={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Qu="Season",Hu={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=Date.parse(r.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Hs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Hu,{schema:Ks,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Qu,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Qu,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(Hu,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(u("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return u("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","Amount must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${B()}`},s=await this.ctx.api.season.grantStatusTokens(i);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","TierNumber must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${B()}`},s=await this.ctx.api.season.claimTierReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",n);}return s}async claimTierRewardsBatch(e,t){if(!e)return u("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return u("client","TierNumbers is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${B()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let o=n.data;for(let p of o.Items??[]){let d=p.Data?.TierNumber;p.Success&&typeof d=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,d);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return n}};var $u="Premium",$s=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection($u,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection($u,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(i);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,i="Default",s=1){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,RelatedEntityID:`premium_purchase_${e}_${t}`},o=await this.ctx.api.premium.purchaseItemOrCurrency(n);if(o.ok){let p=o.data;p.Premium&&this.ctx.data.user.applyPremium(p.Premium),this.ctx.data.user.applyResourceOperation(p.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",p);}return o}async purchaseRealMoney(e,t,i,s,n,o,p,d){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!s||!n)return u("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return a;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:o,PackageName:p,AppStoreEnvironment:d,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(R);if(V.ok){let re=V.data;re.Premium&&this.ctx.data.user.applyPremium(re.Premium),this.ctx.data.user.applyResourceOperation(re.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",re);}return V}};var Js=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:c.nullish()}),Ao=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:j.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),Js).nullish(),UpdatedAt:c.nullish()}).passthrough(),Ju=zod.z.object({Characters:zod.z.record(zod.z.string(),Ao).nullish()}),ko=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),zo=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),Zu=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Js).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),Yu=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),Vy=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Xu=zod.z.object({ServerTimeUtc:c,Characters:zod.z.record(zod.z.string(),Vy).nullish(),Inventory:Q.nullish()}),wo=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:M.nullish()}),ec=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Js.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),tc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Js.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),ic=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),_y=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:c.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:ue.nullish()}),Ny=zod.z.object({CharacterID:zod.z.string(),CharacterOpen:zod.z.boolean().nullish(),DefaultSkinID:zod.z.string().nullish(),WornSkinID:zod.z.string().nullish(),Skins:zod.z.array(_y).nullish()}),sc=zod.z.object({ServerTimeUtc:c,Characters:zod.z.record(zod.z.string(),Ny).nullish()}),nc=ft(wo),rc=ft(zo),oc=ft(ko),Mo=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),ac=zod.z.object({StatID:zod.z.string(),TypeID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish(),Weight:zod.z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Fe.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Fe.nullish(),RankCurve:Fe.nullish(),Requirements:zod.z.array(Mo).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),jy=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Mo).nullish(),AllowedRarityIDs:zod.z.array(zod.z.string()).nullish(),AllowedItemTags:zod.z.array(zod.z.string()).nullish(),MinItemLevel:zod.z.number().nullish(),MaxItemLevel:zod.z.number().nullish()}).passthrough(),lc=zod.z.object({Slots:zod.z.record(zod.z.string(),jy).nullish()}).passthrough(),uc=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Lore:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Wy=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ky=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:ue.nullish()}).passthrough(),Qy=zod.z.object({Stats:K.nullish(),Levels:K.nullish(),Equipment:K.nullish()}).passthrough(),cc=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Fe.nullish()}).passthrough(),Oo="@skin";function Hy(r){return !!r&&r.startsWith("@")}var $y=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),Jy=zod.z.object({PriceOptions:ue.nullish(),Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Zy=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Mo).nullish()}).passthrough(),Yy=zod.z.object({SkinID:zod.z.string().nullish(),Identity:uc.nullish(),Item:$y.nullish(),Sale:Jy.nullish(),Requirements:Zy.nullish()}).passthrough(),Xy=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),Yy).nullish()}).passthrough(),eR=zod.z.object({CharacterID:zod.z.string(),Identity:uc.nullish(),Classification:Wy.nullish(),Unlock:Ky.nullish(),Presets:Qy.nullish(),Equipment:lc.nullish(),Stats:zod.z.record(zod.z.string(),ac).nullish(),RankLadder:cc.nullish(),RankStatCurve:Fe.nullish(),StatMaxLevelCurve:Fe.nullish(),Skins:Xy.nullish()}).passthrough(),tR=zod.z.object({Stats:zod.z.record(zod.z.string(),ac).nullish()}).passthrough(),iR=zod.z.object({RankLadder:cc.nullish()}).passthrough(),sR=zod.z.object({Equipment:lc.nullish()}).passthrough(),nR=zod.z.object({Stats:zod.z.record(zod.z.string(),tR).nullish(),Levels:zod.z.record(zod.z.string(),iR).nullish(),Equipment:zod.z.record(zod.z.string(),sR).nullish()}).passthrough(),Zs=zod.z.object({Definitions:zod.z.record(zod.z.string(),eR).nullish(),Presets:nR.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"},rR="SKIN_ALREADY_OWNED";var Uo="Character",Ys=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Uo)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,n])=>n?.Unlock?.UnlockedByDefault===true&&!i[n.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Uo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Uo,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${B()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return u("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${B()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok){let o=n.data;this.ctx.data.user.patchCharacter(o.CharacterID,p=>{p.StatLevels??={},p.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(p.Power=o.Power),p.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return n}async upgradeCharacterLevel(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${B()}`,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level=n.NewLevel,n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(i);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(i);if(s.ok){let n=s.data;this.applyUnequipChangesLocally(e,n),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:n.ClearedSlotIDs??[],power:n.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${B()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok){let o=n.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return n}async equipSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let o=n.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return n}async unequipSkin(e){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let s=i.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):a}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,Oo,t??null),n.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return u("client","characterIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level??=1,n.StatLevels??={},n.Equipment??={},s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level=s.NewLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(n.StatLevels??={},n.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.StatLevels??={},n.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[s,n]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,s,n);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let n of i)s.patchCharacterEquipment(e,n,null);s.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,s]of Object.entries(e.Characters??{})){for(let n of s.ClearedSlotIDs??[])t.patchCharacterEquipment(i,n,null);t.patchCharacter(i,n=>{s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=e.ServerTimeUtc;});}}};var pc="Match",Xs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,o){let p=this.ctx.auth.context;if(!p)return a;let d={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:o,RelatedEntityID:`pvp_create_${p.userID}_${B()}`},R=await this.ctx.api.match.createMatch(d);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 u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(i);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,s){let n=this.ctx.auth.context;if(!n)return a;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${B()}`},p=await this.ctx.api.match.instantBattle(o);if(p.ok){let d=p.data,R=this.ctx.data.config.itemDefinitions;if(d.Resources)this.ctx.data.user.applyResourceOperation(d.Resources,R);else if(d.ResourcesDual){let V=d.ResourcesDual;V.FromUserID===n.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,R):V.ToUserID===n.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",d);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;s.Page=e,s.PageSize=t,s.Statuses=i;let n=await this.ctx.api.match.getMyMatches(s);return n.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",n.data),n}async getAvailableMatches(e=0,t=20,i=false){let s=this.ctx.authedRequest();if(!s)return a;s.Page=e,s.PageSize=t,s.OnlyPublic=i;let n=await this.ctx.api.match.getAvailableMatches(s);return n.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",n.data),n}async getDefinitions(e){let t=this.ctx.cache.configSection(pc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(pc,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var hc="Craft",en=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(hc,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(hc,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n){if(!e)return u("client","CraftID is required.");let o=this.ctx.auth.context;if(!o)return a;let p={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,RelatedEntityID:`craft_${e}_${o.userID}_${B()}`},d=await this.ctx.api.craft.craft(p);return d.ok&&(this.ctx.data.user.applyResourcesWithDelta(d.data.Resources,d.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",d.data)),d}};var Et=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Et),zod.z.record(zod.z.string(),Et)]));var qt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},dc=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Kt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function zi(r){return r!==Kt.Pending&&r!==Kt.Running}var oR={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 aR(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var lR=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),uR=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),tn=zod.z.object({GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:dc.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Et).nullish(),Assets:zod.z.array(lR).nullish(),Error:uR.nullish(),Charge:M.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:M.nullish(),Context:zod.z.record(zod.z.string(),Et).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish()}),mc=zod.z.object({Data:zod.z.array(tn).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),cR=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish()}).passthrough(),pR=zod.z.object({Modality:dc.nullish(),Async:zod.z.boolean().nullish(),Limits:Re.nullish(),PriceOptions:ue.nullish(),Tags:zod.z.array(zod.z.string()).nullish(),HistoryMessages:zod.z.number().nullish(),MaxTokens:zod.z.number().nullish(),AllowImages:zod.z.boolean().nullish(),MaxInputImages:zod.z.number().nullish(),MaxInputImageBytes:zod.z.number().nullish(),AllowedImageTypes:zod.z.array(zod.z.string()).nullish(),MaxImages:zod.z.number().nullish(),AllowEdit:zod.z.boolean().nullish(),AllowReferenceImage:zod.z.boolean().nullish(),MaxPromptChars:zod.z.number().nullish(),LockBehavior:zod.z.boolean().nullish(),ImageSize:zod.z.string().nullish(),VideoSize:zod.z.string().nullish(),VideoSeconds:zod.z.number().nullish(),Voice:zod.z.string().nullish(),AudioFormat:zod.z.string().nullish(),MusicFormat:zod.z.string().nullish(),ThreeDOperation:zod.z.string().nullish(),ArtStyle:zod.z.string().nullish(),ThreeDFormat:zod.z.string().nullish(),Reward:H.nullish(),PromptVariables:zod.z.array(cR).nullish(),AllowFreePrompt:zod.z.boolean().nullish()}).passthrough(),fc=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),pR).nullish()}).passthrough(),Ge={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic"};var gc="AI",hR=/^[A-Za-z0-9_-]{1,128}$/,dR=2e3,mR=5e3,fR=30*6e4;function gR(r,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,r);e?.addEventListener("abort",i,{once:true});})}var sn=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(gc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(gc,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):a}async getGeneration(e){if(!e)return u("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):a}isTerminal(e){return zi(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;i=p.data;}else {if(!e?.GenerationID)return u("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??fR),n=Math.max(1,t.intervalMs??dR),o=Math.max(n,t.maxIntervalMs??mR);for(;!zi(i.Status);){if(t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return u("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await gR(n,t.signal),t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(i);if(n=Math.min(o,Math.round(n*1.5)),!p.ok){if(p.reason==="connection")continue;return p}i=p.data,zi(i.Status)||t.onUpdate?.(i);}return F(i)}pollFor(e){switch(e.Modality){case qt.Text:return this.getText(e.GenerationID);case qt.Image:return this.getImage(e.GenerationID);case qt.Audio:return this.getAudio(e.GenerationID);case qt.Music:return this.getMusic(e.GenerationID);case qt.Video:return this.getVideo(e.GenerationID);case qt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return u("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!hR.test(n))return u("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??B()},p=await s(o);return p.ok&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return u("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.GenerationID=e;let s=await t(i);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Kt.Completed&&!this.rewarded.has(e.GenerationID)&&(this.rewarded.add(e.GenerationID),await this.ctx.userService.getUserInventory()),!(!t||!e.Charge||this.charged.has(e.GenerationID))&&(this.charged.add(e.GenerationID),this.ctx.data.user.applyResourceOperation(e.Charge,this.ctx.data.config.itemDefinitions));}emitView(e){this.ctx.emitter.emit("ai:generationUpdated",e),e.Status===Kt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Kt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Eo="Collection",nn=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let i=e.cache.configSection(Eo),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(p=>(p?.Seasons??[]).some(d=>!!d?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Eo,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Eo,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,s){let n=this.ctx.auth.context;if(!n)return a;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${B()}`},p=await this.ctx.api.collection.openPack(o);return p.ok&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${B()}`},o=await this.ctx.api.collection.openCollectionChest(n);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${B()}`},n=await this.ctx.api.collection.useCollectibleJoker(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",n.data)),n}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${B()}`},n=await this.ctx.api.collection.claimSetReward(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",n.data)),n}async claimSetRewardsBatch(e){if(!e||e.length===0)return u("client","sets is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${B()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,o=false){let p=this.ctx.auth.context;if(!p)return a;let d={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${p.userID}_${s}_${B()}`},R=await this.ctx.api.collection.sendTradeOffer(d);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${B()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${B()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${B()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var yR=zod.z.object({}).passthrough().transform(r=>r),RR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},CR={Active:"Active",Left:"Left",Replaced:"Replaced"},SR=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),xR=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Oe.nullish(),BuildObjectsProgress:SR.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),bR=zod.z.object({Index:zod.z.number().nullish(),OwnerUserID:zod.z.string().nullish(),CurrentProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish(),IsCompleted:zod.z.boolean().nullish()}).passthrough(),DR=zod.z.object({Objects:zod.z.array(bR).nullish()}).passthrough(),yc=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CoopChainID:zod.z.string().nullish(),CoopEventID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),Members:zod.z.array(xR).nullish(),BuildObjectsState:DR.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:zod.z.number().nullish()}).passthrough(),Rc=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Cc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),PR=zod.z.string(),qo=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Weight:zod.z.number().nullish(),MinProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish()}).passthrough(),IR=zod.z.object({Index:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxProgress:zod.z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),vR=zod.z.object({Objects:zod.z.array(IR).nullish(),PriceOptions:ue.nullish(),SpinnerTable:zod.z.array(qo).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Cc=zod.z.object({CoopEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),EventType:PR.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:vR.nullish(),GrandPrize:H.nullish()}).passthrough(),TR=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ge.nullish(),Events:zod.z.array(Cc).nullish(),Gate:Z.nullish()}).passthrough(),rn=zod.z.object({ServerTimeUtc:c.nullish(),UserState:yR.nullish(),ActiveGroup:yc.nullish()}),Lo=zod.z.object({ServerTimeUtc:c.nullish(),Group:yc.nullish(),SecondsRemaining:j.nullish()}),Sc=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Resources:M.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:qo.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(qo).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),Bo=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),xc=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),on=zod.z.object({Chains:zod.z.record(zod.z.string(),TR).nullish()}).passthrough(),ht={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var bc="CoopEvent",Dc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},an=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Dc,{schema:rn,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(bc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(bc,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return u("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(Dc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return u("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return u("client","CoopChainID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let s=i.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,s){if(!e||!t)return u("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,RelatedEntityID:B()},o=await this.ctx.api.coopEvent.spin(n);return o.ok&&(this.ctx.data.user.applyResourceOperation(o.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",o.data)),o}async claimObjectReward(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var AR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},kR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},zR=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:c.nullish(),CompletedAtUtc:c.nullish(),LastExecutedAtUtc:c.nullish(),NextAvailableAtUtc:c.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),wR=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),Pc=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:c.nullish(),ExhaustedAtUtc:c.nullish(),ExpiredAtUtc:c.nullish(),DismissedAtUtc:c.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:c.nullish(),Nodes:zod.z.record(zod.z.string(),zR).nullish(),Tracks:zod.z.record(zod.z.string(),wR).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),MR=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:c.nullish(),ActiveOfferExpiresAtUtc:c.nullish(),ActiveOffer:Pc.nullish(),NextCycleStartsAtUtc:c.nullish(),LastUpdatedUtc:c.nullish(),DismissSkipAvailableAtUtc:c.nullish(),LastDismissedAtUtc:c.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),OR=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),UR=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:c.nullish(),LastActivatedAtUtc:c.nullish(),LastExhaustedAtUtc:c.nullish(),NodeCounts:zod.z.record(zod.z.string(),OR).nullish()}).passthrough(),ER=zod.z.object({Slots:zod.z.record(zod.z.string(),MR).nullish(),OfferHistory:zod.z.record(zod.z.string(),UR).nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),qR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},LR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},BR=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),ln=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ic=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),vc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),GR=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Behaviour:K.nullish()}).passthrough(),FR=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ln.nullish(),Availability:Ic.nullish(),Behaviour:vc.nullish(),Queue:zod.z.array(BR).nullish(),Presets:GR.nullish()}).passthrough(),VR=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),_R=zod.z.object({RewardedVideo:VR.nullish()}).passthrough(),NR=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),jR=zod.z.object({Identity:K.nullish(),Graph:K.nullish(),Milestones:K.nullish()}).passthrough(),WR=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish()}).passthrough(),KR=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),QR=zod.z.object({TrackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),StartValue:zod.z.number().nullish(),MinValue:zod.z.number().nullish(),MaxValue:zod.z.number().nullish(),ClampToMin:zod.z.boolean().nullish(),ClampToMax:zod.z.boolean().nullish(),HiddenFromUI:zod.z.boolean().nullish()}).passthrough(),HR=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(NR).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),Tc=zod.z.object({Options:ue.nullish()}).passthrough(),Ac=zod.z.object({Grants:H.nullish(),TrackChanges:zod.z.array(KR).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),$R=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:ln.nullish(),Pricing:Tc.nullish(),Reward:Ac.nullish(),Action:_R.nullish(),UnlockRules:HR.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Re.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:WR.nullish()}).passthrough(),kc=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array($R).nullish(),Tracks:zod.z.array(QR).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),zc=zod.z.object({Milestones:zod.z.record(zod.z.string(),Le).nullish(),ClaimMode:zod.z.string().nullish(),Token:Nt.nullish()}).passthrough(),wc=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ln.nullish(),Graph:kc.nullish(),Milestones:zc.nullish(),Presets:jR.nullish()}).passthrough(),JR=zod.z.object({Identity:zod.z.record(zod.z.string(),ln).nullish(),Availability:zod.z.record(zod.z.string(),Ic).nullish(),Behaviour:zod.z.record(zod.z.string(),vc).nullish(),Graph:zod.z.record(zod.z.string(),kc).nullish(),Milestones:zod.z.record(zod.z.string(),zc).nullish(),Pricing:zod.z.record(zod.z.string(),Tc).nullish(),Reward:zod.z.record(zod.z.string(),Ac).nullish()}).passthrough(),Go=zod.z.object({Slots:zod.z.record(zod.z.string(),FR).nullish(),Offers:zod.z.record(zod.z.string(),wc).nullish(),Presets:JR.nullish()}).passthrough(),Mc=zod.z.object({DealOfferDefinitions:Go.nullish()}),Oc=zod.z.object({DealOffers:ER.nullish()}),ZR=zod.z.object({EntityID:zod.z.string().nullish(),TotalEarned:zod.z.number().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),ReachedUnclaimedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),YR=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:wc.nullish(),ActivationState:Pc.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:c.nullish(),Cost:xt.nullish(),Milestone:ZR.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),un=zod.z.object({Slots:zod.z.array(YR).nullish()}),Uc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ec=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),qc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),Lc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Bc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),yt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var XR="DealOffer",Gc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},cn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Gc,{schema:un,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(XR,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(Gc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${B()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,s){if(!e||!t)return u("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return a;let n=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:n??`deal_exec_${e}_${t}_${B()}`},p=await this.ctx.api.dealOffer.executeNode(o);return p.ok&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${B()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return u("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${B()}`},s=await this.ctx.api.dealOffer.claimMilestone(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${B()}`},n=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",n.data)),n}};var Fc="Referral",pn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Fc,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),F(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Fc,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=_t.parseReferralCode(e)?.toUpperCase();if(!t)return u("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let o=n.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return n}async claimInviteReward(e){let t=e.trim();if(!t)return u("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let o=n.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return n}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return u("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let o=n.data;for(let p of o.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return n}};var eC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Vc=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),tC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},iC=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),sC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},nC=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),et={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},rC={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"},oC=100,aC=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),_c=zod.z.object({FeatureID:zod.z.string().nullish(),Args:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Url:zod.z.string().nullish(),Label:zod.z.string().nullish()}).passthrough(),lC=zod.z.object({Texts:zod.z.record(zod.z.string(),aC).nullish(),Category:Vc.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:_c.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),uC=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:ce.nullish(),Cost:ce.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:c.nullish(),SenderGate:Z.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),cC=zod.z.object({Type:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxAmountPerGift:zod.z.number().nullish()}).passthrough(),pC=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(cC).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:c.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:ce.nullish(),SenderGate:Z.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),Nc=zod.z.object({Enabled:zod.z.boolean().nullish(),Capacity:zod.z.number().nullish(),RewardLetterDays:zod.z.number().nullish(),PlainLetterDays:zod.z.number().nullish(),ClaimedRetentionDays:zod.z.number().nullish(),DefaultLanguage:zod.z.string().nullish(),Templates:zod.z.record(zod.z.string(),lC).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),uC).nullish(),Transfer:pC.nullish()}).passthrough().nullish(),Integrations:zod.z.object({Leaderboard:zod.z.boolean().nullish(),CoopEvent:zod.z.boolean().nullish(),Season:zod.z.boolean().nullish(),Referral:zod.z.boolean().nullish()}).passthrough().nullish()}).passthrough(),hC=zod.z.object({MessageID:zod.z.string(),Source:iC,Category:Vc,TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:_c.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:H.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:c,ExpiresAt:c.nullish(),ReadAt:c.nullish(),ClaimedAt:c.nullish()}).passthrough(),dC=zod.z.object({MessageID:zod.z.string(),Module:nC,Key:zod.z.string(),TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish()}).passthrough(),Fo=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),jc=zod.z.object({ServerTimeUtc:c.nullish(),Messages:zod.z.array(hC).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(dC).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),hn=zod.z.object({ServerTimeUtc:c.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Vo=zod.z.object({ServerTimeUtc:c.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(Fo).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),mC=zod.z.object({MessageID:zod.z.string(),Rewards:ce.nullish()}).passthrough(),dn=zod.z.object({ServerTimeUtc:c.nullish(),Claimed:zod.z.array(mC).default([]),Failed:zod.z.array(Fo).default([]),Resources:M.nullish(),Inventory:Q.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Wc=zod.z.object({ServerTimeUtc:c.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(Fo).default([]),Resources:M.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish()}).passthrough(),Kc=zod.z.object({ServerTimeUtc:c.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),RecipientReceives:ce.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),Qc=zod.z.object({ServerTimeUtc:c.nullish(),ResetsAt:c.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:c.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish()}).passthrough().nullish()}).passthrough();var _o="Mailbox",No={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},mn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(No,{schema:hn,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(No,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(_o)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(_o,e);if(t)return F(t);let i=this.request();if(!i)return a;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(_o,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return a;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(No,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return a;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return a;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return u("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):a}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return u("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):a}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):a}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return a;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return u("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return u("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return a;let n=await this.ctx.api.mailbox.sendGift(s);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",n.data)),n}async sendTransfer(e,t,i){if(!e?.trim())return u("client","RecipientUserID is required.");if(!i?.requestID?.trim())return u("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return a;let n=await this.ctx.api.mailbox.sendTransfer(s);return n.ok&&(n.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(n.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",n.data)),n}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):a}};var fC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},gC={Title:"Title",Platform:"Platform"},Hc=zod.z.object({UserID:zod.z.string(),PublicData:Oe.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),wi=zod.z.object({Friends:zod.z.array(Hc).nullish()}),yC=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Mi=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:Hc.nullish(),Counters:yC.nullish()}),RC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},CC={Like:"Like",Favorite:"Favorite"},SC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},xC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},bC={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},DC=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),PC=zod.z.object({Id:zod.z.string(),Verb:zod.z.string().nullish(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Count:zod.z.number().nullish(),LastActors:zod.z.array(DC).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),OccurredAt:c.nullish(),OwnerImpact:M.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),$c=zod.z.object({Items:zod.z.array(PC).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:c.nullish()}).passthrough(),Oi=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:c.nullish()}).passthrough(),IC=zod.z.object({Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),Followers:zod.z.number().nullish(),Following:zod.z.number().nullish(),Comments:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Posts:zod.z.number().nullish(),Dislikes:zod.z.number().nullish()}).passthrough(),Lt=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:IC.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Jc=zod.z.object({Items:zod.z.array(Lt).nullish()}).passthrough(),jo={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},vC=zod.z.object({UserID:zod.z.string(),PublicData:Oe.nullish(),Mutual:zod.z.boolean().nullish(),Since:c.nullish()}).passthrough(),fn=zod.z.object({Items:zod.z.array(vC).nullish(),...jo}).passthrough(),TC=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:c.nullish()}).passthrough(),Zc=zod.z.object({Items:zod.z.array(TC).nullish(),...jo}).passthrough(),gn=zod.z.object({CommentID:zod.z.string(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),ParentCommentID:zod.z.string().nullish(),AuthorUserID:zod.z.string().nullish(),AuthorPublicData:Oe.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:c.nullish(),EditedAt:c.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Yc=zod.z.object({Items:zod.z.array(gn).nullish(),...jo,TotalCount:zod.z.number().nullish()}).passthrough(),Xc=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),ep=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),tp=zod.z.object({CommentsEnabled:zod.z.boolean().nullish(),CommentableTypes:zod.z.array(zod.z.string()).nullish(),CommentMaxLength:zod.z.number().nullish(),CommentMaxLinks:zod.z.number().nullish()}).passthrough(),AC="FRIENDS_FROM_PLATFORM",kC={Off:"Off",Default:"Default",Always:"Always"},zC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},ip=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),Ce={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report"};var Wo={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},yn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Wo,{schema:Oi,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return a;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return u("client","TargetUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return u("client","FriendUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return a;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(Wo,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(Wo,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):a}async getEntityStates(e,t){if(!t?.length)return u("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):a}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return u("client","Text is required.");n.Text=i,n.ParentCommentID=s;let o=await this.ctx.api.social.addComment(n);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return u("client","CommentID is required.");if(!t?.trim())return u("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return a;i.CommentID=e,i.Text=t;let s=await this.ctx.api.social.editComment(i);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return u("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=i.parentCommentID,this.applyPage(s,i.cursor,i.limit),this.ctx.api.social.getComments(s))}async report(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i)return u("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let o=await this.ctx.api.social.report(n);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let o=await this.ctx.api.social[e](n);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):a}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return u("client","EntityType is required.");if(!t)return u("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):a}};var sp="TimedBoost";function wC(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Rn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(sp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(sp,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let i=e.trim();if(!wC(i))return u("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${B()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok){let o=n.data;if(o.ActivatedBoost){let p=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var Tt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},MC={Client:"Client",Server:"Server",System:"System"},OC=zod.z.enum(["Client","Server","System"]).catch("Client"),UC=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:c.nullish(),Version:zod.z.number().nullish(),LastWriter:OC.nullish(),ExpiresAt:c.nullish()}).passthrough(),Cn=zod.z.record(zod.z.string(),UC),np=zod.z.object({Version:zod.z.number().nullish(),Private:Cn.nullish(),Public:Cn.nullish(),ReadOnly:Cn.nullish()}),Ko=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Cn.nullish()}),Qo=zod.z.object({ServerTimeUtc:c.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:c.nullish()}),EC=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:c.nullish()}),rp=zod.z.object({ServerTimeUtc:c.nullish(),Results:zod.z.array(EC).nullish()}),op=zod.z.object({ServerTimeUtc:c.nullish(),DeletedCount:zod.z.number().nullish()}),ap=zod.z.object({Results:zod.z.array(Ko).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),qC={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},LC=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),BC=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:LC.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Sn=zod.z.object({Keys:zod.z.record(zod.z.string(),BC).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),dt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var GC="UserCustomData";function lp(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var xn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(GC,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,Tt.Private)}async setPublicData(e,t){return this.setData(e,t,Tt.Public)}async setData(e,t,i){let s=e.trim();if(!lp(s))return u("client",'KeyID is required and must not contain "." or "$".');if(t==null)return u("client","Value is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(i===Tt.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(p.ok){let d=p.data;this.ctx.data.user.patchUserCustomDataKey(i,d.KeyID,t,d.Version??0,d.ExpiresAt),this.ctx.emitter.emit(i===Tt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",d);}return p}async deleteKey(e,t){let i=e.trim();if(!lp(i))return u("client",'KeyID is required and must not contain "." or "$".');if(t!==Tt.Private&&t!==Tt.Public)return u("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},n=await this.ctx.api.userCustomData.deleteKey(s);return n.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),n}async batchSet(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??Tt.Private,o=e.find(p=>p.Bucket===n&&p.KeyID===s.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,o.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return u("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var FC="TitleCustomDataDefinitions",up=50;function VC(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function Ho(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function _C(r){let e={};for(let[t,i]of Object.entries(r))Ho(i)||(e[t]=i);return e}var bn=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(FC,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return a;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return u("client","At least one KeyID is required.");if(t.some(n=>!VC(n)))return u("client",'KeyID must not contain "." or "$".');if(t.length>up)return u("client",`At most ${up} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return a;i.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Ho(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Ho(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=_C(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var Dn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var NC=15,jC="GameLoop",cp="BoardDefinition",Pn=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(jC,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(cp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),F(i);let s=this.ctx.authedRequest();if(!s)return a;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(cp,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return u("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return a;i.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return u("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${B()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,o=Vl(new Date,NC);this.ctx.data.user.patchBoardState(p=>{p.Position=n.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?p.Pending={Type:n.ActionRequired,TargetUserID:n.ActionData.TargetUserID,TargetPublicData:n.ActionData.PublicData,TargetBuildingStates:n.ActionData.TargetBuildingStates??void 0,TargetHasShield:n.ActionData.TargetHasShield??void 0,RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o}:n.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${B()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.IsBotTarget&&n.Operation?this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs):!n.IsBotTarget&&n.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(n.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",n);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return u("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${B()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let o=n.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return n}async boardLoopRaidFast(e){if(!e.length)return u("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${B()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(s.ok){let n=s.data;n.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(n)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",n);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return u("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${B()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(n.BuiltIndex,o=>{n.NewLevel!=null&&(o.Level=n.NewLevel),o.IsDamaged=false,n.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t){if(!e)return u("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${B()}`},n=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(n.ok){let o=n.data;o.Mode==="Instant"||o.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(d=>{d.ChoiceID=e,d.ChosenMode=o.Mode??"Timed",d.StartedAtUtc=o.StartedAtUtc??null,d.DurationSeconds=o.DurationSeconds??null,d.AdViewsUsed=0;}),o.Operation&&this.ctx.data.user.applyResourcesWithDelta(o.Operation,o.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",o);}return n}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${B()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=n.AdViewsUsed??0,o.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${B()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",n);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return u("client","milestoneID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var In=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return u("client","FunctionName is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(o);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var pp=zod.z.object({ServerTimeUtc:c,SourceType:ai,SourceID:zod.z.string(),TargetType:ai,TargetID:zod.z.string(),SourceSpent:j,FeeAmount:j,RateApplied:Y,TargetCredited:j}),hp=zod.z.object({ServerTimeUtc:c,SourceType:ai,SourceID:zod.z.string(),TargetType:ai,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),vn={Convert:"Convert",CryptoConvert:"CryptoConvert"},WC={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},dp=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),KC={Automatic:"Automatic",Manual:"Manual"},QC=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),HC=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),$C=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),JC=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),ZC=zod.z.object({TargetCurrencyType:ai.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),mp=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:QC.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(ZC).nullish()}).passthrough(),fp=zod.z.object({CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough(),YC=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:HC.nullish(),Recharge:$C.nullish(),Conversion:mp.nullish(),Permissions:JC.nullish(),Audit:fp.nullish(),Status:dp.nullish()}).passthrough(),XC=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),eS=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),tS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),iS=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish(),RefuseOverCap:zod.z.boolean().nullish()}).passthrough(),$o=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),DisplayDecimals:zod.z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:zod.z.array(XC).nullish(),Limits:eS.nullish(),Permissions:tS.nullish(),Conversion:mp.nullish(),Audit:fp.nullish(),Status:dp.nullish(),ServerGrantPolicy:iS.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),Tn=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),YC).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),$o).nullish()}).passthrough();var sS={EVM:"EVM",Solana:"Solana"},nS=zod.z.enum(["EVM","Solana"]).catch("EVM"),rS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},oS=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),aS={Token:"Token",Nft:"Nft"},gp=zod.z.enum(["Token","Nft"]).catch("Token"),lS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},uS=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),cS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},pS=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),hS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Jo=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),yp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function An(r){let e=r?.trim();return e||yp.GameTopUp}var dS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Rp=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),mS=zod.z.object({ContractAddress:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),Cp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),fS=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:nS.nullish(),ChainID:zod.z.number().nullish(),ChainTicker:zod.z.string().nullish(),RewardPoolAddress:zod.z.string().nullish(),VaultDepositAddress:zod.z.string().nullish(),ChainConfigVersion:zod.z.number().nullish(),RequiredConfirmations:zod.z.number().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Cp.nullish(),NftCollections:zod.z.array(mS).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RpcUrl:zod.z.string().nullish(),GasPrice:zod.z.number().nullish(),NftBridgeAddress:zod.z.string().nullish(),SignatureEpoch:zod.z.number().nullish()}).passthrough(),gS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Cp.nullish()}).passthrough(),yS=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),RS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},CS=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Sp=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:CS.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),SS=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),xS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ui=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),bS=zod.z.object({Mode:Ui.nullish(),TokenGates:zod.z.array(Sp).nullish()}).passthrough(),Zo=zod.z.object({SystemState:gS.nullish(),Networks:zod.z.record(zod.z.string(),fS).nullish(),AccountSafety:yS.nullish(),WalletLogin:SS.nullish(),PlayAccess:bS.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),DS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:c.nullish(),LastUsedAt:c.nullish(),LinkType:oS.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),xp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:gp.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),PS=zod.z.object({Status:uS.nullish(),Tier:pS.nullish(),VerifiedAt:c.nullish(),ExpiresAt:c.nullish(),RejectedAt:c.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),IS=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),vS=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:zod.z.record(zod.z.string(),IS).nullish()}).passthrough(),TS=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),AS=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),PerCollection:zod.z.record(zod.z.string(),TS).nullish()}).passthrough(),kS=zod.z.object({Tokens:vS.nullish(),Nfts:AS.nullish()}).passthrough(),Yo=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Bt=zod.z.object({Granted:zod.z.boolean(),Mode:Ui.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:c.nullish(),Balances:zod.z.array(Yo).nullish()}).passthrough(),zS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:c.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:c.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(Yo).nullish()}).passthrough(),wS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),bp=zod.z.object({Mode:Ui.nullish(),TokenGates:zod.z.array(Sp).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(wS).nullish(),Status:Bt.nullish()}).passthrough(),MS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:c.nullish(),LoggedInAt:c.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(Yo).nullish()}).passthrough(),OS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:c.nullish()}).passthrough(),US=zod.z.object({Version:zod.z.number().nullish(),Stats:kS.nullish(),LinkedWallets:zod.z.record(zod.z.string(),DS).nullish(),LastWalletLogin:MS.nullish(),PlayAccess:zS.nullish(),PendingWithdrawals:zod.z.array(xp).nullish(),Kyc:PS.nullish(),FirstActivityAt:c.nullish(),LastActivityAt:c.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(OS).nullish()}).passthrough(),ES=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:c}).passthrough(),yi=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),ES).nullish(),PendingAdded:xp.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),qS=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough().transform(r=>r),LS=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Rp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Jo.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:c.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:c.nullish(),RefundCheckedAt:c.nullish()}).passthrough(),BS=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Rp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Jo.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:c.nullish()}).passthrough(),Dp=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Xo=zod.z.object({TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ContractAddress:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(Dp).nullish(),Signature:zod.z.string().nullish()}).passthrough(),ea=zod.z.object({Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),ProgramID:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(Dp).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Pp=zod.z.object({Blockchain:Zo.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),$o).nullish()}).passthrough(),Ip=zod.z.object({State:US.nullish(),CryptoBalances:zod.z.record(zod.z.string(),qS).nullish()}).passthrough(),vp=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:yi.nullish()}).passthrough(),Tp=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Ap=zod.z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:c.nullish(),EvmSignature:Xo.nullish(),SolanaSignature:ea.nullish(),StateDelta:yi.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),kp=zod.z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),EvmSignature:Xo.nullish(),SolanaSignature:ea.nullish(),StateDelta:yi.nullish(),Inventory:Q.nullish()}).passthrough(),zp=zod.z.object({TokenTransactions:zod.z.array(LS).nullish(),NFTTransactions:zod.z.array(BS).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),ta=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:zod.z.string().nullish()}).passthrough(),wp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:gp.nullish(),EvmSignature:Xo.nullish(),SolanaSignature:ea.nullish()}).passthrough(),Mp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:Jo.nullish(),StateDelta:yi.nullish()}).passthrough(),Qe={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 GS="Blockchain",Op="Blockchain:Definitions",kn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Op,e);if(t)return F(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return a;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(GS,n.data.Blockchain),this.ctx.data.config.patchSection(Op,n.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",n.data)),n)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,i,s,n){if(!e)return u("client","CurrencyID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return a;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=s,o.Category=An(n);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,i,s,n,o,p){if(!e)return u("client","ItemID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let d=this.ctx.authedRequest();if(!d)return a;d.ItemID=e,d.NetworkID=t,d.WalletAddress=i,d.Amount=s,d.Category=An(n),o!==void 0&&(d.Level=o),p&&(d.ItemInstanceID=p);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(d);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return a;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return u("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return u("client","TitleTransactionID is required.");if(!t)return u("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TitleTransactionID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var FS={Head:"Head",Torso:"Torso",Legs:"Legs"},zn=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),VS={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},ia=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Ep=zod.z.object({AttackTarget:zn,DefenseTarget:zn});var _S=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),NS=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:zn.nullish(),DefenseZone:zn.nullish(),HitType:_S.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),jS=zod.z.object({MaxHp:zod.z.number().nullish(),CurrentHp:zod.z.number().nullish(),Damage:zod.z.number().nullish(),AttackSpeed:zod.z.number().nullish(),CritChance:zod.z.number().nullish(),CritMultiplier:zod.z.number().nullish(),Armor:zod.z.number().nullish(),DodgeChance:zod.z.number().nullish()}).passthrough(),WS=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Up=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:Ao.nullish(),BattleStrategy:zod.z.array(Ep).nullish(),UnstackableItems:zod.z.record(zod.z.string(),WS).nullish(),Stats:jS.nullish()}).passthrough(),KS=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:ce.nullish(),NetReward:ce.nullish(),BattleLog:zod.z.array(NS).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:Up.nullish(),P2BattleProfile:Up.nullish()}).passthrough(),qp=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:c.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(Ep).nullish(),TargetUserID:zod.z.string().nullish(),Entry:ce.nullish(),CreationCostPaid:ce.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:c.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:c.nullish(),Status:ia.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:c.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:c.nullish()}).passthrough(),Lp=zod.z.object({Status:ia,MatchID:zod.z.string(),Entry:ce.nullish(),Resources:M.nullish()}),Bp=zod.z.object({Match:qp.nullish()}),Gp=zod.z.object({MatchID:zod.z.string(),Status:ia,Resources:M.nullish()}),Fp=zod.z.object({Battle:KS.nullish(),Resources:M.nullish(),ResourcesDual:bt.nullish()}),sa=zod.z.object({Matches:zod.z.array(qp).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),Rt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var QS=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var HS=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),$S=zod.z.object({HealthStatID:zod.z.string().nullish(),DamageStatID:zod.z.string().nullish(),ArmorStatID:zod.z.string().nullish(),AttackSpeedStatID:zod.z.string().nullish(),CritChanceStatID:zod.z.string().nullish(),CritDamageStatID:zod.z.string().nullish(),DodgeStatID:zod.z.string().nullish(),AllMightStatID:zod.z.string().nullish()}).passthrough(),JS=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),ZS=zod.z.object({MaxRounds:zod.z.number().nullish(),BlockDamageMultiplier:zod.z.number().nullish(),MinHitDamage:zod.z.number().nullish(),DefaultCritMultiplier:zod.z.number().nullish(),MaxCritChance:zod.z.number().nullish(),MaxDodgeChance:zod.z.number().nullish(),ArmorMode:JS.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),YS=zod.z.object({Kind:HS.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Fe.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),XS=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(YS).nullish()}).passthrough(),Qt=zod.z.object({Terms:zod.z.array(XS).nullish()}).passthrough(),ex=zod.z.object({Health:Qt.nullish(),Damage:Qt.nullish(),Armor:Qt.nullish(),AttackSpeed:Qt.nullish(),CritChance:Qt.nullish(),CritDamage:Qt.nullish(),Dodge:Qt.nullish()}).passthrough(),Vp=zod.z.object({StatMapping:$S.nullish(),Combat:ZS.nullish(),Formula:ex.nullish()}).passthrough(),tx=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),Ei=zod.z.object({Kind:QS.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:Wi.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),_p=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(Ei).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Np=zod.z.object({PriceOptions:ue.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Re.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),ix=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:tx.nullish(),Entry:_p.nullish(),Creation:Np.nullish(),Settings:Vp.nullish()}).passthrough(),sx=zod.z.object({Rules:zod.z.record(zod.z.string(),ix).nullish(),Defaults:Vp.nullish(),EntryDefaults:_p.nullish(),CreationDefaults:Np.nullish()}).passthrough(),na=zod.z.object({InstantBattle:sx.nullish()}).passthrough(),jp=na;var nx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},ra=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),rx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},oa=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),ox={Burn:"Burn",Ledger:"Ledger"},ax=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Mn={Item:"Item",VirtualCurrency:"VirtualCurrency"},aa=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),lx=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish()}).passthrough(),On=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(Ei).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),la=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish(),Sink:ax.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),lx).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),ux=zod.z.object({AllowedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedItemIDs:zod.z.array(zod.z.string()).nullish(),AllowUnstackableWithState:zod.z.boolean().nullish(),AllowedCurrencyIDs:zod.z.array(zod.z.string()).nullish(),DeniedCurrencyIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),cx=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Re.nullish(),BuyLimits:Re.nullish(),ListingFeeOptions:ue.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),px=zod.z.object({Enabled:zod.z.boolean().nullish(),MinDurationHours:zod.z.number().nullish(),MaxDurationHours:zod.z.number().nullish(),AntiSnipeWindowSeconds:zod.z.number().nullish(),AntiSnipeExtensionSeconds:zod.z.number().nullish(),MaxAntiSnipeExtensions:zod.z.number().nullish(),MinBidStepPercent:zod.z.number().nullish(),MinBidStepAbsolute:j.nullish(),BidLimits:Re.nullish()}).passthrough(),hx=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Re.nullish(),FillLimits:Re.nullish()}).passthrough(),dx=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Re.nullish()}).passthrough(),mx=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),ua=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),PricePolicy:On.nullish(),Commission:la.nullish(),Tradability:ux.nullish(),Listings:cx.nullish(),Auctions:px.nullish(),BuyOrders:hx.nullish(),DirectTrades:dx.nullish(),Matching:mx.nullish()}).passthrough(),Wp=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:j.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:c.nullish()}).passthrough(),fx=zod.z.object({BidAxisType:li.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:j.nullish(),CurrentBid:j.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(Wp).nullish()}).passthrough(),wn=zod.z.object({LastAt:c.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),gx=zod.z.object({Create:wn.nullish(),Buy:wn.nullish(),Sell:wn.nullish(),Bid:wn.nullish()}).passthrough(),yx=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Rx=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:yx.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),At=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:ra.nullish(),Status:oa.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Oe.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:aa.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),GoodsInstances:zod.z.array(Rx).nullish(),Price:ce.nullish(),Auction:fx.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),Cx=zod.z.object({GoodsType:aa.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(ra,j).nullish()}).passthrough(),Kp=zod.z.object({Definitions:ua.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),ca=zod.z.object({Offers:zod.z.array(At).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Qp=zod.z.object({Groups:zod.z.array(Cx).nullish()}).passthrough(),Hp=zod.z.object({Offer:At.nullish()}).passthrough(),at=zod.z.object({OfferID:zod.z.string().nullish(),Status:oa.nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:ce.nullish()}).passthrough(),qi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:At.nullish(),Resources:M.nullish(),Matched:zod.z.boolean().nullish(),Settlement:at.nullish()}).passthrough(),$p=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:j.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish()}).passthrough(),Un=zod.z.object({MyOffers:zod.z.array(At).nullish(),MyBids:zod.z.array(At).nullish(),MyBuyOrders:zod.z.array(At).nullish(),IncomingTrades:zod.z.array(At).nullish(),OutgoingTrades:zod.z.array(At).nullish(),Claimables:zod.z.array(At).nullish(),DrainedRefunds:zod.z.array(Wp).nullish(),Limits:gx.nullish()}).passthrough(),Sx=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:ra.nullish(),FinalStatus:oa.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:aa.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),PricePaid:ce.nullish(),CommissionTaken:ce.nullish(),CompletedAt:c.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),Jp=zod.z.object({Entries:zod.z.array(Sx).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),ke={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 xx="Marketplace",Zp={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"]},En=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Zp,{schema:Un,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(xx,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,s=20){if(!e)return u("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let o=await this.ctx.api.marketplace.getOffersByItem(n);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let s=this.ctx.authedRequest();if(!s)return a;s.ItemID=e,s.ContinuationToken=t,s.PageSize=i;let n=await this.ctx.api.marketplace.getBuyOrders(s);return n.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",n.data),n}getMyState(e,t){return this.ctx.cache.read(Zp,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,o,p){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let d=this.ctx.authedRequest();if(!d)return a;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.PriceBundle=s,d.DurationHours=n,d.ItemInstanceIDs=o,d.SelectedOptionID=p;let R=await this.ctx.api.marketplace.createListing(d);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,s,n,o,p={}){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");let d=this.ctx.authedRequest();if(!d)return a;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.BidAxisType=s,d.BidCurrencyID=p.bidCurrencyID,d.BidCatalogID=p.bidCatalogID,d.BidItemID=p.bidItemID,d.StartingBid=n,d.DurationHours=o,d.ItemInstanceIDs=p.itemInstanceIDs,d.SelectedOptionID=p.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(d);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return u("client","OfferID is required.");if(!t||t<=0)return u("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,s,n){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return a;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=s,o.DurationHours=n;let p=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,s,n){if(!e)return u("client","TargetUserID is required.");if(!t)return u("client","CatalogID is required.");if(!i)return u("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return a;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=s,o.RequestedBundle=n;let p=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return u("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(i);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return u("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=Mn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Mn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):u("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var qn=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return u("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let s=await this.ctx.api.multiplayer.createRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.RoomID=e,s.TargetUserID=t,s.Ban=i;let n=await this.ctx.api.multiplayer.kickMember(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",n.data),n}async unbanMember(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return a;i.Page=e,i.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(i);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,i,s){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");if(!i)return u("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let o=await this.ctx.api.multiplayer.sendSignal(n);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(i);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,i){if(!e)return u("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.RoomID=e,s.Ready=t,s.MemberState=i;let n=await this.ctx.api.multiplayer.setMemberState(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",n.data),n}};var Yp=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Ln=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.ParentContentID=e.parentContentID,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):a}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return u("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):a}async getCreatorProfile(e,t,i){if(!e)return u("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):a}async publish(e){if(!e.files||e.files.length===0)return u("client","At least one file is required.");let t=new Map,i=e.files.map((d,R)=>{if("sourceAssetUrl"in d)return {Role:d.role,ContentType:d.contentType,SourceAssetUrl:d.sourceAssetUrl};let V=Xp(d.data,d.contentType);return t.set(R,V),{Role:d.role,ContentType:d.contentType,Size:V.size}}),s=e.thumbnail?Xp(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let o=n.data.Uploads??[];for(let d=0;d<o.length;d++){let R=o[d];if(!R||R.ServerCopy||!R.Url)continue;let V=t.get(d);if(!V)return u("client",`No bytes for file #${d+1}.`);let re=await this.putBytes(R.Url,V,R.ContentType??V.type);if(!re.ok)return re}let p=n.data.ThumbnailUpload;if(p?.Url&&s){let d=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!d.ok)return d}return this.publishUploaded({ContentID:n.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID})}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):a}async publishUploaded(e){if(!e.ContentID)return u("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return a;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let s=await this.ctx.api.workshop.updateContent(i);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getMyContent(s)):a}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let s=await this.ctx.api.workshop.acquire(i);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let s of t.data.Files??[])if(s.Url)try{let n=await this.ctx.fetchImpl(s.Url);if(!n.ok)return u("connection",`Download failed (HTTP ${n.status}).`);i.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await n.arrayBuffer()});}catch(n){return u("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${Yp}`)}return F({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):a}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):a}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?F(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${Yp}`)}}contentRequest(e){if(!e)return u("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):a}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function Xp(r,e){return r instanceof Blob?r:typeof r=="string"?new Blob([new TextEncoder().encode(r)],{type:e}):r instanceof Uint8Array?new Blob([r.slice().buffer],{type:e}):new Blob([r],{type:e})}var bx={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},Dx=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Px={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},eh=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),Ix={Everyone:"Everyone",Owner:"Owner",Server:"Server"},th=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),vx={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},Tx=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),Ax={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},kx=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),zx={Count:"Count",Sum:"Sum"},wx=zod.z.enum(["Count","Sum"]).catch("Count"),Mx={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Ox=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Ux={Strict:"Strict",Loose:"Loose"},Ex=zod.z.enum(["Strict","Loose"]).catch("Strict"),qx=zod.z.object({Kind:kx,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),Lx=zod.z.object({Type:eh,ItemType:eh.nullish(),Ref:qx.nullish(),Required:zod.z.boolean().optional(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),MaxItems:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish(),Unique:zod.z.boolean().optional(),UniqueIgnoreCase:zod.z.boolean().optional(),Indexed:zod.z.boolean().optional(),Visibility:th.optional(),ClientWritable:zod.z.boolean().nullish(),Immutable:zod.z.boolean().optional(),Description:zod.z.string().nullish(),AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxFileBytes:zod.z.number().nullish()}),Bx=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Bn=zod.z.object({Mode:Tx,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),Gx=zod.z.object({Read:zod.z.array(Bn).nullish(),Create:zod.z.array(Bn).nullish(),Update:zod.z.array(Bn).nullish(),Delete:zod.z.array(Bn).nullish()}),pa=zod.z.object({Cost:ce.nullish(),Grant:ce.nullish()}),Fx=zod.z.object({ID:zod.z.string(),SortKey:zod.z.string(),PartitionField:zod.z.string().nullish(),PageSize:zod.z.number().optional(),MaxItems:zod.z.number().optional(),PublishItems:zod.z.boolean().optional()}),Vx=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Namespace:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Enabled:zod.z.boolean().nullish(),Kind:Dx,Mode:Ex.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),Lx).nullish(),SortKeys:zod.z.array(Bx).nullish(),Access:Gx.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:Ox.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:wx,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:th.optional()})).nullish(),Economy:zod.z.object({OnCreate:pa.nullish(),OnUpdate:pa.nullish(),OnDelete:pa.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:zod.z.array(Fx).nullish(),AnonymousSearch:zod.z.boolean().nullish(),Integrations:zod.z.object({QuestMetricOnCreate:zod.z.string().nullish(),QuestMetricOnUpdate:zod.z.string().nullish(),QuestMetricOnDelete:zod.z.string().nullish(),AnalyticsEventOnCreate:zod.z.string().nullish(),AnalyticsEventOnUpdate:zod.z.string().nullish(),AnalyticsEventOnDelete:zod.z.string().nullish(),TriggerOnCreate:zod.z.string().nullish(),TriggerOnUpdate:zod.z.string().nullish(),TriggerOnDelete:zod.z.string().nullish()}).nullish(),Moderation:zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish()}).nullish()}),ih=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),Vx).default({})}),_x=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),sh=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),Ri=zod.z.object({Collection:zod.z.string(),ItemID:zod.z.string(),OwnerUserID:zod.z.string().nullish(),Data:zod.z.record(zod.z.string(),zod.z.unknown()).default({}),Version:zod.z.number(),CreatedAt:zod.z.string(),UpdatedAt:zod.z.string(),ExpireAt:zod.z.string().nullish(),Expanded:zod.z.record(zod.z.string(),zod.z.unknown()).nullish(),Files:zod.z.record(zod.z.string(),_x).nullish()}),ha=zod.z.object({Item:Ri}),nh=zod.z.object({Items:zod.z.array(Ri).default([]),Missing:zod.z.array(zod.z.string()).default([])}),da=zod.z.object({Items:zod.z.array(Ri).default([]),NextCursor:zod.z.string().nullish()}),rh=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),ma=zod.z.object({Item:Ri,AlreadyExists:zod.z.boolean().optional(),Economy:M.nullish()}),oh=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:M.nullish()}),ah=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),lh=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:Ri.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),uh=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),ch=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),ph=zod.z.object({Version:zod.z.string(),Collection:zod.z.string(),View:zod.z.string(),SortKey:zod.z.string().nullish(),PageSize:zod.z.number(),UpdatedAt:zod.z.string(),BaseUrl:zod.z.string(),Partitions:zod.z.record(zod.z.string(),zod.z.object({Segment:zod.z.string(),Pages:zod.z.number(),Total:zod.z.number()})).default({})}),hh=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(Ri).default([])}),Nx={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 jx=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,fh=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,ga=100,dh=25,mh=100;function Wx(r,e,t){return {Field:r,Op:e,Value:t}}var Gn=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(a)}get(e,t,i={}){let s=tt(e)??Li(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.get({...n,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let s=tt(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(o=>fh.test(o)))];return n.length?n.length>mh?Promise.resolve(u("client",`At most ${mh} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(u("client","At least one valid item id is required."))}query(e,t={},i={}){let s=tt(e)??fa(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],o=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:o,Limit:t.Limit??ga},i);if(!p.ok)return p;if(n.push(...p.data.Items),o=p.data.NextCursor??void 0,!o||n.length>=s)return F(n.slice(0,s))}}count(e,t={}){let i=tt(e)??fa(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,i={}){let s=tt(e)??(i.itemID?Li(i.itemID):null);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.create({...n,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,s={}){let n=tt(e)??Li(t);return n?Promise.resolve(n):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=tt(e)??Li(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.delete({...n,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(u("client","Operations are empty."));if(e.length>dh)return Promise.resolve(u("client",`At most ${dh} operations per batch.`));let t=e.map(i=>tt(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let s=tt(e);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.getCounter({...n,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,s){let n=tt(e);return n?Promise.resolve(n):t?s>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(u("client","File size must be positive.")):Promise.resolve(u("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,n,i.size);if(!o.ok)return o;let p=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||n);return p.ok?o:p}async getPublicViews(e){let t=tt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return F(i);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,i={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let n=s.data.Views[t];if(!n)return u("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(n,ph);if(!o.ok)return o;let p=o.data.Partitions[i.partition??""],d=Math.max(1,i.page??1);if(!p||d>p.Pages)return F({pointer:o.data,page:{Page:d,HasMore:false,Items:[]}});let R=await this.fetchJson(`${o.data.BaseUrl}${p.Segment}/page-${d}.json`,hh);return R.ok?F({pointer:o.data,page:R.data}):R}getPublic(e,t){let i=tt(e)??Li(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=tt(e)??fa(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(a)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?F(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return u("connection","Internet Connection Error")}if(!i.ok)return u("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return u("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?F(n.data):u("server","CDN answer has an unexpected shape.")}};function tt(r){return jx.test(r??"")?null:u("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function Li(r){return fh.test(r??"")?null:u("client",`Item id '${r}' is invalid.`)}function fa(r){return r.Limit!=null&&(r.Limit<1||r.Limit>ga)?u("client",`Limit must be 1..${ga}.`):(r.Where?.length??0)>8?u("client","At most 8 filters per query."):null}var ya={Open:"Open",Declared:"Declared"},Kx=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),Qx=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),gh=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Kx).nullish(),Dimensions:zod.z.array(Qx).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),Gt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Ct={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Fn=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Hx={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},$x=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),yh=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array($x).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Ra={LogEvents:"LogEvents"};function Rh(r,e=0){let t=r??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let p=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let p=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let n=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(n)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(n[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function Ch(r){let e=typeof navigator>"u"?void 0:navigator,t=Rh(e?.userAgent??"",e?.maxTouchPoints??0),i={};r.appVersion&&(i.AppVersion=r.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let s=r.locale||e?.language;return s&&(i.Language=s),i}var Jx=25,Zx=3e4,Sh=1800*1e3,xh=500,Yx=5,Xx=1e3,eb=3600*1e3,bh="idos_analytics_queue",Ca="idos_analytics_pending",Sa="idos_analytics_opt_out",Dh="idos_analytics_first_open",Ph="idos_analytics_last_activity",Ih="idos_analytics_last_context",vh="idos_analytics_owner",Vn=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Fn.test(e)?u("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):tb(e)?u("client",`Event name "${e}" uses a reserved prefix (${Ct.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return u("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Gt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return F(null);if(this.config()?.Enabled===false)return this.clear(),F(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return F(null);this.pending={BatchID:B(),Events:this.queue.splice(0,Ct.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=Yx)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Sa);return}this.write(Sa,"1"),this.clear();}get isEnabled(){return this.read(Sa)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(vh);e&&t&&t!==e&&this.clear(),e&&this.write(vh,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Zx),typeof window<"u"&&(window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide)),this.beginAutomatic(),this.flush();}async stop(){this.started&&(this.started=false,this.automaticDone=false,this.timer&&clearInterval(this.timer),this.drainTimer&&clearTimeout(this.drainTimer),this.timer=null,this.drainTimer=null,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null,typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),await this.flush());}beginAutomatic(){if(this.automaticDone||!this.started)return;if(this.config()?.Enabled!==true){this.stopWaitingForConfig??=this.ctx.emitter.on("title:publicConfigurationReceived",()=>this.beginAutomatic());return}this.automaticDone=true,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null;let e=Number(this.read(Ph)??"0");this.read(Dh)||(this.write(Dh,new Date().toISOString()),this.enqueue(Gt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Ih);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Gt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Gt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Ih,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Sh)&&this.enqueue(Gt.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=Sh&&this.enqueue(Gt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,s){if(!this.isEnabled||this.disabledByServer)return F(null);let n=this.config();if(n?.Enabled===false)return F(null);if(s&&n?.AutomaticEvents===false)return F(null);if(n?.Events?.[e]?.Blocked)return u("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===ya.Declared.toLowerCase()&&!n.Events?.[e])return u("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return u("client","value must be a finite number.");let o=ib(t);if(o.error)return u("client",o.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(p.Params=o.params),i!==void 0&&(p.Value=i),this.queue.push(p),this.queue.length>xh&&this.queue.splice(0,this.queue.length-xh),this.touch(),this.persist(),this.started&&this.queue.length>=Jx&&this.flush(),F(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},Xx));}dropStale(){let e=Date.now()-(Ct.maxEventAgeMs-eb);this.queue=this.queue.filter(t=>{let i=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(i)||i>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=Ch({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(bh);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(Ca);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(bh,this.queue),this.pending?this.writeJson(Ca,this.pending):this.remove(Ca);}touch(){this.write(Ph,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.platform.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.platform.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.platform.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function tb(r){let e=r.toLowerCase();return Ct.reservedPrefixes.some(t=>e.startsWith(t))}function ib(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>Ct.maxParams)return {error:`Too many parameters: ${e.length}, max ${Ct.maxParams}.`};let t={};for(let i of e){if(!Fn.test(i))return {error:`Invalid parameter name "${i}".`};let s=r[i];typeof s=="string"?t[i]=s.length>Ct.maxStringValueLength?s.slice(0,Ct.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var sb="idos_experiments",_n=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let o=this.views.get(s);(!o||o.VariantID!==n.VariantID||o.Status!==n.Status)&&i.push(n);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${sb}:${this.ctx.settings.titleID}`}};function Ft(r,e,t,i){let n=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var L=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Ft(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var Nn=class extends L{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Ra.LogEvents,e,yh,{silent:true})}};var nb=zod.z.object({VariantID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Weight:zod.z.number().nullish(),IsControl:zod.z.boolean().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},ob=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),ab=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Variants:zod.z.array(nb).nullish(),Salt:zod.z.string().nullish(),LayerID:zod.z.string().nullish(),StickyAssignment:zod.z.boolean().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Goals:zod.z.array(ob).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),Th=zod.z.object({Experiments:zod.z.record(zod.z.string(),ab).nullish()}).passthrough(),lb={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},ub=zod.z.object({ExperimentID:zod.z.string().nullish(),VariantID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ah=zod.z.object({Experiments:zod.z.array(ub).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),xa={GetExperiments:"GetExperiments"};var jn=class extends L{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(xa.GetExperiments,e,Ah)}};var kh=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:c.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:c,PlayAccess:Bt.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:c.nullish()}),zh=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:c,RefreshToken:zod.z.string(),RefreshTokenExpiration:c.nullish(),PlayAccess:Bt.nullish()}),cb=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),wh=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().nullish(),PlatformFallback:zod.z.boolean().nullish(),AndroidClientID:zod.z.string().nullish(),IosClientID:zod.z.string().nullish(),DesktopClientID:zod.z.string().nullish()}).passthrough().nullish(),Apple:zod.z.object({Enabled:zod.z.boolean().nullish(),BundleID:zod.z.string().nullish(),ServiceID:zod.z.string().nullish()}).passthrough().nullish(),PlayAccessMode:Ui.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:zod.z.boolean().nullish(),NativeSso:cb.nullish()}).passthrough(),Mh=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:c.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:Bt.nullish()}).passthrough(),Oh=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:c.nullish(),PlayAccess:Bt.nullish()}).passthrough(),Uh=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Ue=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:c.nullish()}),Eh=zod.z.object({Message:zod.z.string(),ExpiresAt:c}),Ee={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var Wn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Ft(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,kh,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ee.RefreshSession),e,zh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ee.GetAuthOptions),e,wh,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Ft(this.ctx.settings.titleID,"Authentication",Ee.LinkWallet,e.UserID??""),e,Mh,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Ft(this.ctx.settings.titleID,"Authentication",Ee.UnlinkWallet,e.UserID??""),e,Oh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ee.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ee.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ee.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ee.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ee.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ee.LoginWithSsoCode,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ee.RegisterWithEmail),e,Uh,{ticket:null})}confirmEmailRegistration(e){return this.login(Ee.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ee.ResendVerificationCode),e,Ue,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ee.RequestWalletChallenge),e,Eh,{ticket:null})}loginWithWallet(e){return this.login(Ee.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ee.ForgotPassword),e,Ue,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ee.ResetPassword),e,Ue,{ticket:null})}};var pb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},qh=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),hb=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),Lh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),hb).nullish(),MissingKeyMode:qh.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),db=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),Bh=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:db.nullish()}).passthrough(),Kn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},mb=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),Gh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:qh.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(mb).nullish()}).passthrough(),Fh=zod.z.object({RequestedLocale:zod.z.string().nullish(),Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),NotModified:zod.z.boolean().nullish(),Entries:zod.z.record(zod.z.string(),zod.z.string()).nullish(),FallbackLocale:zod.z.string().nullish(),FallbackVersion:zod.z.number().nullish()}).passthrough();var ba=zod.z.object({TitleConfigVersion:zod.z.string().nullish(),TitleConfigUrl:zod.z.string().nullish(),User:zod.z.unknown().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish(),Localization:Bh.nullish(),Views:zod.z.array(zod.z.object({Name:zod.z.string(),Key:zod.z.string().nullish(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(r=>r),Vh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(r=>r),_h=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),User:zod.z.unknown().nullish()}).passthrough().transform(r=>r),Nh=zod.z.object({}).passthrough().transform(r=>r),jh=zod.z.object({}).passthrough().transform(r=>r),Wh=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:c.nullish(),LastActiveAt:c.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),Kh=zod.z.object({Username:zod.z.string()}),lt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Qn=class extends L{constructor(e){super(e,"User");}getClientState(e){return this.send(lt.GetClientState,e,ba)}getClientStateExcept(e){return this.send(lt.GetClientStateExcept,e,ba)}getStateVersions(e){return this.send(lt.GetStateVersions,e,Vh)}getUserState(e){return this.send(lt.GetUserState,e,_h)}getInventory(e){return this.send(lt.GetInventory,e,Nh)}getEventTokens(e){return this.send(lt.GetEventTokens,e,jh)}getUsageTime(e){return this.send(lt.GetUsageTime,e,Wh)}addUsageTime(e){return this.send(lt.AddUsageTime,e,Ue,{silent:true})}deleteUserAccount(e){return this.send(lt.DeleteUserAccount,e,Ue)}changeUsername(e){return this.send(lt.ChangeUsername,e,Kh)}};var Hn=class extends L{constructor(e){super(e,"Currency");}convert(e){return this.send(vn.Convert,e,pp)}cryptoConvert(e){return this.send(vn.CryptoConvert,e,hp)}};var fb=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),Da=zod.z.object({ServerTimeUtc:c,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:M.nullish(),FodderConsumed:zod.z.array(fb).nullish()}),Qh=zod.z.array(ve(Da)),$n={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},gb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},yb=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Rb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Cb=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Sb=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),xb=zod.z.object({Networks:zod.z.record(zod.z.string(),Sb).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),bb=zod.z.object({FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),Db=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),UseRequirements:zod.z.record(zod.z.string(),zod.z.number()).nullish(),AllowedCharacterIDs:zod.z.array(zod.z.string()).nullish(),AllowedSlotIDs:zod.z.array(zod.z.string()).nullish(),IdleRateBonus:zod.z.number().nullish()}).passthrough(),Pb=zod.z.object({ValuationMode:yb.nullish(),WeightCurve:Fe.nullish(),Selection:Cb.nullish()}).passthrough(),Ib=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Fe.nullish(),FlatBonusCurve:Fe.nullish(),PercentBonusCurve:Fe.nullish(),PowerCurve:Fe.nullish(),Fodder:Pb.nullish()}).passthrough(),vb=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),Tb=zod.z.object({ItemID:zod.z.string(),CatalogID:zod.z.string(),ItemClass:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsStackable:zod.z.boolean().nullish(),IsTradable:zod.z.boolean().nullish(),Weight:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),NFT:xb.nullish(),Stats:bb.nullish(),Equipment:Db.nullish(),Upgrade:Ib.nullish(),Metadata:vb.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),Ab=zod.z.object({Items:zod.z.record(zod.z.string(),Tb).nullish()}).passthrough(),Jn=zod.z.object({Catalogs:zod.z.record(zod.z.string(),Ab).nullish()}).passthrough();var Zn=class extends L{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send($n.UpgradeLevel,e,Da)}upgradeLevelsBatch(e){return this.send($n.UpgradeLevelsBatch,e,Qh)}};var Yn=class extends L{constructor(e){super(e,"Store");}purchase(e){return this.send(Wt.Purchase,e,ho)}purchaseBatch(e){return this.send(Wt.PurchaseBatch,e,$l)}getDefinitions(e){return this.send(Wt.GetDefinitions,e,Rs)}getUserState(e){return this.send(Wt.GetUserState,e,Jl)}getStorefront(e){return this.send(Wt.GetStorefront,e,Cs)}};var kb={Apple:"Apple",Google:"Google"},Xn=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),er=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),Xn).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(r=>r),zb=zod.z.object({PremiumID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Tier:zod.z.number().nullish(),DurationDays:zod.z.number().nullish(),TrialDurationDays:zod.z.number().nullish(),PriceOptions:ue.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Pa=zod.z.object({Definitions:zod.z.record(zod.z.string(),zb).nullish()}).passthrough(),Hh=zod.z.object({Premium:Pa.nullish()}),$h=zod.z.object({ServerTimeUtc:c.nullish(),Premium:er.nullish()}),tr=zod.z.object({ServerTimeUtc:c.nullish(),Premium:er.nullish(),Subscription:Xn.nullish(),Resources:M.nullish()}),Ht={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var wb={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},Mb=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Jh=zod.z.object({StartUtc:c.nullish(),EndUtc:c.nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Ia=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),Ob=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),Ub=zod.z.object({Rewards:K.nullish(),Rules:K.nullish(),Refund:K.nullish()}).passthrough(),Eb=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:Mb.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:Jh.nullish(),Refund:Ia.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:Ob.nullish(),Presets:Ub.nullish()}).passthrough(),qb=zod.z.object({StoreID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),PackageName:zod.z.string().nullish(),VerificationMode:zod.z.string().nullish(),PlayPublicKey:zod.z.string().nullish(),RequireCertificateChain:zod.z.boolean().nullish(),SecretName:zod.z.string().nullish(),IssuerID:zod.z.string().nullish(),KeyID:zod.z.string().nullish(),AcknowledgePurchases:zod.z.boolean().nullish(),NotificationPackageName:zod.z.string().nullish()}).passthrough(),Lb=zod.z.object({Rewards:H.nullish()}).passthrough(),Bb=zod.z.object({Rules:Jh.nullish()}).passthrough(),Gb=zod.z.object({Refund:Ia.nullish()}).passthrough(),Fb=zod.z.object({Rewards:zod.z.record(zod.z.string(),Lb).nullish(),Rules:zod.z.record(zod.z.string(),Bb).nullish(),Refund:zod.z.record(zod.z.string(),Gb).nullish()}).passthrough(),Vb=zod.z.object({MaxPurchaseAgeDays:zod.z.number().nullish(),AllowSandbox:zod.z.boolean().nullish(),RequirePackageMatch:zod.z.boolean().nullish(),MaxReceiptsPerBatch:zod.z.number().nullish(),RefundCheckHorizonDays:zod.z.number().nullish(),RejectCrossUserReceipts:zod.z.boolean().nullish()}).passthrough(),_b=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),Eb).nullish(),Stores:zod.z.record(zod.z.string(),qb).nullish(),Presets:Fb.nullish(),Validation:Vb.nullish(),Refund:Ia.nullish()}).passthrough(),Zh=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:c.nullish(),LastPurchasedAt:c.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Yh=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:c.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:c.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:c.nullish()}).passthrough(),Nb=zod.z.object({Products:zod.z.record(zod.z.string(),Zh).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Yh).nullish(),LastRefundCheckAt:c.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:c.nullish(),LastPurchaseAt:c.nullish()}).passthrough(),jb=zod.z.object({ProductID:zod.z.string(),Available:zod.z.boolean(),Owned:zod.z.boolean(),Blocked:zod.z.boolean(),Reason:zod.z.string().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Xh=zod.z.object({ServerTimeUtc:c,Purchase:_b.nullish(),Availability:zod.z.array(jb).nullish()}),ed=zod.z.object({ServerTimeUtc:c,Purchase:Nb.nullish()}),Wb={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},Kb=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),va=zod.z.object({ServerTimeUtc:c,Store:ji.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:Kb.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),ProductState:Zh.nullish(),Premium:er.nullish(),Subscription:Xn.nullish(),SubscriptionMirror:Yh.nullish()}).passthrough(),td=zod.z.object({ServerTimeUtc:c,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:c.nullish()}).passthrough(),id=ft(va),$t={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var ir=class extends L{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send($t.GetDefinitions,e,Xh)}getUserState(e){return this.send($t.GetUserState,e,ed)}validatePurchase(e){return this.send($t.ValidatePurchase,e,va)}validatePurchasesBatch(e){return this.send($t.ValidatePurchasesBatch,e,id)}createTelegramInvoice(e){return this.send($t.CreateTelegramInvoice,e,td)}};var Qb=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),sd=zod.z.object({Reward:H.nullish(),Weight:zod.z.number().nullish(),AmountRange:Qb.nullish()}).passthrough(),Ci=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(sd).nullish()}).passthrough(),Si=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(sd).nullish()}).passthrough(),Hb=zod.z.object({RewardSlots:zod.z.array(Ci).nullish()}).passthrough(),$b=zod.z.object({PityRules:zod.z.array(Si).nullish()}).passthrough(),sr=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),Hb).nullish(),PityPresets:zod.z.record(zod.z.string(),$b).nullish()}).passthrough();var Jb=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),nd=zod.z.object({ServerTimeUtc:c,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:zod.z.array(M).nullish(),TriggeredPity:zod.z.array(Jb).nullish()}),Zb=zod.z.object({RewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),Yb=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:j.nullish()}).passthrough(),Xb=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ue.nullish(),RewardSlots:zod.z.array(Ci).nullish(),PityRules:zod.z.array(Si).nullish(),Presets:Zb.nullish(),RewardMultiplier:Ki.nullish(),SupplyLimits:zod.z.array(Yb).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),eD=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Ta=zod.z.object({Definitions:zod.z.record(zod.z.string(),Xb).nullish(),RewardPools:sr.nullish(),Settings:eD.nullish()}).passthrough(),rd=zod.z.object({LootboxDefinitions:Ta.nullish()}),nr={GetDefinitions:"GetDefinitions",Open:"Open"};var rr=class extends L{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(nr.GetDefinitions,e,rd)}open(e){return this.send(nr.Open,e,nd)}};var tD=zod.z.object({}).passthrough().transform(r=>r),iD=zod.z.object({}).passthrough().transform(r=>r),sD=zod.z.object({}).passthrough().transform(r=>r),nD=zod.z.object({}).passthrough().transform(r=>r),rD=zod.z.object({}).passthrough().transform(r=>r),od=zod.z.object({ServerTimeUtc:c,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:tD,Resources:M.nullish(),Inventory:Q.nullish()}),ad=zod.z.object({ServerTimeUtc:c,AccrualID:zod.z.string(),AccruedSeconds:j.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:iD,Resources:M.nullish(),Inventory:Q.nullish()}),ld=zod.z.object({ServerTimeUtc:c,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:sD,Resources:M.nullish(),Inventory:Q.nullish()}),ud=zod.z.object({ServerTimeUtc:c,ClaimID:zod.z.string(),ClaimState:nD,Resources:M.nullish(),Inventory:Q.nullish()}),cd=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:j.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),oD=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),aD=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:H.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Bi=zod.z.object({Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Aa=zod.z.object({Availability:K.nullish()}).passthrough(),lD=zod.z.object({Availability:zod.z.record(zod.z.string(),Bi).nullish()}).passthrough(),uD=zod.z.object({CalendarID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Days:zod.z.array(aD).nullish(),IsLooping:zod.z.boolean().nullish(),MissBehavior:zod.z.string().nullish(),ResetByDays:zod.z.number().nullish(),MissThresholdMultiplier:zod.z.number().nullish(),ClaimMode:zod.z.string().nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),Availability:Bi.nullish(),Presets:Aa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),cD=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),pD=zod.z.object({BaseRatePerSecond:zod.z.number().nullish(),PowerCoefficient:zod.z.number().nullish(),BoardRankCoefficient:zod.z.number().nullish(),EquipmentBonusEnabled:zod.z.boolean().nullish(),EquipmentCharacterID:zod.z.string().nullish(),PremiumMultipliers:zod.z.array(cD).nullish()}).passthrough(),hD=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Bi.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),dD=zod.z.object({AccrualID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rate:pD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:hD.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),mD=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:H.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),fD=zod.z.object({ComebackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(mD).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Bi.nullish(),Presets:Aa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),gD=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxClaimsPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish(),TotalClaimLimit:zod.z.number().nullish()}).passthrough(),yD=zod.z.object({ClaimID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Mode:zod.z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:zod.z.array(gD).nullish(),Availability:Bi.nullish(),Presets:Aa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),ka=zod.z.object({TierRewards:oD.nullish(),MilestoneRewardMultiplier:Ki.nullish(),DailyCalendars:zod.z.record(zod.z.string(),uD).nullish(),IdleAccruals:zod.z.record(zod.z.string(),dD).nullish(),Comebacks:zod.z.record(zod.z.string(),fD).nullish(),Claims:zod.z.record(zod.z.string(),yD).nullish(),Presets:lD.nullish()}).passthrough(),pd=zod.z.object({RewardDefinitions:ka.nullish()}),hd=zod.z.object({Rewards:rD.nullish()}),kt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var or=class extends L{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(kt.GetRewardDefinitions,e,pd)}getUserRewardsState(e){return this.send(kt.GetUserRewardsState,e,hd)}getMilestoneRewardMultiplier(e){return this.send(kt.GetMilestoneRewardMultiplier,e,cd)}claimDailyReward(e){return this.send(kt.ClaimDailyReward,e,od)}collectIdleAccrual(e){return this.send(kt.CollectIdleAccrual,e,ad)}claimComebackReward(e){return this.send(kt.ClaimComebackReward,e,ld)}claimReward(e){return this.send(kt.ClaimReward,e,ud)}};var ar=class extends L{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(nt.GetTutorialDefinitions,e,kl)}getUserTutorialState(e){return this.send(nt.GetUserTutorialState,e,$i)}startFlow(e){return this.send(nt.StartFlow,e,wt)}reportStepShown(e){return this.send(nt.ReportStepShown,e,wt)}completeStep(e){return this.send(nt.CompleteStep,e,wt)}completeStepsBatch(e){return this.send(nt.CompleteStepsBatch,e,Ml)}skipStep(e){return this.send(nt.SkipStep,e,wt)}skipFlow(e){return this.send(nt.SkipFlow,e,wt)}claimFlowReward(e){return this.send(nt.ClaimFlowReward,e,wl)}resetFlow(e){return this.send(nt.ResetFlow,e,wt)}};var RD={Open:"Open",Application:"Application"},CD=zod.z.enum(["Open","Application"]).catch("Open"),SD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},dd=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),xD={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},za=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),bD={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var Jt={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},DD=zod.z.object({CampaignID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IsRunning:zod.z.boolean().nullish()}).passthrough(),md=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:CD.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:dd.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(DD).nullish()}).passthrough(),PD=zod.z.object({Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),CountedMetrics:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ReachedMilestones:zod.z.array(zod.z.string()).nullish(),CappedBySubmissionLimit:zod.z.boolean().nullish(),CappedByCreatorLimit:zod.z.boolean().nullish(),NotPaidAsCopy:zod.z.boolean().nullish()}).passthrough(),ID=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:za.nullish(),CurrencyID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),Granted:zod.z.number().nullish(),Paid:zod.z.number().nullish(),Overpaid:zod.z.number().nullish(),Claimable:zod.z.number().nullish(),BySubmission:zod.z.record(zod.z.string(),PD).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),vD=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:za.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),fd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(ID).nullish(),Payouts:zod.z.array(vD).nullish()}).passthrough(),gd=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:za.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),TD=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),AD=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),Signature:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(TD).nullish()}).passthrough(),kD=zod.z.object({Kind:zod.z.string().nullish(),Target:zod.z.string().nullish(),Required:zod.z.number().nullish(),Actual:zod.z.number().nullish(),Passed:zod.z.boolean().nullish()}).passthrough(),yd=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:dd.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(kD).nullish()}).passthrough(),zD=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),wD=zod.z.object({ProgramID:zod.z.string().nullish(),Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(zD).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Rd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:zod.z.number().nullish(),NetAmountNative:zod.z.number().nullish(),BurnAmountNative:zod.z.number().nullish(),AmountUsd:zod.z.number().nullish(),ExpiresAt:zod.z.string().nullish(),EvmSignature:AD.nullish(),SolanaSignature:wD.nullish(),StateDelta:yi.nullish()}).passthrough();var lr=class extends L{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(Jt.GetCommunityMarketingState,e,md)}getEarnings(e){return this.send(Jt.GetEarnings,e,fd)}claim(e){return this.send(Jt.Claim,e,gd)}checkJoinEligibility(e){return this.send(Jt.CheckJoinEligibility,e,yd)}withdrawCryptoReward(e){return this.send(Jt.WithdrawCryptoReward,e,Rd)}};var ur=class extends L{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Ke.GetChatDefinitions,e,fu)}getChannels(e){return this.send(Ke.GetChannels,e,zs)}poll(e){return this.send(Ke.Poll,e,gu)}getHistory(e){return this.send(Ke.GetHistory,e,yu)}getConversations(e){return this.send(Ke.GetConversations,e,Su)}sendMessage(e){return this.send(Ke.SendMessage,e,Ru)}openDirectChannel(e){return this.send(Ke.OpenDirectChannel,e,Cu)}markRead(e){return this.send(Ke.MarkRead,e,fi)}joinChannel(e){return this.send(Ke.JoinChannel,e,fi)}leaveChannel(e){return this.send(Ke.LeaveChannel,e,fi)}reportMessage(e){return this.send(Ke.ReportMessage,e,xu)}ignoreUser(e){return this.send(Ke.IgnoreUser,e,fi)}unignoreUser(e){return this.send(Ke.UnignoreUser,e,fi)}};var cr=class extends L{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(gi.GetPushConfig,e,Pu)}subscribePush(e){return this.send(gi.SubscribePush,e,So)}unsubscribePush(e){return this.send(gi.UnsubscribePush,e,Ue)}getPushSubscriptions(e){return this.send(gi.GetPushSubscriptions,e,Iu)}};var pr=class extends L{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send(Kn.GetLocalizationManifest,e,Gh)}getLocalizationTable(e){return this.send(Kn.GetLocalizationTable,e,Fh)}};var hr=class extends L{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(pt.GetQuestDefinitions,e,Hi)}getUserQuestState(e){return this.send(pt.GetUserQuestState,e,yl)}refreshQuestCycles(e){return this.send(pt.RefreshQuestCycles,e,Ue)}claimQuestReward(e){return this.send(pt.ClaimQuestReward,e,eo)}claimQuestRewardsBatch(e){return this.send(pt.ClaimQuestRewardsBatch,e,Sl)}claimMilestoneReward(e){return this.send(pt.ClaimMilestoneReward,e,to)}claimMilestoneRewardsBatch(e){return this.send(pt.ClaimMilestoneRewardsBatch,e,xl)}claimGroupCompletionReward(e){return this.send(pt.ClaimGroupCompletionReward,e,Rl)}addQuestProgress(e){return this.send(pt.AddQuestProgress,e,Cl)}};var dr=class extends L{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ot.GetActiveEvents,e,Ls)}getDefinitions(e){return this.send(ot.GetDefinitions,e,qs)}getUserLteState(e){return this.send(ot.GetUserLteState,e,ku)}grantTokens(e){return this.send(ot.GrantTokens,e,M)}spendTokens(e){return this.send(ot.SpendTokens,e,Do)}claimMilestone(e){return this.send(ot.ClaimMilestone,e,Po)}claimMilestonesBatch(e){return this.send(ot.ClaimMilestonesBatch,e,Io)}claimAllMilestones(e){return this.send(ot.ClaimAllMilestones,e,Io)}spendTokensBatch(e){return this.send(ot.SpendTokensBatch,e,zu)}grantTokensBatch(e){return this.send(ot.GrantTokensBatch,e,wu)}};var mr=class extends L{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ve.GetDefinitions,e,js)}getLeaderboard(e){return this.send(Ve.GetLeaderboard,e,ki)}getMyProgress(e){return this.send(Ve.GetMyProgress,e,Gs)}submitScore(e){return this.send(Ve.SubmitScore,e,Fs)}submitScoreFromSource(e){return this.send(Ve.SubmitScoreFromSource,e,Fs)}claimCycleReward(e){return this.send(Ve.ClaimCycleReward,e,Vs)}claimMilestone(e){return this.send(Ve.ClaimMilestone,e,_s)}getFriendsLeaderboard(e){return this.send(Ve.GetFriendsLeaderboard,e,ki)}getLeaderboardsBatch(e){return this.send(Ve.GetLeaderboardsBatch,e,Uu)}getProgressBatch(e){return this.send(Ve.GetProgressBatch,e,Ns)}claimCycleRewardsBatch(e){return this.send(Ve.ClaimCycleRewardsBatch,e,Eu)}claimMilestonesBatch(e){return this.send(Ve.ClaimMilestonesBatch,e,qu)}submitScoresBatch(e){return this.send(Ve.SubmitScoresBatch,e,Lu)}claimAllRewardsBatch(e){return this.send(Ve.ClaimAllRewardsBatch,e,Bu)}getOverviewBatch(e){return this.send(Ve.GetOverviewBatch,e,Gu)}};var fr=class extends L{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Ut.GetDefinitions,e,Qs)}getActiveSeason(e){return this.send(Ut.GetActiveSeason,e,Ks)}getUserState(e){return this.send(Ut.GetUserState,e,vo)}grantStatusTokens(e){return this.send(Ut.GrantStatusTokens,e,Nu)}claimTierReward(e){return this.send(Ut.ClaimTierReward,e,To)}claimTierRewardsBatch(e){return this.send(Ut.ClaimTierRewardsBatch,e,ju)}};var gr=class extends L{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Ht.GetDefinitions,e,Hh)}getUserState(e){return this.send(Ht.GetUserState,e,$h)}activateTrial(e){return this.send(Ht.ActivateTrial,e,tr)}purchaseItemOrCurrency(e){return this.send(Ht.PurchaseWithResources,e,tr)}purchaseRealMoney(e){return this.send(Ht.PurchaseRealMoney,e,tr)}};var yr=class extends L{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(_e.GetCharacterDefinitions,e,Zs)}getUserCharacters(e){return this.send(_e.GetUserCharacters,e,Ju)}unlockCharacter(e){return this.send(_e.UnlockCharacter,e,wo)}upgradeStatLevel(e){return this.send(_e.UpgradeStatLevel,e,ko)}upgradeCharacterLevel(e){return this.send(_e.UpgradeCharacterLevel,e,zo)}equipItems(e){return this.send(_e.EquipItems,e,Zu)}unequipItems(e){return this.send(_e.UnequipItems,e,Yu)}unequipAllCharacters(e){return this.send(_e.UnequipAllCharacters,e,Xu)}unlockCharactersBatch(e){return this.send(_e.UnlockCharactersBatch,e,nc)}upgradeCharacterLevelsBatch(e){return this.send(_e.UpgradeCharacterLevelsBatch,e,rc)}upgradeStatLevelsBatch(e){return this.send(_e.UpgradeStatLevelsBatch,e,oc)}unlockSkin(e){return this.send(_e.UnlockSkin,e,ec)}equipSkin(e){return this.send(_e.EquipSkin,e,tc)}unequipSkin(e){return this.send(_e.UnequipSkin,e,ic)}getCharacterSkins(e){return this.send(_e.GetCharacterSkins,e,sc)}};var Rr=class extends L{constructor(e){super(e,"Match");}createMatch(e){return this.send(Rt.CreateMatch,e,Lp)}updateMatch(e){return this.send(Rt.UpdateMatch,e,Bp)}cancelMatch(e){return this.send(Rt.CancelMatch,e,Gp)}instantBattle(e){return this.send(Rt.InstantBattle,e,Fp)}saveStrategy(e){return this.send(Rt.SaveStrategy,e,Ue)}getMyMatches(e){return this.send(Rt.GetMyMatches,e,sa)}getAvailableMatches(e){return this.send(Rt.GetAvailableMatches,e,sa)}getDefinitions(e){return this.send(Rt.GetDefinitions,e,jp)}};var MD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Cd=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),OD={None:"None",Min:"Min",Average:"Average",Max:"Max"},UD=zod.z.enum(["None","Min","Average","Max"]).catch("None"),ED={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},qD=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),LD={Clamp:"Clamp",Reject:"Reject"},BD=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),GD=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),FD=zod.z.object({Index:zod.z.number().nullish(),BurnedItemIDs:zod.z.array(zod.z.string()).nullish(),RolledCollectionID:zod.z.string().nullish(),UsedCollections:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Output:Zr.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(GD).nullish()}),Sd=zod.z.object({ServerTimeUtc:c,Type:Cd.nullish(),CraftID:zod.z.string(),CraftedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),InputRarity:zod.z.string().nullish(),OutputRarity:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:zod.z.array(FD).nullish()}),VD=zod.z.object({CraftID:zod.z.string().nullish(),Type:Cd.nullish(),CatalogID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),InputRarityID:zod.z.string().nullish(),OutputRarityID:zod.z.string().nullish(),RequiredItemCount:zod.z.number().nullish(),PriceOptions:ue.nullish(),OutputLevelMode:UD.nullish(),InputSelection:qD.nullish(),OutputLevelOverflow:BD.nullish()}).passthrough(),wa=zod.z.object({Definitions:zod.z.record(zod.z.string(),VD).nullish()}).passthrough(),xd=zod.z.object({ServerTimeUtc:c.nullish(),CraftDefinitions:wa.nullish()}),Cr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Sr=class extends L{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Cr.GetDefinitions,e,xd)}craft(e){return this.send(Cr.Craft,e,Sd)}};var _D=2e5,xr=class extends L{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,tn,{timeoutMs:_D,autoRetry:false})}readGeneration(e,t){return this.send(e,t,tn,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Ge.GetDefinitions,e,fc)}generateText(e){return this.generate(Ge.GenerateText,e)}getText(e){return this.readGeneration(Ge.GetText,e)}generateImage(e){return this.generate(Ge.GenerateImage,e)}editImage(e){return this.generate(Ge.EditImage,e)}getImage(e){return this.readGeneration(Ge.GetImage,e)}generateVideo(e){return this.generate(Ge.GenerateVideo,e)}getVideo(e){return this.readGeneration(Ge.GetVideo,e)}generateAudio(e){return this.generate(Ge.GenerateAudio,e)}getAudio(e){return this.readGeneration(Ge.GetAudio,e)}generateMusic(e){return this.generate(Ge.GenerateMusic,e)}getMusic(e){return this.readGeneration(Ge.GetMusic,e)}generateThreeD(e){return this.generate(Ge.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Ge.GetThreeD,e)}listGenerations(e){return this.send(Ge.ListGenerations,e,mc)}getGeneration(e){return this.readGeneration(Ge.GetGeneration,e)}};var ND={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},jD=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),bd=zod.z.object({}).passthrough().transform(r=>r),xi=zod.z.object({CollectibleID:zod.z.string(),Rarity:zod.z.number().nullish(),IsSpecial:zod.z.boolean().nullish(),IsDuplicate:zod.z.boolean().nullish(),CollectionCurrencyConverted:zod.z.number().nullish()}),Dd=zod.z.object({GrantedCollectibles:zod.z.array(xi).nullish(),DuplicateCollectibles:zod.z.array(xi).nullish(),CollectionCurrencyEarned:j.nullish()}),Pd=zod.z.object({OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(Dd).nullish(),GrantedCollectibles:zod.z.array(xi).nullish(),DuplicateCollectibles:zod.z.array(xi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Id=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(Dd).nullish(),GrantedCollectibles:zod.z.array(xi).nullish(),DuplicateCollectibles:zod.z.array(xi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),vd=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ma=zod.z.object({SetID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Td=zod.z.array(ve(Ma)),Ad=zod.z.object({Resources:M.nullish(),Inventory:Q.nullish()}),WD=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:Oe.nullish(),OfferedCollectibleID:zod.z.string().nullish(),OfferedCollectibleIsSpecial:zod.z.boolean().nullish(),ReceiverUserID:zod.z.string().nullish(),RequestedCollectibleID:zod.z.string().nullish(),RequestedCollectibleIsSpecial:zod.z.boolean().nullish(),Status:jD.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RespondedAtUtc:c.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),kd=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:c.nullish(),Resources:M.nullish()}),zd=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),wd=zod.z.object({OfferID:zod.z.string(),ReceivedCollectibleID:zod.z.string().nullish(),ReceivedIsSpecial:zod.z.boolean().nullish(),SentCollectibleID:zod.z.string().nullish(),SentCollectibleIsSpecial:zod.z.boolean().nullish(),Transfer:zod.z.unknown().nullish()}),Md=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),Oa=zod.z.object({Offers:zod.z.array(WD).nullish()}),KD=zod.z.object({CollectibleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rarity:zod.z.number().nullish(),HasSpecialVersion:zod.z.boolean().nullish(),SortOrder:zod.z.number().nullish()}).passthrough(),QD=zod.z.object({SetID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SortOrder:zod.z.number().nullish(),Collectibles:zod.z.array(KD).nullish(),SetCompletionReward:H.nullish()}).passthrough(),HD=zod.z.object({CollectionID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SeasonChainID:zod.z.string().nullish(),Sets:zod.z.array(QD).nullish(),GrandPrize:H.nullish()}).passthrough(),Od=zod.z.object({BonusRewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),$D=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:ue.nullish(),BonusRewardSlots:zod.z.array(Ci).nullish(),PityRules:zod.z.array(Si).nullish(),Presets:Od.nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectibleCount:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),GuaranteeMaxRarity:zod.z.boolean().nullish(),RarityWeights:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ColorTier:zod.z.number().nullish()}).passthrough(),JD=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),ZD=zod.z.object({CollectionChestID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectionCurrencyCost:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),MinCollectibleCount:zod.z.number().nullish(),MaxCollectibleCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),BonusRewardSlots:zod.z.array(Ci).nullish(),PityRules:zod.z.array(Si).nullish(),Presets:Od.nullish(),Tier:zod.z.number().nullish()}).passthrough(),YD=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),XD=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),br=zod.z.object({Collections:zod.z.record(zod.z.string(),HD).nullish(),PackTypes:zod.z.record(zod.z.string(),$D).nullish(),CollectionChests:zod.z.array(ZD).nullish(),DuplicateConversions:zod.z.array(JD).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(YD).nullish(),RewardPools:sr.nullish(),Settings:XD.nullish()}).passthrough(),Ne={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var Dr=class extends L{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ne.GetDefinitions,e,br)}getUserState(e){return this.send(Ne.GetUserState,e,bd)}openPack(e){return this.send(Ne.OpenPack,e,Pd)}openCollectionChest(e){return this.send(Ne.OpenCollectionChest,e,Id)}useCollectibleJoker(e){return this.send(Ne.UseCollectibleJoker,e,vd)}claimSetReward(e){return this.send(Ne.ClaimSetReward,e,Ma)}claimSetRewardsBatch(e){return this.send(Ne.ClaimSetRewardsBatch,e,Td)}claimGrandPrize(e){return this.send(Ne.ClaimGrandPrize,e,Ad)}sendTradeOffer(e){return this.send(Ne.SendTradeOffer,e,kd)}cancelTradeOffer(e){return this.send(Ne.CancelTradeOffer,e,zd)}acceptTradeOffer(e){return this.send(Ne.AcceptTradeOffer,e,wd)}declineTradeOffer(e){return this.send(Ne.DeclineTradeOffer,e,Md)}getMyTradeOffers(e){return this.send(Ne.GetMyTradeOffers,e,Oa)}getIncomingTradeOffers(e){return this.send(Ne.GetIncomingTradeOffers,e,Oa)}};var Pr=class extends L{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ht.GetDefinitions,e,on)}getActiveEvent(e){return this.send(ht.GetActiveEvent,e,Rc)}getUserState(e){return this.send(ht.GetUserState,e,rn)}getGroupState(e){return this.send(ht.GetGroupState,e,Lo)}joinOrCreateGroup(e){return this.send(ht.JoinOrCreateGroup,e,Lo)}spin(e){return this.send(ht.Spin,e,Sc)}claimObjectReward(e){return this.send(ht.ClaimObjectReward,e,Bo)}claimGrandPrize(e){return this.send(ht.ClaimGrandPrize,e,Bo)}leaveGroup(e){return this.send(ht.LeaveGroup,e,xc)}};var Ir=class extends L{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(yt.GetDefinition,e,Mc)}getUserState(e){return this.send(yt.GetUserState,e,Oc)}getActiveDeals(e){return this.send(yt.GetActiveDeals,e,un)}dismissDeal(e){return this.send(yt.DismissDeal,e,Ec)}executeNode(e){return this.send(yt.ExecuteNode,e,Uc)}recordShow(e){return this.send(yt.RecordShow,e,qc)}claimMilestone(e){return this.send(yt.ClaimMilestone,e,Lc)}claimMilestonesBatch(e){return this.send(yt.ClaimMilestonesBatch,e,Bc)}};var eP=zod.z.object({}).passthrough().transform(r=>r),tP=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:Re.nullish()}).passthrough(),Ua=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:zod.z.record(zod.z.string(),Le).nullish(),SpendRewards:zod.z.array(tP).nullish()}).passthrough(),Ud=zod.z.object({ReferralDefinitions:Ua.nullish()}).passthrough(),Ed=zod.z.object({Referral:eP.nullish(),InviteUrl:zod.z.string().nullish()}).passthrough(),qd=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Ea=zod.z.object({RewardID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Ld=ft(Ea),Zt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch"};var vr=class extends L{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Zt.GetDefinitions,e,Ud)}getUserState(e){return this.send(Zt.GetUserState,e,Ed)}activateReferralCode(e){return this.send(Zt.ActivateReferralCode,e,qd)}claimInviteReward(e){return this.send(Zt.ClaimInviteReward,e,Ea)}claimInviteRewardsBatch(e){return this.send(Zt.ClaimInviteRewardsBatch,e,Ld)}};var Tr=class extends L{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(et.GetDefinitions,e,Nc)}getMessages(e){return this.send(et.GetMessages,e,jc)}getUnreadCount(e){return this.send(et.GetUnreadCount,e,hn)}readMessages(e){return this.send(et.ReadMessages,e,Vo)}claimReward(e){return this.send(et.ClaimReward,e,dn)}claimRewardsBatch(e){return this.send(et.ClaimRewardsBatch,e,dn)}claimAll(e){return this.send(et.ClaimAll,e,dn)}deleteMessages(e){return this.send(et.DeleteMessages,e,Vo)}sendGift(e){return this.send(et.SendGift,e,Wc)}sendTransfer(e){return this.send(et.SendTransfer,e,Kc)}getGiftStatus(e){return this.send(et.GetGiftStatus,e,Qc)}};var Ar=class extends L{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Ce.GetFriendsList,e,wi)}getIncomingRequests(e){return this.send(Ce.GetIncomingRequests,e,wi)}getOutgoingRequests(e){return this.send(Ce.GetOutgoingRequests,e,wi)}getRecommendedFriends(e){return this.send(Ce.GetRecommendedFriends,e,wi)}sendFriendRequest(e){return this.send(Ce.SendFriendRequest,e,Mi)}acceptFriendRequest(e){return this.send(Ce.AcceptFriendRequest,e,Mi)}declineFriendRequest(e){return this.send(Ce.DeclineFriendRequest,e,Mi)}removeFriend(e){return this.send(Ce.RemoveFriend,e,Mi)}getInbox(e){return this.send(Ce.GetInbox,e,$c)}markInboxSeen(e){return this.send(Ce.MarkInboxSeen,e,Oi)}getInboxUnread(e){return this.send(Ce.GetInboxUnread,e,Oi)}follow(e){return this.send(Ce.Follow,e,Lt)}unfollow(e){return this.send(Ce.Unfollow,e,Lt)}getFollowers(e){return this.send(Ce.GetFollowers,e,fn)}getFollowing(e){return this.send(Ce.GetFollowing,e,fn)}block(e){return this.send(Ce.Block,e,Lt)}unblock(e){return this.send(Ce.Unblock,e,Lt)}getBlocked(e){return this.send(Ce.GetBlocked,e,fn)}react(e){return this.send(Ce.React,e,Lt)}unreact(e){return this.send(Ce.Unreact,e,Lt)}getMyReactions(e){return this.send(Ce.GetMyReactions,e,Zc)}getEntityStates(e){return this.send(Ce.GetEntityStates,e,Jc)}addComment(e){return this.send(Ce.AddComment,e,gn)}editComment(e){return this.send(Ce.EditComment,e,gn)}deleteComment(e){return this.send(Ce.DeleteComment,e,Xc)}getComments(e){return this.send(Ce.GetComments,e,Yc)}report(e){return this.send(Ce.Report,e,ep)}};var iP={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Yt=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),sP=zod.z.object({BoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ue.nullish(),Effect:Yt.nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),kr=zod.z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),qa=zod.z.object({Availability:K.nullish(),Effects:K.nullish()}).passthrough(),nP=zod.z.object({ScheduledBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Effects:zod.z.array(Yt).nullish(),Availability:kr.nullish(),Presets:qa.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rP=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(Yt).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),oP=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Phases:zod.z.array(rP).nullish(),Availability:kr.nullish(),Presets:qa.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),aP=zod.z.object({TriggeredBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Sources:zod.z.array(st).nullish(),Effects:zod.z.array(Yt).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:kr.nullish(),Presets:qa.nullish()}).passthrough(),lP=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),uP=zod.z.object({Effects:zod.z.array(Yt).nullish()}).passthrough(),cP=zod.z.object({Availability:zod.z.record(zod.z.string(),kr).nullish(),Effects:zod.z.record(zod.z.string(),uP).nullish()}).passthrough(),pP=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),lP).nullish()}).passthrough(),zr=zod.z.object({Definitions:zod.z.record(zod.z.string(),sP).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),nP).nullish(),BoostChains:zod.z.record(zod.z.string(),oP).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),aP).nullish(),Settings:pP.nullish(),Presets:cP.nullish()}).passthrough(),Bd=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:Yt.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:c.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:c.nullish()}).passthrough();var Gd=zod.z.object({ServerTimeUtc:c.nullish(),Active:zod.z.record(zod.z.string(),Bd).nullish()}),Fd=zod.z.object({ServerTimeUtc:c.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:Bd.nullish(),Resources:M.nullish()}),hP={Scheduled:"Scheduled",Chain:"Chain"},dP=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),Effects:zod.z.array(Yt).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Vd=zod.z.object({ServerTimeUtc:c.nullish(),Windows:zod.z.array(dP).nullish()}),Xt={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var wr=class extends L{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(Xt.GetDefinitions,e,zr)}getActive(e){return this.send(Xt.GetActive,e,Gd)}getActiveWindows(e){return this.send(Xt.GetActiveWindows,e,Vd)}activate(e){return this.send(Xt.Activate,e,Fd)}cleanupExpired(e){return this.send(Xt.CleanupExpired,e,Ue)}};var Mr=class extends L{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(dt.GetUserCustomDataDefinitions,e,Sn)}getMyUserCustomData(e){return this.send(dt.GetMyUserCustomData,e,np)}getPublicUserCustomDataOf(e){return this.send(dt.GetPublicUserCustomDataOf,e,Ko)}setPrivateData(e){return this.send(dt.SetPrivateData,e,Qo)}setPublicData(e){return this.send(dt.SetPublicData,e,Qo)}deleteKey(e){return this.send(dt.DeleteKey,e,Ue)}batchSet(e){return this.send(dt.BatchSet,e,rp)}batchDelete(e){return this.send(dt.BatchDelete,e,op)}batchGetPublicUserCustomDataOf(e){return this.send(dt.BatchGetPublicUserCustomDataOf,e,ap)}};var mP={Static:"Static",Runtime:"Runtime"},fP={Public:"Public",Private:"Private"},gP=zod.z.enum(["Client","Server","System"]).catch("Client"),yP=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),RP=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:c.nullish(),Version:zod.z.number().nullish(),LastWriter:gP.nullish(),ExpiresAt:c.nullish()}).passthrough(),_d=zod.z.record(zod.z.string(),RP),La=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:_d.nullish(),Runtime:_d.nullish(),NotModified:zod.z.boolean().nullish()}),CP=zod.z.object({KeyID:zod.z.string(),Scope:zod.z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:zod.z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:yP.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Or=zod.z.object({Keys:zod.z.record(zod.z.string(),CP).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),Gi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Ur=class extends L{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Gi.GetTitleCustomDataDefinitions,e,Or)}getPublicTitleData(e){return this.send(Gi.GetPublicTitleData,e,La)}getPublicTitleDataKeys(e){return this.send(Gi.GetPublicTitleDataKeys,e,La)}};var SP={Fast:"Fast",Sequential:"Sequential"},xP={Instant:"Instant",Timed:"Timed"};var bP={Hit:"Hit",Blocked:"Blocked"},DP=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),PP=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:H.nullish()}).passthrough();var IP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:H.nullish()}).passthrough(),vP=zod.z.object({Reward:H.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough();zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(IP).nullish(),Rate:vP.nullish()}).passthrough();zod.z.object({PlayedCount:zod.z.number().nullish(),RewardsClaimedCount:zod.z.number().nullish(),InstantClaimsCount:zod.z.number().nullish(),EarlyClaimsCount:zod.z.number().nullish(),LateClaimsCount:zod.z.number().nullish(),AdViewsTotal:zod.z.number().nullish(),StatRewardClaimsCount:zod.z.number().nullish(),StatReportsClampedCount:zod.z.number().nullish(),StatReportsUnknownMetricCount:zod.z.number().nullish()}).passthrough();var Nd=zod.z.object({}).passthrough().transform(r=>r),jd=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),je=zod.z.object({Operation:M.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),TP=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),AP=zod.z.object({ShieldChance:zod.z.number().nullish(),DamagedBuildingChance:zod.z.number().nullish(),RankMultiplierMin:zod.z.number().nullish(),RankMultiplierMax:zod.z.number().nullish(),RankOffsetMin:zod.z.number().nullish(),RankOffsetMax:zod.z.number().nullish(),StageLevelSpread:zod.z.number().nullish()}).passthrough(),kP=zod.z.object({CostMatrixTemplatesByID:zod.z.record(zod.z.string(),zod.z.array(zod.z.array(zod.z.number()))).nullish(),PerBoardGrowth:zod.z.number().nullish(),VisualTemplateCycle:zod.z.array(zod.z.string()).nullish(),EconomyScaledResources:ce.nullish(),ScaleRaidStealWithEconomy:zod.z.boolean().nullish(),ScaleAttackRewardWithEconomy:zod.z.boolean().nullish(),AttackValueFromCostMatrix:zod.z.boolean().nullish(),AttackBlockedRewardFactor:zod.z.number().nullish(),ScaleVictimLossWithEconomy:zod.z.boolean().nullish(),ScaleVictimLossWithTier:zod.z.boolean().nullish(),SynthesizedBuildingSlots:zod.z.number().nullish(),SynthesizedBuildingMaxLevel:zod.z.number().nullish(),DifficultyGrowthPerBoard:zod.z.number().nullish()}).passthrough(),zP=zod.z.object({CostMatrix:zod.z.array(zod.z.array(zod.z.number())).nullish(),PerBoardGrowth:zod.z.number().nullish(),EconomyScale:zod.z.number().nullish(),ScaledResources:ce.nullish()}).passthrough(),Wd=zod.z.object({SlotIndex:zod.z.number().nullish(),Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxLevel:zod.z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),wP=zod.z.object({Index:zod.z.number().nullish(),Type:zod.z.string().nullish(),CustomTypeID:zod.z.string().nullish(),RandomActionAttackWeight:zod.z.number().nullish(),RandomActionRaidWeight:zod.z.number().nullish(),ChanceTableID:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),MP=zod.z.object({Tiles:zod.z.record(zod.z.string(),wP).nullish()}).passthrough(),OP=zod.z.object({Weight:zod.z.number().nullish(),Bonus:je.nullish(),Tag:zod.z.string().nullish()}).passthrough(),UP=zod.z.object({Weight:zod.z.number().nullish(),Tag:zod.z.string().nullish(),MinBonusCells:zod.z.number().nullish(),MaxBonusCells:zod.z.number().nullish(),BonusPool:zod.z.array(OP).nullish(),GuaranteedBonus:je.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),EP=zod.z.object({Variants:zod.z.array(UP).nullish()}).passthrough(),qP=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:je.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),LP=zod.z.object({Outcomes:zod.z.array(qP).nullish()}).passthrough(),Kd=zod.z.object({PerAdMultiplierRange:jd.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),BP=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:je.nullish()}).passthrough(),GP=zod.z.object({Tiers:zod.z.array(BP).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:je.nullish()}).passthrough(),FP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:je.nullish()}).passthrough(),VP=zod.z.object({Reward:je.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),_P=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(FP).nullish(),Rate:VP.nullish()}).passthrough(),Qd=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),_P).nullish()}).passthrough(),NP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:je.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ue.nullish(),Multipliers:Kd.nullish(),Gradation:GP.nullish(),RunStats:Qd.nullish()}).passthrough(),jP=zod.z.object({Choices:zod.z.array(NP).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),WP=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:je.nullish(),Tag:zod.z.string().nullish()}).passthrough(),KP=zod.z.object({OnPassStart:je.nullish(),OnTileLanding:zod.z.record(zod.z.string(),je).nullish(),OnAttack:zod.z.record(zod.z.string(),je).nullish(),OnRaid:zod.z.record(zod.z.string(),je).nullish(),OnBuild:je.nullish(),OnStageComplete:je.nullish(),OnAttackBonusDrops:zod.z.array(WP).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),LP).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),jP).nullish()}).passthrough(),Hd=zod.z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Wd).nullish(),HeistGridBonusConfig:EP.nullish(),StageOperations:KP.nullish(),TileLandingMultiplier:jd.nullish(),EconomyOverride:zP.nullish()}).passthrough(),QP=zod.z.object({Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BoardTemplateID:zod.z.string().nullish(),Buildings:zod.z.array(Wd).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:Hd.nullish()}).passthrough(),HP=zod.z.object({AttackCooldownSeconds:zod.z.number().nullish(),RaidCooldownSeconds:zod.z.number().nullish(),MaxRecentTargets:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),LiveOpponentPoolSize:zod.z.number().nullish(),LiveOpponentPoolCacheSeconds:zod.z.number().nullish(),MaxLiveCandidateReads:zod.z.number().nullish(),VictimImmunitySeconds:zod.z.number().nullish()}).passthrough(),$P=zod.z.object({Enabled:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),MaxPerCatchUp:zod.z.number().nullish(),Chance:zod.z.number().nullish(),AttackWeight:zod.z.number().nullish(),RaidWeight:zod.z.number().nullish(),MinBoardStageLevel:zod.z.number().nullish(),RaidLossMultiplier:zod.z.number().nullish()}).passthrough(),Er=zod.z.object({RollCurrencyID:zod.z.string().nullish(),ShieldCurrencyID:zod.z.string().nullish(),RaidMode:zod.z.string().nullish(),AllowedRollMultipliers:zod.z.array(zod.z.number()).nullish(),BoardTemplatesByID:zod.z.record(zod.z.string(),MP).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),Hd).nullish(),StagesByLevel:zod.z.record(zod.z.string(),QP).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:kP.nullish(),Dice:TP.nullish(),Bots:AP.nullish(),Targeting:HP.nullish(),BotRaids:$P.nullish()}).passthrough(),JP=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:c.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),Le).nullish(),GrandPrize:H.nullish()}).passthrough(),qr=zod.z.object({Board:Er.nullish(),CommunityChest:JP.nullish()}).passthrough(),$d=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),ce).nullish()}).passthrough(),ZP=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Oe.nullish(),TargetBuildingStates:zod.z.array(DP).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:$d.nullish()}).passthrough(),YP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:je.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ue.nullish(),Multipliers:Kd.nullish(),RunStats:Qd.nullish()}).passthrough(),XP=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(YP).nullish()}).passthrough(),eI=zod.z.object({GroupID:zod.z.string().nullish(),Delta:j.nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),Jd=zod.z.object({UsedMultiplier:zod.z.number().nullish(),Steps:zod.z.number().nullish(),DiceValues:zod.z.array(zod.z.number()).nullish(),OldPosition:zod.z.number().nullish(),NewPosition:zod.z.number(),CyclesCompletedDelta:j.nullish(),LandedTileType:zod.z.string().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:ZP.nullish(),SpecialModeOffer:XP.nullish(),CommunityChestContribution:eI.nullish()}).passthrough(),Zd=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:bt.nullish()}).passthrough(),Ba=zod.z.object({Status:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),FoundSymbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(PP).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:bt.nullish(),RaidRewardPreview:$d.nullish()}).passthrough(),Yd=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish()}).passthrough(),Xd=zod.z.object({Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish()}).passthrough(),em=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),tI=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),tm=zod.z.object({FinalMultiplier:zod.z.number().nullish(),AdViewsUsed:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),IsEarlyClaim:zod.z.boolean().nullish(),ReachedTierIndex:zod.z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(tI).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),iI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},im=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),sI={Active:"Active",Left:"Left",Replaced:"Replaced"},nI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),rI=zod.z.object({CurrentProgress:j.nullish(),MaxProgress:j.nullish()}).passthrough(),oI=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Oe.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:j.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),ml).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:nI.nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),sm=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(oI).nullish(),SharedProgress:rI.nullish(),Status:im.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:zod.z.number().nullish()}).passthrough(),aI=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:im.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:c.nullish()}).passthrough(),lI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(aI).nullish()}).passthrough(),nm=zod.z.object({ServerTimeUtc:c.nullish(),UserState:lI.nullish(),ActiveGroup:sm.nullish(),SecondsRemaining:j.nullish()}),rm=zod.z.object({ServerTimeUtc:c.nullish(),Group:sm.nullish(),SecondsRemaining:j.nullish()}),Ga=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),om=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),qe={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var uI={Mesh:"Mesh",Host:"Host"},Fa=zod.z.enum(["Mesh","Host"]).catch("Mesh"),cI={ServerRelay:"ServerRelay",P2P:"P2P"},Va=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),pI={Public:"Public",Private:"Private"},hI=zod.z.enum(["Public","Private"]).catch("Public"),dI={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},mI=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),am=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),fI=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),lm=zod.z.object({SystemState:fI.nullish(),DefaultTopology:Fa.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:Va.nullish(),AllowCreatorChatOverride:zod.z.boolean().nullish(),MaxPlayersPerRoom:zod.z.number().nullish(),RoomTtlSeconds:zod.z.number().nullish(),MaxRoomLifetimeSeconds:zod.z.number().nullish(),HeartbeatIntervalMs:zod.z.number().nullish(),MemberTimeoutMs:zod.z.number().nullish(),MaxSignalPayloadBytes:zod.z.number().nullish(),MaxChatTextLength:zod.z.number().nullish(),RoomLogCap:zod.z.number().nullish(),VoiceEnabled:zod.z.boolean().nullish(),RecordVoices:zod.z.boolean().nullish(),IceServers:zod.z.array(am).nullish()}).passthrough(),gI=zod.z.object({UserID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),Ready:zod.z.boolean().nullish(),State:zod.z.record(zod.z.string(),zod.z.string()).nullish(),JoinedAt:zod.z.number().nullish(),IsHost:zod.z.boolean().nullish(),LastSeenMs:zod.z.number().nullish()}).passthrough(),yI=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:Fa.nullish(),ChatMode:Va.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),RI=zod.z.object({Seq:zod.z.number().nullish(),Type:mI.nullish(),FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Payload:zod.z.string().nullish(),Ts:zod.z.number().nullish()}).passthrough(),Fi=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:Fa.nullish(),ChatMode:Va.nullish(),Visibility:hI.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),Members:zod.z.array(gI).nullish(),IceServers:zod.z.array(am).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),um=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),cm=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),_a=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),pm=zod.z.object({Rooms:zod.z.array(yI).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),hm=zod.z.object({Envelopes:zod.z.array(RI).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Lr=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),He={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 Na=zod.z.object({TitleCustomData:Or.nullish(),Character:Zs.nullish(),Item:Jn.nullish(),Currency:Tn.nullish(),Store:Rs.nullish(),Lootbox:Ta.nullish(),Quest:Hi.nullish(),TimedEvent:qs.nullish(),Leaderboard:js.nullish(),Season:Qs.nullish(),Reward:ka.nullish(),Collection:br.nullish(),Craft:wa.nullish(),DealOffer:Go.nullish(),Premium:Pa.nullish(),TimedBoost:zr.nullish(),CoopEvent:on.nullish(),GameLoop:qr.nullish(),Match:na.nullish(),Experiment:Th.nullish(),Blockchain:Zo.nullish(),Marketplace:ua.nullish(),Multiplayer:lm.nullish(),UserCustomData:Sn.nullish(),Referral:Ua.nullish(),Localization:Lh.nullish(),Analytics:gh.nullish(),Social:tp.nullish(),PlatformBridge:ip.nullish()}).passthrough();var ei={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Br=class extends L{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(ei.GetTitlePublicConfiguration,e,Na)}getTitlePublicConfigurationExcept(e){return this.send(ei.GetTitlePublicConfigurationExcept,e,Na)}getCurrencyDefinitions(e){return this.send(ei.GetCurrencyDefinitions,e,Tn)}getItemDefinitions(e){return this.send(ei.GetItemDefinitions,e,Jn)}getServerTime(e){return this.send(ei.GetServerTime,e,Ue)}};var Gr=class extends L{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(qe.GetGameLoops,e,qr)}getBoardDefinition(e,t=false){return this.send(qe.GetBoardDefinition,e,Er,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(qe.GetBoardDefinitionForLevel,e,Er,{silent:t})}getUserBoardState(e){return this.send(qe.GetUserBoardState,e,Nd)}boardLoopRoll(e){return this.send(qe.BoardLoopRoll,e,Jd)}boardLoopAttack(e){return this.send(qe.BoardLoopAttack,e,Zd)}boardLoopRaid(e){return this.send(qe.BoardLoopRaid,e,Ba)}boardLoopRaidFast(e){return this.send(qe.BoardLoopRaidFast,e,Ba)}boardLoopBuild(e){return this.send(qe.BoardLoopBuild,e,Yd)}boardSpecialChoose(e){return this.send(qe.BoardSpecialChoose,e,Xd)}boardSpecialApplyMultiplier(e){return this.send(qe.BoardSpecialApplyMultiplier,e,em)}boardSpecialClaim(e){return this.send(qe.BoardSpecialClaim,e,tm)}getCommunityChestState(e){return this.send(qe.GetCommunityChestState,e,nm)}joinOrCreateCommunityChest(e){return this.send(qe.JoinOrCreateCommunityChest,e,rm)}claimCommunityChestMilestone(e){return this.send(qe.ClaimCommunityChestMilestone,e,Ga)}claimCommunityChestGrandPrize(e){return this.send(qe.ClaimCommunityChestGrandPrize,e,Ga)}leaveCommunityChest(e){return this.send(qe.LeaveCommunityChest,e,om)}};var SI={Live:"Live",Latest:"Latest",Specific:"Specific"},xI={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},bI=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),DI={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"},PI=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),II=zod.z.object({Level:bI,Message:zod.z.string().nullish(),Data:Et.nullish()}),vI=zod.z.object({Error:PI,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),dm=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Et.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(II).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:vI.nullish()}),ja={Execute:"Execute"};var Fr=class extends L{constructor(e){super(e,"CloudCode");}execute(e){return this.send(ja.Execute,e,dm)}};var Vr=class extends L{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Qe.GetDefinitions,e,Pp)}getUserState(e){return this.send(Qe.GetUserState,e,Ip)}depositToken(e){return this.send(Qe.DepositToken,e,vp)}depositNFT(e){return this.send(Qe.DepositNFT,e,Tp)}requestTokenWithdrawal(e){return this.send(Qe.RequestTokenWithdrawal,e,Ap)}requestNFTWithdrawal(e){return this.send(Qe.RequestNFTWithdrawal,e,kp)}getTransactionHistory(e){return this.send(Qe.GetTransactionHistory,e,zp)}retryWithdrawal(e){return this.send(Qe.RetryWithdrawal,e,wp)}confirmWithdrawal(e){return this.send(Qe.ConfirmWithdrawal,e,Mp)}donateToDeveloper(e){return this.send(Qe.DonateToDeveloper,e,ta)}donateToUsersPool(e){return this.send(Qe.DonateToUsersPool,e,ta)}getPlayAccess(e){return this.send(Qe.GetPlayAccess,e,bp)}confirmPlayAccess(e){return this.send(Qe.ConfirmPlayAccess,e,Bt)}};var _r=class extends L{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(ke.GetDefinitions,e,Kp)}getGroupedOffers(e){return this.send(ke.GetGroupedOffers,e,Qp)}getOffersByItem(e){return this.send(ke.GetOffersByItem,e,ca)}getOffer(e){return this.send(ke.GetOffer,e,Hp)}getBuyOrders(e){return this.send(ke.GetBuyOrders,e,ca)}getMyState(e){return this.send(ke.GetMyState,e,Un)}getHistory(e){return this.send(ke.GetHistory,e,Jp)}createListing(e){return this.send(ke.CreateListing,e,qi)}cancelListing(e){return this.send(ke.CancelListing,e,at)}buy(e){return this.send(ke.Buy,e,at)}marketBuy(e){return this.send(ke.MarketBuy,e,at)}marketSell(e){return this.send(ke.MarketSell,e,at)}createAuction(e){return this.send(ke.CreateAuction,e,qi)}placeBid(e){return this.send(ke.PlaceBid,e,$p)}claimAuction(e){return this.send(ke.ClaimAuction,e,at)}createBuyOrder(e){return this.send(ke.CreateBuyOrder,e,qi)}cancelBuyOrder(e){return this.send(ke.CancelBuyOrder,e,at)}fillBuyOrder(e){return this.send(ke.FillBuyOrder,e,at)}createDirectTrade(e){return this.send(ke.CreateDirectTrade,e,qi)}respondDirectTrade(e){return this.send(ke.RespondDirectTrade,e,at)}cancelDirectTrade(e){return this.send(ke.CancelDirectTrade,e,at)}claimBack(e){return this.send(ke.ClaimBack,e,at)}};var Nr=class extends L{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(He.CreateRoom,e,Fi)}joinRoom(e){return this.send(He.JoinRoom,e,Fi)}leaveRoom(e,t=false){return this.send(He.LeaveRoom,e,_a,{keepalive:t})}listRooms(e){return this.send(He.ListRooms,e,pm)}getRoom(e){return this.send(He.GetRoom,e,Fi)}closeRoom(e){return this.send(He.CloseRoom,e,_a)}poll(e){return this.send(He.Poll,e,hm)}sendSignal(e){return this.send(He.SendSignal,e,Lr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(He.ClaimHost,e,Fi)}kickMember(e){return this.send(He.KickMember,e,um)}unbanMember(e){return this.send(He.UnbanMember,e,cm)}sendChat(e){return this.send(He.SendChat,e,Lr)}setMemberState(e){return this.send(He.SetMemberState,e,Lr)}};var TI={Free:"Free",Price:"Price",Holding:"Holding"},Wa=zod.z.enum(["Free","Price","Holding"]).catch("Free"),AI={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},kI=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),zI={All:"All",Any:"Any"},wI=zod.z.enum(["All","Any"]).catch("All"),MI={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},OI=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),UI={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},EI=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),qI={Purchase:"Purchase",Free:"Free",Holding:"Holding"},fm=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),LI={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},BI={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},GI=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),FI=zod.z.object({Type:li.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),MinLevel:zod.z.number().nullish()}).passthrough(),VI=zod.z.object({Requirements:zod.z.array(FI).nullish(),Match:wI.nullish(),Mode:kI.nullish()}).passthrough(),_I=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Wa.nullish(),Price:ce.nullish(),Holding:VI.nullish()}).passthrough(),NI=zod.z.object({AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxBytes:zod.z.number().nullish(),MaxCount:zod.z.number().nullish(),Required:zod.z.boolean().nullish()}).passthrough(),jI=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),NI).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(Wa).nullish(),PricePolicy:On.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ue.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),WI=zod.z.object({Allowed:zod.z.array(Ei).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),KI=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),QI=zod.z.object({MaxTitleLength:zod.z.number().nullish(),MaxDescriptionLength:zod.z.number().nullish(),MaxTags:zod.z.number().nullish(),MaxTagLength:zod.z.number().nullish(),MaxMetadataKeys:zod.z.number().nullish(),MaxMetadataValueLength:zod.z.number().nullish(),MaxAccessOptions:zod.z.number().nullish(),ThumbnailMaxBytes:zod.z.number().nullish()}).passthrough(),HI=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Order:zod.z.number().nullish()}).passthrough(),$I=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),ContentTypes:zod.z.record(zod.z.string(),jI).nullish(),PricePolicy:On.nullish(),Commission:la.nullish(),HoldingPolicy:WI.nullish(),Moderation:KI.nullish(),Limits:QI.nullish(),Featured:zod.z.array(HI).nullish()}).passthrough(),JI=zod.z.object({Acquisitions:zod.z.number().nullish(),Downloads:zod.z.number().nullish(),Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),ReportCount:zod.z.number().nullish(),Remixes:zod.z.number().nullish()}).passthrough(),ti=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:Oe.nullish(),Title:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Metadata:zod.z.record(zod.z.string(),zod.z.string()).nullish(),ThumbnailUrl:zod.z.string().nullish(),Visibility:OI.nullish(),Access:zod.z.array(_I).nullish(),Status:EI.nullish(),ModerationNote:zod.z.string().nullish(),Stats:JI.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),PublishedAt:c.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),ZI=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Wa.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),gm=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Order:zod.z.number().nullish()}).passthrough(),ym=zod.z.object({Definitions:$I.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish(),CanPublish:zod.z.record(zod.z.string(),zod.z.boolean()).nullish(),Collections:zod.z.array(gm).nullish()}).passthrough(),jr=zod.z.object({Items:zod.z.array(ti).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Rm=zod.z.object({Content:ti.nullish(),AccessState:zod.z.array(ZI).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Cm=zod.z.object({Collection:gm.nullish(),Items:zod.z.array(ti).nullish()}).passthrough(),Sm=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:Oe.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(ti).nullish()}).passthrough(),mm=zod.z.object({Role:zod.z.string().nullish(),Index:zod.z.number().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish(),ServerCopy:zod.z.boolean().nullish()}).passthrough(),xm=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(mm).nullish(),ThumbnailUpload:mm.nullish(),ExpiresAt:c.nullish()}).passthrough(),bm=zod.z.object({Content:ti.nullish(),Resources:M.nullish()}).passthrough(),Ka=zod.z.object({Content:ti.nullish()}).passthrough(),Dm=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:fm.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:ce.nullish()}).passthrough(),YI=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),Pm=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:GI.nullish(),Files:zod.z.array(YI).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:c.nullish()}).passthrough(),XI=zod.z.object({ContentID:zod.z.string().nullish(),Source:fm.nullish(),OptionID:zod.z.string().nullish(),PricePaid:ce.nullish(),AcquiredAt:c.nullish(),Content:ti.nullish()}).passthrough(),Im=zod.z.object({Licenses:zod.z.array(XI).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),We={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 Wr=class extends L{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(We.GetDefinitions,e,ym)}browse(e){return this.send(We.Browse,e,jr)}getContent(e){return this.send(We.GetContent,e,Rm)}getCollection(e){return this.send(We.GetCollection,e,Cm)}getCreatorProfile(e){return this.send(We.GetCreatorProfile,e,Sm)}beginUpload(e){return this.send(We.BeginUpload,e,xm)}publish(e){return this.send(We.Publish,e,bm)}updateContent(e){return this.send(We.UpdateContent,e,Ka)}unpublish(e){return this.send(We.Unpublish,e,Ka)}getMyContent(e){return this.send(We.GetMyContent,e,jr)}acquire(e){return this.send(We.Acquire,e,Dm)}getDownload(e){return this.send(We.GetDownload,e,Pm)}getMyLicenses(e){return this.send(We.GetMyLicenses,e,Im)}getMyFavorites(e){return this.send(We.GetMyFavorites,e,jr)}};var Kr=class extends L{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,ih,"defs")}get(e){return this.sendKeyed("Get",e,ha,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,nh,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,da,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,rh,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,ma,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,ma,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,oh,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,lh,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,ah,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,uh,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,sh,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,ch,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,ha,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,da,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Qr=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=Xa(e),this.emitter=new Pi,this.platform=e.platform??new ri,this.clientPlatform=e.clientPlatform??hl(),this.acquisition=new _t(this.platform),this.acquisition.capture(),this.playtime=new Ii(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear();}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new ts({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 rs(this.emitter),this.cache=new as(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new ls(this.platform.storage,this.settings.titleID),this.api={authentication:new Wn(this),user:new Qn(this),currency:new Hn(this),item:new Zn(this),store:new Yn(this),purchase:new ir(this),lootbox:new rr(this),reward:new or(this),quest:new hr(this),tutorial:new ar(this),communityMarketing:new lr(this),chat:new ur(this),push:new cr(this),localization:new pr(this),timedEvent:new dr(this),leaderboard:new mr(this),season:new fr(this),premium:new gr(this),character:new yr(this),match:new Rr(this),craft:new Sr(this),ai:new xr(this),collection:new Dr(this),coopEvent:new Pr(this),dealOffer:new Ir(this),referral:new vr(this),mailbox:new Tr(this),social:new Ar(this),timedBoost:new wr(this),userCustomData:new Mr(this),titleCustomData:new Ur(this),title:new Br(this),gameLoop:new Gr(this),cloudCode:new Fr(this),blockchain:new Vr(this),marketplace:new _r(this),multiplayer:new Nr(this),workshop:new Wr(this),dataCollections:new Kr(this),analytics:new Nn(this),experiment:new jn(this)},this.userService=new ds(this),this.cache.attachState(this.userService),this.auth=new us(this),this.currency=new fs(this),this.item=new gs(this),this.store=new Ss(this),this.purchase=new xs(this),this.checkout=new Ds(this),this.lootbox=new Ps(this),this.reward=new Is(this),this.quest=new Es(this),this.tutorial=new Ts(this),this.communityMarketing=new As(this),this.chat=new ws(this),this.push=new Ms(this),this.localization=new Us(this),this.timedEvent=new Bs(this),this.leaderboard=new Ws(this),this.season=new Hs(this),this.premium=new $s(this),this.character=new Ys(this),this.match=new Xs(this),this.craft=new en(this),this.ai=new sn(this),this.collection=new nn(this),this.coopEvent=new an(this),this.dealOffer=new cn(this),this.referral=new pn(this),this.mailbox=new mn(this),this.social=new yn(this),this.timedBoost=new Rn(this),this.userCustomData=new xn(this),this.titleCustomData=new bn(this),this.title=new Dn(this),this.gameLoop=new Pn(this),this.cloudCode=new In(this),this.blockchain=new kn(this),this.marketplace=new En(this),this.multiplayer=new qn(this),this.workshop=new Ln(this),this.dataCollections=new Gn(this),this.analytics=new Vn(this),this.experiments=new _n(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.platform.getFullURL(),RelatedEntityID:B()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var Hr=class{ctx;constructor(e){this.ctx=new Qr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Ft(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},zod.z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function tv(r){return new Hr(r)}var vm="idos_sso",Tm="state",Qa="idos:sso:state",iv="https://idosgames.com/sso/",sv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],nv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function rv(){if(typeof window>"u")return false;let{origin:r}=window.location;return sv.includes(r)||nv.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function ov(){if(typeof window>"u")return null;let r=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!r)return null;let e=new URLSearchParams(r),t=e.get(vm);if(!t)return null;let i=e.get(Tm)??"",s=pv();return dv(e),hv(),s&&i!==s?null:{code:t,state:i}}function av(r){if(typeof window>"u")return;let e=r.returnTo??lv(),t=uv();cv(t);let i=new URL(r.ssoUrl??iv);i.searchParams.set("title",r.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function lv(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function uv(){let r=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(r);else for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*256);return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function cv(r){try{window.sessionStorage.setItem(Qa,r);}catch{}}function pv(){try{return window.sessionStorage.getItem(Qa)}catch{return null}}function hv(){try{window.sessionStorage.removeItem(Qa);}catch{}}function dv(r){r.delete(vm),r.delete(Tm);let e=r.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var mv={EMAIL_SENDER_NOT_CONFIGURED:"Sign-in by e-mail is unavailable in this game right now. Try another way to sign in.",INVALID_VERIFICATION_CODE:"That code is not right. Check the e-mail and try again.",VERIFICATION_CODE_ATTEMPTS_EXCEEDED:"Too many wrong attempts. Ask for a new code.",INCORRECT_EMAIL_OR_PASSWORD:"Wrong e-mail or password.",INCORRECT_EMAIL:"That does not look like an e-mail address.",PASSWORD_LENGTH_INVALID:"The password must be 8 to 100 characters long.",TOO_MANY_FAILED_ATTEMPTS:"Too many attempts. Please try again a little later.",RATE_LIMIT_EXCEEDED:"Too many requests. Please try again in a moment.",APPLE_EMAIL_MISSING:"Apple did not share an e-mail address. Try again and allow it, or use another way to sign in.",INVALID_WALLET_SIGNATURE:"The signature does not match the wallet. Please try again.",WALLET_CHALLENGE_EXPIRED:"The request expired. Please try again.",WALLET_CHANGES_TOO_FREQUENT:"Too many wallets were changed this week. Try again in a few days.",WALLET_UNLINK_COOLDOWN:"This wallet was unlinked from another account less than 7 days ago. Try again after the 7 days.",PLAY_ACCESS_GUEST_DISABLED:"Guest play is off in this game. Sign in to link a crypto wallet.",PLAY_ACCESS_WALLET_LOGIN_ONLY:"This game can only be entered with a crypto wallet or your iDos Games account.",PLAY_ACCESS_WALLET_USED_BY_ANOTHER_ACCOUNT:"This wallet already plays with another account.",PLAY_ACCESS_WALLET_REQUIRED:"Link a crypto wallet to play.",PLAY_ACCESS_WALLET_NETWORK_NOT_GATED:"This wallet's network is not accepted here. Link a wallet of the required network.",PLAY_ACCESS_REQUIRED:"Check your balance to continue.",PLAY_ACCESS_CHECK_FAILED:"Could not check your balance right now. Please try again in a moment."};function fv(r,e="Something went wrong. Please try again."){return r?mv[r]??r:e}function gv(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function yv(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function Rv(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function km(r,e,t,i=1){if(!r)return e;let s=r.Base??e,n=Math.max(0,t-i),o;switch(r.Shape??"Flat"){case "PerStep":o=s+(r.PerStep??0)*n;break;case "PerStepRate":o=s*(1+(r.PerStepRate??0)*n);break;case "Geometric":o=s*Math.pow(1+(r.GrowthRate??0),n);break;case "Table":o=s*Am(r,t,1);break;case "TableAbsolute":o=Am(r,t,s);break;default:o=s;break}return Number.isNaN(o)?s:(r.MinResult!=null&&o<r.MinResult&&(o=r.MinResult),r.MaxResult!=null&&o>r.MaxResult&&(o=r.MaxResult),o)}function Cv(r,e,t=1){return km(r,1,e,t)}function Sv(r){if(!r)return false;switch(r.Shape??"Flat"){case "PerStep":return (r.PerStep??0)!==0;case "PerStepRate":return (r.PerStepRate??0)!==0;case "Geometric":return (r.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return zm(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function xv(r){if(Number.isNaN(r)||r<=0)return 0;if(!Number.isFinite(r))return Number.MAX_SAFE_INTEGER;let e=Math.round(r);return Math.abs(r-e)<=1e-9*Math.max(1,Math.abs(r))?e:Math.ceil(r)}function zm(r){if(!r)return [];let e=[];for(let t of r)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function Am(r,e,t){let i=zm(r.Points);if(i.length===0)return t;let s=null,n=null,o=null;for(let p of i)(o===null||p.AtStep>o.AtStep)&&(o=p),p.AtStep<=e&&(s===null||p.AtStep>=s.AtStep)&&(s=p),p.AtStep>e&&(n===null||p.AtStep<n.AtStep)&&(n=p);if(s===null)return t;if(n===null){let p=r.TailGrowthRate??0;return p===0?o.Value:o.Value*Math.pow(1+p,e-o.AtStep)}switch(r.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+p*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let d=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+d*(n.Value-s.Value)}let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,p)}default:return s.Value}}var bv={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Ha=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),Dv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Pv=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),Iv=zod.z.object({PlacementID:zod.z.string().nullish(),Type:Ha.nullish(),Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),CreditsRewarded:zod.z.number().nullish(),AllowedProviderIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),vv=zod.z.object({DefaultCreditsPerView:zod.z.number().nullish(),MaxCreditsBalance:zod.z.number().nullish(),DailyCreditEarnCap:zod.z.number().nullish(),DailyViewCap:zod.z.number().nullish(),MinSecondsBetweenViews:zod.z.number().nullish()}).passthrough(),Tv=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),Av=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:Pv.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),kv=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),zv=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),wv=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),DisableInterstitials:zod.z.boolean().nullish(),DisableBanners:zod.z.boolean().nullish(),DisableAppOpen:zod.z.boolean().nullish()}).passthrough(),Mv=zod.z.object({RequirePersonalizedAdsConsent:zod.z.boolean().nullish(),RequireTrackingConsent:zod.z.boolean().nullish(),CurrentPolicyVersion:zod.z.string().nullish(),RegulatedRegions:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ov=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),Uv=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:Ha.nullish()}).passthrough(),Ev={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},qv=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Lv=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:qv.nullish(),Enabled:zod.z.boolean().nullish(),Priority:zod.z.number().nullish(),AndroidAppID:zod.z.string().nullish(),IosAppID:zod.z.string().nullish(),WebAppID:zod.z.string().nullish(),Units:zod.z.record(zod.z.string(),Uv).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),Iv).nullish(),Providers:zod.z.record(zod.z.string(),Lv).nullish(),RewardedVideo:vv.nullish(),Interstitial:Tv.nullish(),Banner:Av.nullish(),AppOpen:kv.nullish(),FrequencyCapping:zv.nullish(),PremiumAdReductions:zod.z.array(wv).nullish(),Consent:Mv.nullish(),Verification:Ov.nullish()}).passthrough();var Bv=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),Gv=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:c.nullish(),LastCompletedAt:c.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),Fv=zod.z.object({Date:c.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),Vv=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:c.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),_v=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:c.nullish(),ConsentRevokedAt:c.nullish()}).passthrough(),Nv=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:Ha.nullish(),IssuedAt:c.nullish(),ExpiresAt:c.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),jv=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:c.nullish()}).passthrough();zod.z.object({Credits:Bv.nullish(),Placements:zod.z.record(zod.z.string(),Gv).nullish(),Daily:Fv.nullish(),Session:Vv.nullish(),LastImpressionAt:c.nullish(),LastInterstitialAt:c.nullish(),LastRewardedAt:c.nullish(),LastAppOpenAt:c.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:c.nullish(),Consent:_v.nullish(),PendingRequests:zod.z.record(zod.z.string(),Nv).nullish(),FraudFlags:jv.nullish(),UpdatedAt:c.nullish()}).passthrough();var wm="idos_device_id",$r=class{storage;constructor(e=new si){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(wm);return e||(e="noop-device",this.storage.setString(wm,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};var $a={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},Wv=30*6e4,Kv=/^[a-z0-9]{8}-preview\.idos\.games$/,Ja="idos:platformSignIn:declined:";function Qv(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(Kv.test(window.location.hostname.toLowerCase()))return false;let r=window.location.ancestorOrigins?.[0];if(r&&!Pt.includes(r))try{let e=new URL(r).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}async function Hv(r){let e=await Ai($a.request,$a.response,{titleID:r},{answerTimeoutMs:Wv}),t=e.data.code;return e.ok&&typeof t=="string"&&t.length>0?{code:t}:{error:e.error??"no_code"}}function $v(r){try{window.localStorage.setItem(Ja+r,"1");}catch{}}function Jv(r){try{window.localStorage.removeItem(Ja+r);}catch{}}function Zv(r){try{return window.localStorage.getItem(Ja+r)==="1"}catch{return false}}
|
|
2
2
|
exports.AIAction=Ge;exports.AIErrorCode=oR;exports.AIGenerationStatus=Kt;exports.AIModality=qt;exports.AcquisitionCapture=_t;exports.AdProviderKind=Ev;exports.AdType=bv;exports.AnalyticsAction=Ra;exports.AnalyticsDropReason=Hx;exports.AnalyticsEventNaming=ya;exports.AnalyticsLimits=Ct;exports.AttackOutcome=bP;exports.AuthType=we;exports.AuthenticationAction=Ee;exports.AutomaticEvent=Gt;exports.BannerPosition=Dv;exports.BlockchainAction=Qe;exports.BlockchainNetworkType=sS;exports.BlockchainOperationCategory=yp;exports.BlockchainTransactionStatus=hS;exports.BlockchainTransactionType=aS;exports.BodyPart=FS;exports.BoostWindowKind=hP;exports.BrowserPlatformAdapter=ri;exports.BrowserStorage=ii;exports.CharacterAction=_e;exports.ChatAction=Ke;exports.ChatAuthorType=Jg;exports.ChatBlockedTermAction=Hg;exports.ChatChannelType=Ng;exports.ChatDirectAudience=Kg;exports.ChatPartitioning=jg;exports.ChatReportReason=Yg;exports.ClientPlatform=mt;exports.CloudCodeAction=ja;exports.CloudCodeErrorCode=DI;exports.CloudCodeLogLevel=xI;exports.CloudCodeRevisionSelection=SI;exports.CollectionAction=Ne;exports.CommissionSink=ox;exports.CommunityChestMemberStatus=sI;exports.CommunityChestStatus=iI;exports.CommunityCreatorStatus=SD;exports.CommunityMarketingAction=Jt;exports.CommunityMetricKind=bD;exports.CommunityParticipationMode=RD;exports.CommunityPayoutCurrencyKind=xD;exports.ConversionRateMode=KC;exports.CoopEventAction=ht;exports.CoopGroupStatus=RR;exports.CoopMemberStatus=CR;exports.CraftAction=Cr;exports.CraftInputSelectionMode=ED;exports.CraftOutputLevelMode=OD;exports.CraftOutputLevelOverflow=LD;exports.CraftType=MD;exports.CurrencyAction=vn;exports.CurrencyStatus=WC;exports.CurrencyType=ut;exports.CurveInterpolation=nf;exports.CurveShape=tf;exports.CustomDataBucket=Tt;exports.CustomDataValueType=qC;exports.CustomDataWriter=MC;exports.DEFAULT_BASE_URL=Ya;exports.DataAccessMode=vx;exports.DataCollectionKind=bx;exports.DataCollectionSchemaMode=Ux;exports.DataCollectionsAction=Nx;exports.DataCounterKind=zx;exports.DataFieldType=Px;exports.DataFieldVisibility=Ix;exports.DataOwnerDeletedPolicy=Mx;exports.DataRefKind=Ax;exports.DealComparisonOperator=LR;exports.DealNodeRuntimeStatus=kR;exports.DealNodeType=qR;exports.DealOfferAction=yt;exports.DealOfferActivationStatus=AR;exports.EVENT_NAME_PATTERN=Fn;exports.EnvelopeType=dI;exports.EventTokenType=_m;exports.ExperimentAction=xa;exports.ExperimentGoalKind=rb;exports.FRIENDS_FROM_PLATFORM=AC;exports.FodderSelectionMode=Rb;exports.FodderValuationMode=gb;exports.FriendActionStatus=fC;exports.FriendSource=gC;exports.GameLoopAction=qe;exports.IDosGamesClient=Hr;exports.IapProductType=wb;exports.IapPurchaseStatus=Wb;exports.IapStoreValues=Vm;exports.ItemAction=$n;exports.KycStatus=lS;exports.KycTier=cS;exports.LeaderboardAction=Ve;exports.LocalizationAction=Kn;exports.LocalizationMissingKeyMode=pb;exports.LootboxAction=nr;exports.MAILBOX_COUNTER_CAP=oC;exports.MailboxAction=et;exports.MailboxCategory=eC;exports.MailboxErrors=rC;exports.MailboxLetterSource=tC;exports.MailboxRewardModule=sC;exports.MarketGoodsType=Mn;exports.MarketOfferStatus=rx;exports.MarketOfferType=nx;exports.MarketplaceAction=ke;exports.MatchAction=Rt;exports.MatchStatus=VS;exports.MemoryStorage=si;exports.MultiplayerAction=He;exports.MultiplayerChatMode=cI;exports.MultiplayerTopology=uI;exports.NoopPlatformAdapter=$r;exports.OFFER_NOT_IN_ROTATION=Eg;exports.PLATFORM_BRIDGE_ACK=ru;exports.PLATFORM_ORIGINS=Pt;exports.PLATFORM_PAGE_UNAVAILABLE=ou;exports.PLATFORM_SIGN_IN_MESSAGES=$a;exports.PLATFORM_TOPUP_MESSAGES=mo;exports.PlatformFriendsMode=zC;exports.PlatformProfileMode=kC;exports.PlayAccessMode=xS;exports.PlayerExperimentStatus=lb;exports.PlaytimeTracker=Ii;exports.PremiumAction=Ht;exports.PurchaseAction=$t;exports.PushAction=gi;exports.PushPermissionState=It;exports.PushTopic=hy;exports.PushTransport=cy;exports.QuestAction=pt;exports.QuestObjectiveSource=ff;exports.QuestPrerequisiteMode=yf;exports.QuestStatus=hf;exports.RaidMode=SP;exports.ReferralAction=Zt;exports.ResourceEntryType=_i;exports.RewardAction=kt;exports.RoomVisibility=pI;exports.SKIN_ALREADY_OWNED=rR;exports.SKIN_SLOT=Oo;exports.ScheduleMode=Nm;exports.SeasonAction=Ut;exports.SocialAction=Ce;exports.SocialContentStatus=xC;exports.SocialEntityType=RC;exports.SocialInboxVerb=bC;exports.SocialReactionKind=CC;exports.SocialReportReason=SC;exports.SpecialChoiceMode=xP;exports.StoreAction=Wt;exports.StoreRotationMode=Rg;exports.StoreType=kb;exports.TimedBoostAction=Xt;exports.TimedBoostStackingPolicy=iP;exports.TimedEventAction=ot;exports.TitleAction=ei;exports.TitleCustomDataAction=Gi;exports.TitleDataBucket=fP;exports.TitleDataScope=mP;exports.TradeOfferStatus=ND;exports.TransactionDirection=dS;exports.TutorialAction=nt;exports.TutorialBoardAction=Mf;exports.TutorialFlowStatus=kf;exports.TutorialGateMode=$m;exports.TutorialRestartPolicy=Tf;exports.TutorialScriptModule=wf;exports.TutorialStepCompletionMode=If;exports.TypedEmitter=Pi;exports.UserAction=lt;exports.UserCustomDataAction=dt;exports.WalletGateBalanceSource=RS;exports.WalletLinkType=rS;exports.WorkshopAccessMode=TI;exports.WorkshopAccessVia=BI;exports.WorkshopAction=We;exports.WorkshopContentStatus=UI;exports.WorkshopHoldingMatch=zI;exports.WorkshopHoldingMode=AI;exports.WorkshopLicenseSource=qI;exports.WorkshopSort=LI;exports.WorkshopVisibility=MI;exports.askPlatformPage=Ai;exports.authErrorText=fv;exports.beginSsoRedirect=av;exports.canUsePlatformSignIn=Qv;exports.canUsePlatformTopUp=fo;exports.claimedMilestoneIDs=yv;exports.clearPlatformSignInDeclined=Jv;exports.createIDosGamesClient=tv;exports.cryptoShortfallFromError=pi;exports.curveMultiplier=Cv;exports.defineView=tg;exports.describeUserAgent=Rh;exports.evaluateCurve=km;exports.grantedPremiumTiers=Rv;exports.isAIGenerationTerminal=zi;exports.isCurveConfigured=Sv;exports.isFail=Wm;exports.isMilestoneClaimed=gv;exports.isOk=jm;exports.isPlatformParentOrigin=bs;exports.isPlatformSignInDeclined=Zv;exports.isReservedSlot=Hy;exports.isSsoAvailable=rv;exports.markPlatformSignInDeclined=$v;exports.normalizeBlockchainCategory=An;exports.parseAIErrorCode=aR;exports.readSsoCodeFromUrl=ov;exports.requestPlatformSignIn=Hv;exports.requestPlatformTopUp=go;exports.roundAmount=xv;exports.where=Wx;exports.zPaymentProof=fg;exports.zPriceOption=Hl;exports.zPriceOptions=ue;
|