@modrinth/api-client 0.92.0 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -3968,6 +3968,13 @@ export declare namespace Labrinth {
3968
3968
  reason: string;
3969
3969
  created: string;
3970
3970
  };
3971
+ export type UserRestriction = {
3972
+ removed_perms: number;
3973
+ reason: string | null;
3974
+ private_reason?: string;
3975
+ restricted_by?: string;
3976
+ updated: string;
3977
+ };
3971
3978
  }
3972
3979
  export namespace v2 {
3973
3980
  export type Role = Common.Role;
@@ -4086,6 +4093,7 @@ export declare namespace Labrinth {
4086
4093
  allow_friend_requests?: boolean;
4087
4094
  moderation_notes?: Common.ModerationNote | null;
4088
4095
  lock?: Common.UserLock;
4096
+ restriction?: Common.UserRestriction;
4089
4097
  github_id?: number;
4090
4098
  discord_id?: string;
4091
4099
  steam_id?: string;
@@ -4685,6 +4693,11 @@ export declare namespace Labrinth {
4685
4693
  };
4686
4694
  export type ProjectJudgement = FlameJudgement | UnknownJudgement;
4687
4695
  export type ProjectJudgements = Record<string, ProjectJudgement>;
4696
+ export type RestrictUserRequest = {
4697
+ removed_perms: number;
4698
+ reason?: string | null;
4699
+ private_reason?: string | null;
4700
+ };
4688
4701
  }
4689
4702
  }
4690
4703
  export namespace Notifications {
@@ -5726,6 +5739,8 @@ declare class LabrinthModerationInternalModule extends AbstractModule {
5726
5739
  checkLock(projectId: string): Promise<Labrinth.Moderation.Internal.LockStatusResponse>;
5727
5740
  lockUser(userId: string, reason: string): Promise<void>;
5728
5741
  unlockUser(userId: string): Promise<void>;
5742
+ setUserRestrictions(userId: string, restriction: Labrinth.Moderation.Internal.RestrictUserRequest): Promise<void>;
5743
+ clearUserRestrictions(userId: string): Promise<void>;
5729
5744
  revokeUserSessions(userId: string): Promise<void>;
5730
5745
  forceUserPasswordReset(userId: string, email?: string): Promise<void>;
5731
5746
  resetUser2fa(userId: string): Promise<void>;
package/dist/index.js CHANGED
@@ -2,9 +2,9 @@ var o=class{constructor(e){this.client=e}};var U=class extends o{getModuleID(){r
2
2
  `).filter(n=>n.trim()!=="");if(e.length===0)return[];let t=e[0],r=(t.startsWith("#")?t.slice(1):t).split(",");return e.slice(1).map(n=>{let s=n.split(","),a={};return r.forEach((l,c)=>{a[l]=s[c]||""}),a})}var Q=class extends o{getModuleID(){return"iso3166_data"}async build(){try{let[e,t]=await Promise.all([pt(`${dt}/countries.csv`,{responseType:"text"}),pt(`${dt}/subdivisions.csv`,{responseType:"text"})]),r=ht(e),n=ht(t),s=r.map(l=>({alpha2:l.country_code_alpha2,alpha3:l.country_code_alpha3,numeric:l.numeric_code,nameShort:l.name_short,nameLong:l.name_long})),a=n.reduce((l,c)=>{let p=c.country_code_alpha2;return!p||typeof p!="string"||p.trim()===""||(l[p]||(l[p]=[]),l[p].push({code:c["subdivision_code_iso3166-2"],name:c.subdivision_name,localVariant:c.localVariant||null,category:c.category,parent:c.parent_subdivision||null,language:c.language_code})),l},{});return{countries:s,subdivisions:a}}catch(e){return console.error("Error fetching ISO3166 data:",e),{countries:[],subdivisions:{}}}}};var X=class extends o{getModuleID(){return"kyros_content_v1"}uploadAddonFile(e,t,r){let n=new FormData;for(let s of t)n.append("file",s,s instanceof File?s.name:"file");return this.client.upload(`/worlds/${e}/content/upload-addon-file`,{api:"",version:"v1",formData:n,onProgress:r?.onProgress,useNodeAuth:!0})}uploadModpackFile(e,t,r,n){let s=new FormData;return s.append("file",t,t instanceof File?t.name:"file"),s.append("properties",JSON.stringify(r)),this.client.upload(`/worlds/${e}/content/upload-modpack-file`,{api:"",version:"v1",formData:s,params:n?.softOverride!==void 0?{soft_override:String(n.softOverride)}:void 0,onProgress:n?.onProgress,useNodeAuth:!0})}};var wt=/\/modrinth\/v\d+\/fs\/?$/,Lt=/^https?:\/\//i,qt=/^wss?:\/\//i,mt=/^https:\/\//i,gt=/^http:\/\//i;function P(i){let e=i.replace(wt,"");return Lt.test(e)?e:`https://${e}`}function Ye(i){return qt.test(i)?i:mt.test(i)?i.replace(mt,"wss://"):gt.test(i)?i.replace(gt,"ws://"):`wss://${i}`}var Y=class extends o{getModuleID(){return"kyros_files_v0"}getNodeBaseUrl(e){return P(e.url)}async listDirectory(e,t=1,r=100){return this.client.request("/fs/list",{api:"",version:"modrinth/v0",method:"GET",params:{path:e,page:t,page_size:r},useNodeAuth:!0})}async createFileOrFolder(e,t){return this.client.request("/fs/create",{api:"",version:"modrinth/v0",method:"POST",params:{path:e,type:t},headers:{"Content-Type":"application/octet-stream"},useNodeAuth:!0})}async downloadFile(e){return this.client.request("/fs/download",{api:"",version:"modrinth/v0",method:"GET",params:{path:e},useNodeAuth:!0})}async downloadFileWithAuth(e,t){return this.client.request("/fs/download",{api:this.getNodeBaseUrl(e),version:"modrinth/v0",method:"GET",params:{path:t},headers:{Authorization:`Bearer ${e.token}`},skipAuth:!0})}uploadFile(e,t,r){return this.client.upload("/fs/create",{api:"",version:"modrinth/v0",file:t,params:{path:e,type:"file"},onProgress:r?.onProgress,retry:r?.retry,useNodeAuth:!0})}uploadFileWithAuth(e,t,r,n){return this.client.upload("/fs/create",{api:this.getNodeBaseUrl(e),version:"modrinth/v0",file:r,params:{path:t,type:"file"},headers:{Authorization:`Bearer ${e.token}`},onProgress:n?.onProgress,retry:n?.retry,skipAuth:!0})}async updateFile(e,t){let r=typeof t=="string"?new Blob([t]):t;return this.client.request("/fs/update",{api:"",version:"modrinth/v0",method:"PUT",params:{path:e},body:r,headers:{"Content-Type":"application/octet-stream"},useNodeAuth:!0})}async moveFileOrFolder(e,t){return this.client.request("/fs/move",{api:"",version:"modrinth/v0",method:"POST",body:{source:e,destination:t},useNodeAuth:!0})}async renameFileOrFolder(e,t){let r=e.split("/").slice(0,-1).join("/")+"/"+t;return this.moveFileOrFolder(e,r)}async deleteFileOrFolder(e,t){return this.client.request("/fs/delete",{api:"",version:"modrinth/v0",method:"DELETE",params:{path:e,recursive:t},useNodeAuth:!0})}async deleteFileOrFolderWithAuth(e,t,r){return this.client.request("/fs/delete",{api:this.getNodeBaseUrl(e),version:"modrinth/v0",method:"DELETE",params:{path:t,recursive:r},headers:{Authorization:`Bearer ${e.token}`},skipAuth:!0})}async extractFile(e,t=!0,r=!1,n="/"){return this.client.request("/fs/unarchive",{api:"",version:"v1",method:"POST",params:{src:e,trg:n,override:t,dry:r},useNodeAuth:!0})}async modifyOperation(e,t){return this.client.request(`/fs/ops/${t}`,{api:"",version:"v1",method:"POST",params:{id:e},useNodeAuth:!0})}};var Z=class extends o{getModuleID(){return"kyros_files_v1"}async authorizeFileDownload(e,t,r){return this.client.request(`/worlds/${t}/files/contents-raw/authorize`,{api:P(e),version:"v1",method:"GET",params:{path:r}})}getFileDownloadUrl(e,t,r){let n=new URL(`/v1/worlds/${t}/files/contents-raw`,P(e));return n.searchParams.set("token",r),n.toString()}async authorizeFullWorldDownload(e,t){return this.client.request(`/worlds/${t}/files/download-full-zip/authorize`,{api:P(e),version:"v1",method:"GET"})}getFullWorldDownloadUrl(e,t,r){let n=new URL(`/v1/worlds/${t}/files/download-full-zip`,P(e));return n.searchParams.set("token",r),n.toString()}async stat(e,t){return this.client.request(`/worlds/${e}/files/stat`,{api:"",version:"v1",method:"POST",body:t,useNodeAuth:!0})}async createZip(e,t,r){let s=(await this.client.stream(`/worlds/${e}/files/zip`,{api:"",version:"v1",method:"POST",body:t,useNodeAuth:!0,headers:{Accept:"application/json-seq"}})).getReader(),a=new TextDecoder,l="",c=!1,p=d=>{let m=d.trim(),b=m.startsWith("")?m.slice(1).trim():m;if(!b)return;let v=JSON.parse(b);if(r?.(v),v.error)throw new Error(v.error);v.done===!0&&(c=!0)},u=(d=!1)=>{let m=l.indexOf(`
3
3
  `);for(;m!==-1;)p(l.slice(0,m)),l=l.slice(m+1),m=l.indexOf(`
4
4
  `);d&&l.trim()&&(p(l),l="")};try{for(;!c;){let{done:d,value:m}=await s.read();if(d)break;l+=a.decode(m,{stream:!0}),u()}if(c){await s.cancel().catch(()=>{});return}if(l+=a.decode(),u(!0),!c)throw new Error("ZIP operation ended before completion")}finally{s.releaseLock()}}};var ee=class extends o{getModuleID(){return"kyros_logs_v1"}async clear(){return this.client.request("/logs/clear",{api:"",version:"v1",method:"POST",useNodeAuth:!0})}};function w(i,e){return`/worlds/${e}/${i}/upload-session`}var te=class extends o{getModuleID(){return"kyros_upload_sessions_v1"}async create(e,t){return this.client.request(w(e,t),{api:"",version:"v1",method:"POST",useNodeAuth:!0})}async get(e,t){return this.client.request(w(e,t),{api:"",version:"v1",method:"GET",useNodeAuth:!0})}uploadFiles(e,t,r,n,s){let a=new FormData;for(let{file:l,filename:c}of n)a.append("file",l,c);return this.client.upload(`${w(e,t)}/${r}/files`,{api:"",version:"v1",formData:a,onProgress:s?.onProgress,retry:s?.retry,useNodeAuth:!0})}async finalize(e,t,r){return this.client.request(`${w(e,t)}/${r}/finalize`,{api:"",version:"v1",method:"POST",useNodeAuth:!0})}async cancel(e,t,r){return this.client.request(`${w(e,t)}/${r}`,{api:"",version:"v1",method:"DELETE",useNodeAuth:!0})}};var re=class extends o{getModuleID(){return"labrinth_analytics_internal"}async createEvent(e){return this.client.request("/analytics-event",{api:"labrinth",version:"internal",method:"POST",body:e})}async editEvent(e,t){return this.client.request(`/analytics-event/${e}`,{api:"labrinth",version:"internal",method:"PATCH",body:t})}async deleteEvent(e){return this.client.request(`/analytics-event/${e}`,{api:"labrinth",version:"internal",method:"DELETE"})}};var ne=class extends o{getModuleID(){return"labrinth_analytics_v3"}async fetch(e){return this.client.request("/analytics",{api:"labrinth",version:3,method:"POST",body:e,timeout:100*1e3})}async fetchFacets(e){return this.client.request("/analytics/facets",{api:"labrinth",version:3,method:"POST",body:e,timeout:100*1e3})}async getEvents(){return this.client.request("/analytics-event",{api:"labrinth",version:3,method:"GET"})}};var Ct="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function bt(i){let e=0;for(let t of i){let r=Ct.indexOf(t);if(r<0)throw new Error(`Invalid base62 character "${t}" in id "${i}"`);if(e=e*62+r,!Number.isSafeInteger(e))throw new Error(`Base62 id "${i}" exceeds safe integer range`)}return e}var ie=class extends o{getModuleID(){return"labrinth_attribution_internal"}async listProjectAttribution(e){return this.client.request(`/attribution/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async updateGroup(e,t){let r=bt(e);return this.client.request(`/attribution/group/${r}`,{api:"labrinth",version:"internal",method:"PATCH",body:t})}async deleteGroups(e){let t={groups:e};return this.client.request("/attribution/group",{api:"labrinth",version:"internal",method:"DELETE",body:t})}async deleteAllGroups(e){let t={project_id:e};return this.client.request("/attribution/all-groups",{api:"labrinth",version:"internal",method:"DELETE",body:t})}async assignFileToGroup(e){let t={sha1:e.sha1,target_group_id:bt(e.target_group_id),project_id:e.project_id};return this.client.request("/attribution/assign",{api:"labrinth",version:"internal",method:"POST",body:t})}async splitFile(e){return this.client.request("/attribution/split",{api:"labrinth",version:"internal",method:"POST",body:e})}async scanFile(e){return this.client.request(`/attribution/file/${e}/scan`,{api:"labrinth",version:"internal",method:"POST"})}};var se=class extends o{getModuleID(){return"labrinth_auth_internal"}async getNewsletterStatus(){return this.client.request("/auth/email/subscribe",{api:"labrinth",version:"internal",method:"GET"})}async subscribeNewsletter(){return this.client.request("/auth/email/subscribe",{api:"labrinth",version:"internal",method:"POST"})}async createDiscordCommunityLink(){return this.client.request("/auth/discord-community-link",{api:"labrinth",version:"internal",method:"POST"})}};var oe=class extends o{getModuleID(){return"labrinth_auth_v2"}async login(e){return this.client.request("/auth/login",{api:"labrinth",version:2,method:"POST",body:e})}async login2FA(e){return this.client.request("/auth/login/2fa",{api:"labrinth",version:2,method:"POST",body:e})}async createAccount(e){return this.client.request("/auth/create",{api:"labrinth",version:2,method:"POST",body:e})}async validateCreateAccount(e){return this.client.request("/auth/create/validate",{api:"labrinth",version:2,method:"POST",body:e})}async createOAuthAccount(e){return this.client.request("/auth/create/oauth",{api:"labrinth",version:2,method:"POST",body:e})}async resetPasswordBegin(e){return this.client.request("/auth/password/reset",{api:"labrinth",version:2,method:"POST",body:e})}async changePassword(e){return this.client.request("/auth/password",{api:"labrinth",version:2,method:"PATCH",body:e})}async listPasskeys(){return this.client.request("/auth/passkey",{api:"labrinth",version:2,method:"GET"})}async registerPasskeyStart(){return this.client.request("/auth/passkey/register/start",{api:"labrinth",version:2,method:"POST"})}async registerPasskeyFinish(e){return this.client.request("/auth/passkey/register/finish",{api:"labrinth",version:2,method:"POST",body:e})}async authenticatePasskeyStart(){return this.client.request("/auth/passkey/start",{api:"labrinth",version:2,method:"POST",skipAuth:!0})}async authenticatePasskeyFinish(e){return this.client.request("/auth/passkey/finish",{api:"labrinth",version:2,method:"POST",body:e,skipAuth:!0})}async renamePasskey(e,t){return this.client.request(`/auth/passkey/${e}`,{api:"labrinth",version:2,method:"PATCH",body:t})}async deletePasskey(e){return this.client.request(`/auth/passkey/${e}`,{api:"labrinth",version:2,method:"DELETE"})}};var ae=class extends o{getModuleID(){return"labrinth_billing_internal"}async getSubscriptions(e){let t=e?`?user_id=${e}`:"";return this.client.request(`/billing/subscriptions${t}`,{api:"labrinth",version:"internal",method:"GET"})}async getProducts(){return this.client.request("/billing/products",{api:"labrinth",version:"internal",method:"GET"})}async getCustomer(){return this.client.request("/billing/customer",{api:"labrinth",version:"internal",method:"GET"})}async editSubscription(e,t,r){let n=r?"?dry=true":"";return this.client.request(`/billing/subscription/${e}${n}`,{api:"labrinth",version:"internal",method:"PATCH",body:t})}async getPaymentMethods(){return this.client.request("/billing/payment_methods",{api:"labrinth",version:"internal",method:"GET"})}async addPaymentMethodFlow(){return this.client.request("/billing/payment_method",{api:"labrinth",version:"internal",method:"POST"})}async editPaymentMethod(e,t){return this.client.request(`/billing/payment_method/${e}`,{api:"labrinth",version:"internal",method:"PATCH",body:t})}async removePaymentMethod(e){return this.client.request(`/billing/payment_method/${e}`,{api:"labrinth",version:"internal",method:"DELETE"})}async getPayments(e){let t=e?`?user_id=${e}`:"";return this.client.request(`/billing/payments${t}`,{api:"labrinth",version:"internal",method:"GET"})}async initiatePayment(e){return this.client.request("/billing/payment",{api:"labrinth",version:"internal",method:"POST",body:e})}async refundCharge(e,t){return this.client.request(`/billing/charge/${e}/refund`,{api:"labrinth",version:"internal",method:"POST",body:t})}async credit(e){return this.client.request("/billing/credit",{api:"labrinth",version:"internal",method:"POST",body:e})}};var le=class extends o{getModuleID(){return"labrinth_collections"}async get(e){return this.client.request(`/collection/${e}`,{api:"labrinth",version:3,method:"GET"})}async getMultiple(e){return this.client.request("/collections",{api:"labrinth",version:3,method:"GET",params:{ids:JSON.stringify(e)}})}async edit(e,t){return this.client.request(`/collection/${e}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async delete(e){return this.client.request(`/collection/${e}`,{api:"labrinth",version:3,method:"DELETE"})}async editIcon(e,t,r){return this.client.request(`/collection/${e}/icon?ext=${r}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async deleteIcon(e){return this.client.request(`/collection/${e}/icon`,{api:"labrinth",version:3,method:"DELETE"})}};var ce=class extends o{getModuleID(){return"labrinth_content_v3"}async resolve(e){return this.client.request("/content/resolve",{api:"labrinth",version:3,method:"POST",body:e})}};var ue=class extends o{getModuleID(){return"labrinth_external_projects_internal"}async search(e){return this.client.request("/moderation/external-license/search",{api:"labrinth",version:"internal",method:"POST",body:e})}async getBySha1(e){return this.client.request(`/moderation/external-license/by-sha1/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async update(e,t){return this.client.request(`/moderation/external-license/${e}`,{api:"labrinth",version:"internal",method:"PATCH",body:t})}async addFile(e){return this.client.request("/moderation/external-license/file",{api:"labrinth",version:"internal",method:"POST",body:e})}};var pe=class extends o{getModuleID(){return"labrinth_friends_v3"}async list(){return this.client.request("/friends",{api:"labrinth",version:3,method:"GET"})}async add(e){return this.client.request(`/friend/${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"POST"})}async remove(e){return this.client.request(`/friend/${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"DELETE"})}};var de=class extends o{getModuleID(){return"labrinth_geoip"}async getCountry(){let t=(await this.client.request("/trace",{api:"https://api.modrinth.com",version:"cdn-cgi",method:"GET",skipAuth:!0})).split(`
5
- `).find(r=>r.startsWith("loc="))?.slice(4).toUpperCase();return t?.match(/^[A-Z]{2}$/)?t:void 0}};var he=class extends o{getModuleID(){return"labrinth_globals_internal"}async get(){return this.client.request("/globals",{api:"labrinth",version:"internal",method:"GET",skipAuth:!0})}};function It(i,e){let t={ext:i,context:e.context};switch(e.context){case"project":t.project_id=e.project_id;break;case"version":t.version_id=e.version_id;break;case"thread_message":t.thread_message_id=e.thread_message_id;break;case"report":e.report_id&&(t.report_id=e.report_id);break}return t}var me=class extends o{getModuleID(){return"labrinth_images_v3"}uploadImage(e,t,r){return this.client.upload("/image",{api:"labrinth",version:3,file:e,params:It(t,r)})}};var ge=class extends o{getModuleID(){return"labrinth_limits_v3"}async getProjectLimits(){return this.client.request("/limits/projects",{api:"labrinth",version:3,method:"GET"})}async getOrganizationLimits(){return this.client.request("/limits/organizations",{api:"labrinth",version:3,method:"GET"})}async getCollectionLimits(){return this.client.request("/limits/collections",{api:"labrinth",version:3,method:"GET"})}};var be=class extends o{getModuleID(){return"labrinth_moderation_internal"}async getProjects(e={}){return this.client.request("/moderation/projects",{api:"labrinth",version:"internal",method:"GET",params:e,timeout:20*1e3})}async getProjectIds(e={}){return this.client.request("/moderation/projects/ids",{api:"labrinth",version:"internal",method:"GET",params:e})}async acquireLock(e){return this.client.request(`/moderation/lock/${e}`,{api:"labrinth",version:"internal",method:"POST"})}async overrideLock(e){return this.client.request(`/moderation/lock/${e}/override`,{api:"labrinth",version:"internal",method:"POST"})}async releaseLock(e,t){return this.client.request(`/moderation/lock/${e}`,{api:"labrinth",version:"internal",method:"DELETE",headers:t?{Authorization:`Bearer ${t}`}:void 0})}async checkLock(e){return this.client.request(`/moderation/lock/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async lockUser(e,t){return this.client.request(`/admin/user/${e}/lock`,{api:"labrinth",version:"internal",method:"PUT",body:{reason:t}})}async unlockUser(e){return this.client.request(`/admin/user/${e}/lock`,{api:"labrinth",version:"internal",method:"DELETE"})}async revokeUserSessions(e){return this.client.request(`/admin/user/${e}/sessions`,{api:"labrinth",version:"internal",method:"DELETE"})}async forceUserPasswordReset(e,t){return this.client.request(`/admin/user/${e}/password-reset`,{api:"labrinth",version:"internal",method:"POST",body:{email:t}})}async resetUser2fa(e){return this.client.request(`/admin/user/${e}/2fa`,{api:"labrinth",version:"internal",method:"DELETE"})}async setProjectJudgements(e){return this.client.request("/moderation/project",{api:"labrinth",version:"internal",method:"POST",body:e})}};var ve=class extends o{getModuleID(){return"labrinth_notifications_v2"}async getUserNotifications(e){return this.client.request(`/user/${e}/notifications`,{api:"labrinth",version:2,method:"GET"})}async getMultiple(e){return this.client.request(`/notifications?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:2,method:"GET"})}async markAsRead(e){return this.client.request(`/notification/${e}`,{api:"labrinth",version:2,method:"PATCH"})}async markMultipleAsRead(e){return this.client.request("/notifications",{api:"labrinth",version:2,method:"PATCH",params:{ids:JSON.stringify([...new Set(e)])}})}async delete(e){return this.client.request(`/notification/${e}`,{api:"labrinth",version:2,method:"DELETE"})}async deleteMultiple(e){return this.client.request("/notifications",{api:"labrinth",version:2,method:"DELETE",params:{ids:JSON.stringify([...new Set(e)])}})}};var ye=class extends o{getModuleID(){return"labrinth_oauth_internal"}async getUserApps(e){return this.client.request(`/user/${e}/oauth_apps`,{api:"labrinth",version:3,method:"GET"})}async getApp(e){return this.client.request(`/oauth/app/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async getApps(e){return e.length===0?[]:(await Promise.all(e.map(r=>this.getApp(r).catch(()=>null)))).filter(r=>r!==null)}async createApp(e){return this.client.request("/oauth/app",{api:"labrinth",version:"internal",method:"POST",body:e})}async editApp(e,t){return this.client.request(`/oauth/app/${e}`,{api:"labrinth",version:"internal",method:"PATCH",body:t})}async deleteApp(e){return this.client.request(`/oauth/app/${e}`,{api:"labrinth",version:"internal",method:"DELETE"})}async uploadAppIcon(e,t,r){return this.client.request(`/oauth/app/${e}/icon`,{api:"labrinth",version:"internal",method:"PATCH",params:{ext:r},body:t})}async getAuthorizations(){return this.client.request("/oauth/authorizations",{api:"labrinth",version:"internal",method:"GET"})}async revokeAuthorization(e){return this.client.request("/oauth/authorizations",{api:"labrinth",version:"internal",method:"DELETE",params:{client_id:e}})}async authorize(e){return this.client.request("/oauth/authorize",{api:"labrinth",version:"internal",method:"GET",params:e})}async accept(e){return this.client.request("/oauth/accept",{api:"labrinth",version:"internal",method:"POST",body:e})}async reject(e){return this.client.request("/oauth/reject",{api:"labrinth",version:"internal",method:"POST",body:e})}};var fe=class extends o{getModuleID(){return"labrinth_organizations_v3"}async get(e){return this.client.request(`/organization/${e}`,{api:"labrinth",version:3,method:"GET"})}async getProjects(e){return this.client.request(`/organization/${e}/projects`,{api:"labrinth",version:3,method:"GET"})}async getMultiple(e){return this.client.request(`/organizations?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:3,method:"GET"})}async addProject(e,t){return this.client.request(`/organization/${e}/projects`,{api:"labrinth",version:3,method:"POST",body:t})}async removeProject(e,t,r){return this.client.request(`/organization/${e}/projects/${t}`,{api:"labrinth",version:3,method:"DELETE",body:r})}};var Pe=class extends o{getModuleID(){return"labrinth_pats_v2"}async list(){return this.client.request("/pat",{api:"labrinth",version:2,method:"GET"})}async create(e){return this.client.request("/pat",{api:"labrinth",version:2,method:"POST",body:e})}async modify(e,t){return this.client.request(`/pat/${e}`,{api:"labrinth",version:2,method:"PATCH",body:t})}async delete(e){return this.client.request(`/pat/${e}`,{api:"labrinth",version:2,method:"DELETE"})}};var Se=class extends o{getModuleID(){return"labrinth_payout_v3"}async getBalance(){let e=await this.client.request("/payout/balance",{api:"labrinth",version:3,method:"GET"});return{...e,available:Number(e.available),withdrawn_lifetime:Number(e.withdrawn_lifetime),withdrawn_ytd:Number(e.withdrawn_ytd),pending:Number(e.pending),dates:Object.fromEntries(Object.entries(e.dates).map(([t,r])=>[t,Number(r)]))}}async getHistory(){return(await this.client.request("/payout/history",{api:"labrinth",version:3,method:"GET"})).map(t=>t.type==="withdrawal"?{...t,amount:Number(t.amount),fee:t.fee===null?null:Number(t.fee)}:{...t,amount:Number(t.amount)})}async getMethods(e){return this.client.request("/payout/methods",{api:"labrinth",version:3,method:"GET",params:e?{country:e}:void 0})}async cancel(e){return this.client.request(`/payout/${e}`,{api:"labrinth",version:3,method:"DELETE"})}};var Ae=class extends o{getModuleID(){return"labrinth_payouts_v3"}async getPlatformRevenue(e){return this.client.request("/payout/platform_revenue",{api:"labrinth",version:3,method:"GET",params:e})}};var _e=class extends o{getModuleID(){return"labrinth_projects_v2"}async get(e){return this.client.request(`/project/${e}`,{api:"labrinth",version:2,method:"GET"})}async check(e){let t=encodeURIComponent(e);return this.client.request(`/project/${t}/check`,{api:"labrinth",version:2,method:"GET"})}async getMultiple(e){return this.client.request("/projects",{api:"labrinth",version:2,method:"GET",params:{ids:JSON.stringify(e)}})}async search(e){return this.client.request("/search",{api:"labrinth",version:2,method:"GET",params:{...e,facets:e.facets?JSON.stringify(e.facets):void 0,new_filters:e.new_filters??void 0}})}async edit(e,t){return this.client.request(`/project/${e}`,{api:"labrinth",version:2,method:"PATCH",body:t})}async delete(e){return this.client.request(`/project/${e}`,{api:"labrinth",version:2,method:"DELETE"})}async getDependencies(e){return this.client.request(`/project/${e}/dependencies`,{api:"labrinth",version:2,method:"GET"})}async createGalleryImage(e,t,r){let n={ext:r.ext,featured:String(r.featured)};return r.title&&(n.title=r.title),r.description&&(n.description=r.description),r.ordering!==void 0&&(n.ordering=String(r.ordering)),this.client.request(`/project/${e}/gallery`,{api:"labrinth",version:2,method:"POST",params:n,body:t})}async editGalleryImage(e,t,r){let n={url:t,featured:String(r.featured)};return r.title&&(n.title=r.title),r.description&&(n.description=r.description),r.ordering!==void 0&&(n.ordering=String(r.ordering)),this.client.request(`/project/${e}/gallery`,{api:"labrinth",version:2,method:"PATCH",params:n})}async deleteGalleryImage(e,t){return this.client.request(`/project/${e}/gallery`,{api:"labrinth",version:2,method:"DELETE",params:{url:t}})}async getRandom(e){return this.client.request("/projects_random",{api:"labrinth",version:2,method:"GET",params:{count:String(e)}})}async bulkEdit(e,t){return this.client.request("/projects",{api:"labrinth",version:2,method:"PATCH",params:{ids:JSON.stringify(e)},body:t})}};function Ze(i){if(typeof i!="object"||i===null)return!1;let e=i;return typeof e.error=="string"&&typeof e.description=="string"}var g=class i extends Error{constructor(e,t){super(e),this.name="ModrinthApiError",this.statusCode=t?.statusCode,this.originalError=t?.originalError,this.responseData=t?.responseData,this.context=t?.context,Error.captureStackTrace&&Error.captureStackTrace(this,i)}static fromUnknown(e,t){return e instanceof i?e:e instanceof Error?new i(e.message,{originalError:e,context:t}):new i(String(e),{context:t})}},L=class i extends g{constructor(e,t){let r=t?.v1Error?Mt(t.v1Error):e;super(r,t),this.name="ModrinthServerError",this.v1Error=t?.v1Error,Error.captureStackTrace&&Error.captureStackTrace(this,i)}static fromResponse(e,t,r){let n=Ze(t)?t:void 0,s=typeof t=="string"&&/<!doctype html|<html/i.test(t),a=typeof t=="string"&&!s?t:`HTTP ${e}`;return new i(a,{statusCode:e,responseData:s?void 0:t,context:r,v1Error:n})}static fromUnknown(e,t){return e instanceof i?e:e instanceof g?new i(e.message,{statusCode:e.statusCode,originalError:e.originalError,responseData:e.responseData,context:t??e.context}):e instanceof Error?new i(e.message,{originalError:e,context:t}):new i(String(e),{context:t})}};function Mt(i){return Ot(i.details)??i.description}function Ot(i){if(typeof i=="string")return i.trim()||void 0;if(Array.isArray(i))return i.findLast(e=>typeof e!="string"?!1:!!e.trim())?.trim()}var Ee=class extends o{getModuleID(){return"labrinth_projects_v3"}async get(e){return this.client.request(`/project/${e}`,{api:"labrinth",version:3,method:"GET"})}async validate(e){return this.client.request(`/project/${e}/validate`,{api:"labrinth",version:3,method:"GET"})}async getDependencies(e){return this.client.request(`/project/${e}/dependencies`,{api:"labrinth",version:3,method:"GET"})}async getMultiple(e){return this.client.request("/projects",{api:"labrinth",version:3,method:"GET",params:{ids:JSON.stringify(e)}})}async search(e,t){return this.client.request("/search",{api:"labrinth",version:3,method:"GET",headers:t?.headers,params:{...e,facets:e.facets?JSON.stringify(e.facets):void 0}})}async edit(e,t){return this.client.request(`/project/${e}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async getOrganization(e){try{return await this.client.request(`/project/${e}/organization`,{api:"labrinth",version:3,method:"GET"})}catch(t){if(t instanceof g&&t.statusCode===404)return null;throw t}}async getMembers(e){return this.client.request(`/project/${e}/members`,{api:"labrinth",version:3,method:"GET"})}async createServerProject(e){return this.client.request("/project",{api:"labrinth",version:3,method:"PUT",body:e})}async deleteProject(e){return this.client.request(`/project/${e}`,{api:"labrinth",version:3,method:"DELETE"})}async changeIcon(e,t,r){return this.client.request(`/project/${e}/icon`,{api:"labrinth",version:3,method:"PATCH",params:{ext:r},body:t})}async deleteIcon(e){return this.client.request(`/project/${e}/icon`,{api:"labrinth",version:3,method:"DELETE"})}async createGalleryImage(e,t,r){let n={ext:r.ext,featured:String(r.featured)};return r.name&&(n.name=r.name),r.description&&(n.description=r.description),r.ordering!==void 0&&(n.ordering=String(r.ordering)),this.client.request(`/project/${e}/gallery`,{api:"labrinth",version:3,method:"POST",params:n,body:t})}async deleteGalleryImage(e){return this.client.request("/project-gallery",{api:"labrinth",version:3,method:"DELETE",params:{url:e}})}async getDisclosures(e){return this.client.request(`/project/${e}/disclosures`,{api:"labrinth",version:3,method:"GET"})}async modifyDisclosures(e,t){return this.client.request(`/project/${e}/disclosures`,{api:"labrinth",version:3,method:"PATCH",body:t})}};var Re=class extends o{getModuleID(){return"labrinth_reports_v3"}async get(e){return this.client.request(`/report/${e}`,{api:"labrinth",version:3,method:"GET"})}async list(e){let t={};return e?.count!=null&&(t.count=String(e.count)),e?.offset!=null&&(t.offset=String(e.offset)),e?.all!=null&&(t.all=String(e.all)),this.client.request("/report",{api:"labrinth",version:3,method:"GET",params:Object.keys(t).length>0?t:void 0})}async getMultiple(e){return this.client.request(`/reports?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:3,method:"GET"})}async create(e){return this.client.request("/report",{api:"labrinth",version:3,method:"POST",body:e})}async edit(e,t){return this.client.request(`/report/${e}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async delete(e){return this.client.request(`/report/${e}`,{api:"labrinth",version:3,method:"DELETE"})}};var Te=class extends o{getModuleID(){return"labrinth_server_ping_internal"}async pingMinecraftJava(e){return this.client.request("/server-ping/minecraft-java",{api:"labrinth",version:"internal",method:"POST",body:e})}};var ke=class extends o{getModuleID(){return"labrinth_sessions_v2"}async list(){return this.client.request("/session/list",{api:"labrinth",version:2,method:"GET"})}async delete(e){return this.client.request(`/session/${e}`,{api:"labrinth",version:2,method:"DELETE"})}};var vt="YV97U1kk",yt="M4c3ITvd",$t=60;function Ut(i,e){let t=i.slice();for(let r=t.length-1;r>0;r--){let n=Math.floor(Math.random()*(r+1)),s=t[r];t[r]=t[n],t[n]=s}return t.slice(0,e)}var xe=class extends o{getModuleID(){return"labrinth_state"}async fetchHomePageProjects(){let e=await this.client.labrinth.collections.get(vt),t=Ut(e.projects??[],$t);return t.length===0?[]:this.client.labrinth.projects_v2.getMultiple(t)}async build(){let e=[],t=(h,kt,xt)=>(console.error("Error fetching state data:",h),e.push({endpoint:xt,error:h}),kt),[r,n,s,a,l,c,p,u,d,m,b,v,y,x]=await Promise.all([this.client.request("/tag/category",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/category")),this.client.request("/tag/loader",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/loader")),this.client.request("/tag/game_version",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/game_version")),this.client.request("/tag/donation_platform",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/donation_platform")),this.client.request("/tag/report_type",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/report_type")),this.fetchHomePageProjects().catch(h=>t(h,[],`/v3/collection/${vt}`)),this.client.request("/search",{api:"labrinth",version:2,method:"GET",params:{limit:"3",query:"leave",index:"relevance"}}).catch(h=>t(h,{},"/v2/search")),this.client.request("/search",{api:"labrinth",version:2,method:"GET",params:{limit:"3",query:"",index:"updated"}}).catch(h=>t(h,{},"/v2/search")),this.client.labrinth.collections.get(yt).then(h=>h.projects??[]).catch(h=>t(h,[],`/v3/collection/${yt}`)),this.client.labrinth.billing_internal.getProducts().catch(h=>t(h,[],"/_internal/billing/products")),this.client.request("/mural/bank-details",{api:"labrinth",version:"internal",method:"GET"}).catch(h=>t(h,null,"/_internal/mural/bank-details")),this.client.iso3166.data.build().catch(h=>t(h,{countries:[],subdivisions:{}},"iso3166/data")),this.client.request("/payout/methods",{api:"labrinth",version:3,method:"GET"}).catch(h=>t(h,[],"/v3/payout/methods")),this.client.request("/globals",{api:"labrinth",version:"internal",method:"GET"}).catch(h=>t(h,null,"/_internal/globals"))]),E=Object.fromEntries(y.filter(h=>h.type==="tremendous").map(h=>[h.id,{name:h.name,image_url:h.image_logo_url}]));return{categories:r,loaders:n,gameVersions:s,donationPlatforms:a,reportTypes:l,homePageProjects:c,homePageSearch:p,homePageNotifs:u,prideProjectIds:d,products:m,muralBankDetails:b?.bankDetails??{},tremendousIdMap:E,countries:v.countries,subdivisions:v.subdivisions,taxComplianceThresholds:x?.tax_compliance_thresholds??{},errors:e}}};var we=class extends o{getModuleID(){return"labrinth_tech_review_internal"}async getRules(){return this.client.request("/moderation/tech-review/rules",{api:"labrinth",version:"internal",method:"GET"})}async getRuleSchema(){return this.client.request("/moderation/tech-review/rules/schema",{api:"labrinth",version:"internal",method:"GET"})}async getIssueTypeSchema(){return this.client.request("/delphi/issue_type/schema",{api:"labrinth",version:"internal",method:"GET"})}async getDetailRuleInput(e){return this.client.request(`/moderation/tech-review/rules/details/${e}/input`,{api:"labrinth",version:"internal",method:"GET"})}async getRuleAffectedDetails(e,t={}){return this.client.request(`/moderation/tech-review/rules/${e}/effects`,{api:"labrinth",version:"internal",method:"GET",params:t})}async testRule(e){return this.client.request("/moderation/tech-review/rules/test",{api:"labrinth",version:"internal",method:"POST",body:e})}async createRule(e){return this.client.request("/moderation/tech-review/rules",{api:"labrinth",version:"internal",method:"POST",body:e})}async updateRule(e,t){return this.client.request(`/moderation/tech-review/rules/${e}`,{api:"labrinth",version:"internal",method:"PUT",body:t})}async deleteRule(e){return this.client.request(`/moderation/tech-review/rules/${e}`,{api:"labrinth",version:"internal",method:"DELETE"})}async scanRules(e){return this.client.stream("/moderation/tech-review/rules/scan",{api:"labrinth",version:"internal",method:"POST",signal:e})}async searchProjects(e){return this.client.request("/moderation/tech-review/search",{api:"labrinth",version:"internal",method:"POST",body:e})}async getReport(e){return this.client.request(`/moderation/tech-review/report/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async getIssue(e,t={}){return this.client.request(`/moderation/tech-review/issue/${e}`,{api:"labrinth",version:"internal",method:"GET",params:t})}async updateIssueDetail(e,t){return this.updateIssueDetails([{detail_id:e,verdict:t.verdict}])}async updateIssueDetails(e){return this.client.request("/moderation/tech-review/issue-detail",{api:"labrinth",version:"internal",method:"PATCH",body:e})}async updateGlobalIssueDetails(e){return this.client.request("/moderation/tech-review/global-traces",{api:"labrinth",version:"internal",method:"POST",body:e})}async searchGlobalIssueDetails(e){return this.client.request("/moderation/tech-review/global-traces/search",{api:"labrinth",version:"internal",method:"POST",body:e})}async getGlobalIssueDetail(e){return this.client.request("/moderation/tech-review/global-traces/local-traces",{api:"labrinth",version:"internal",method:"POST",body:e})}async submitProject(e,t){return this.client.request(`/moderation/tech-review/submit/${e}`,{api:"labrinth",version:"internal",method:"POST",body:t})}async getProjectReport(e){return this.client.request(`/moderation/tech-review/project/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async getUsersFlaggedProjects(e){return this.client.request("/moderation/tech-review/users/flagged-projects",{api:"labrinth",version:"internal",method:"GET",params:{ids:JSON.stringify(e)}})}async getOrganizationFlaggedProjects(e){return this.client.request(`/moderation/tech-review/organization/${e}/flagged-projects`,{api:"labrinth",version:"internal",method:"GET"})}};var Le=class extends o{getModuleID(){return"labrinth_threads_v3"}async getThread(e){return this.client.request(`/thread/${e}`,{api:"labrinth",version:3,method:"GET"})}async getMultiple(e){return this.client.request(`/threads?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:3,method:"GET"})}async sendMessage(e,t){return this.client.request(`/thread/${e}`,{api:"labrinth",version:3,method:"POST",body:t,retry:!1})}async createIssues(e,t){return this.client.request(`/thread/${e}/issue`,{api:"labrinth",version:3,method:"PUT",body:t,retry:!1})}async editIssueFacet(e,t){return this.client.request(`/thread/issue/facet/${e}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async user_addressed(e){return this.editIssueFacet(e,{user_addressed:!0})}async moderator_verified(e){return this.editIssueFacet(e,{moderator_verified:!0})}async deleteMessage(e){return this.client.request(`/message/${e}`,{api:"labrinth",version:3,method:"DELETE"})}};var qe=class extends o{getModuleID(){return"labrinth_users_v2"}async get(e){return this.client.request(`/user/${e}`,{api:"labrinth",version:2,method:"GET"})}async getMultiple(e){return this.client.request(`/users?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:2,method:"GET"})}async getProjects(e){return this.client.request(`/user/${e}/projects`,{api:"labrinth",version:2,method:"GET"})}async getOrganizations(e){return this.client.request(`/user/${e}/organizations`,{api:"labrinth",version:3,method:"GET"})}async getCollections(e){return this.client.request(`/user/${e}/collections`,{api:"labrinth",version:3,method:"GET"})}async getNotifications(e){return this.client.request(`/user/${e}/notifications`,{api:"labrinth",version:2,method:"GET"})}async getFollowedProjects(e){return this.client.request(`/user/${e}/follows`,{api:"labrinth",version:2,method:"GET"})}async patch(e,t){return this.client.request(`/user/${e}`,{api:"labrinth",version:2,method:"PATCH",body:t})}async changeIcon(e,t,r){return this.client.request(`/user/${e}/icon`,{api:"labrinth",version:2,method:"PATCH",params:{ext:r},body:t})}async deleteIcon(e){return this.client.request(`/user/${e}/icon`,{api:"labrinth",version:2,method:"DELETE"})}};var Ce=class extends o{getModuleID(){return"labrinth_users_v3"}async getAuthenticated(){return this.client.request("/user",{api:"labrinth",version:3,method:"GET"})}async get(e){return this.client.request(`/user/${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"GET"})}async getPreferences(e){return this.client.request(`/user/${encodeURIComponent(e)}/preferences`,{api:"labrinth",version:3,method:"GET"})}async patchPreferences(e,t){return this.client.request(`/user/${encodeURIComponent(e)}/preferences`,{api:"labrinth",version:3,method:"PATCH",body:t})}async search(e){return this.client.request(`/users/search?query=${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"GET"})}async getProjects(e){return this.client.request(`/user/${encodeURIComponent(e)}/projects`,{api:"labrinth",version:3,method:"GET"})}async getFollowedProjects(e){return this.client.request(`/user/${encodeURIComponent(e)}/follows`,{api:"labrinth",version:3,method:"GET"})}async getAllProjects(e){return this.client.request(`/user/${encodeURIComponent(e)}/all-projects`,{api:"labrinth",version:3,method:"GET"})}};var Ie=class extends o{getModuleID(){return"labrinth_versions_v2"}async getProjectVersions(e,t){let r={};return t?.game_versions?.length&&(r.game_versions=JSON.stringify(t.game_versions)),t?.loaders?.length&&(r.loaders=JSON.stringify(t.loaders)),t?.include_changelog===!1&&(r.include_changelog="false"),t?.limit!=null&&(r.limit=String(t.limit)),t?.offset!=null&&(r.offset=String(t.offset)),this.client.request(`/project/${e}/version`,{api:"labrinth",version:2,method:"GET",params:Object.keys(r).length>0?r:void 0})}async getVersion(e){return this.client.request(`/version/${e}`,{api:"labrinth",version:2,method:"GET"})}async getVersionFromFileHash(e,t){return this.client.request(`/version_file/${e}`,{api:"labrinth",version:2,method:"GET",params:{algorithm:t}})}async getVersions(e,t){return this.client.request("/versions",{api:"labrinth",version:2,method:"GET",params:{ids:JSON.stringify(e),...t?.include_changelog===!1?{include_changelog:"false"}:{}}})}async getVersionFromIdOrNumber(e,t){return this.client.request(`/project/${e}/version/${t}`,{api:"labrinth",version:2,method:"GET"})}async deleteVersion(e){return this.client.request(`/version/${e}`,{api:"labrinth",version:2,method:"DELETE"})}};var ft=1800*1e3,Me=class extends o{getModuleID(){return"labrinth_versions_v3"}async getProjectVersions(e,t){let r={};return t?.game_versions?.length&&(r.game_versions=JSON.stringify(t.game_versions)),t?.loaders?.length&&(r.loaders=JSON.stringify(t.loaders)),t?.include_changelog===!1&&(r.include_changelog="false"),t?.limit!=null&&(r.limit=String(t.limit)),t?.offset!=null&&(r.offset=String(t.offset)),this.client.request(`/project/${e}/version`,{api:"labrinth",version:t?.apiVersion??2,method:"GET",params:Object.keys(r).length>0?r:void 0})}async getVersion(e){return this.client.request(`/version/${e}`,{api:"labrinth",version:3,method:"GET"})}async getVersions(e){return this.client.request("/versions",{api:"labrinth",version:3,method:"GET",params:{ids:JSON.stringify(e)}})}async getVersionFromIdOrNumber(e,t){return this.client.request(`/project/${e}/version/${t}`,{api:"labrinth",version:3,method:"GET"})}createVersion(e,t,r=null){let n=new FormData,s=t.map(u=>u.file),a=t.map(u=>u.fileType||null),l=s.map((u,d)=>`${u.name}-${d===0?"primary":d}`),c=l.reduce((u,d,m)=>(u[d]=a[m],u),{}),p={project_id:e.project_id,version_number:e.version_number,name:e.name||e.version_number,changelog:e.changelog,dependencies:e.dependencies||[],game_versions:e.game_versions,version_type:e.version_type,featured:!!e.featured,file_parts:l,file_types:c,primary_file:l[0],environment:e.environment,loaders:e.loaders};return r==="modpack"&&(p.mrpack_loaders=e.loaders,p.loaders=["mrpack"]),n.append("data",JSON.stringify(p)),s.forEach((u,d)=>{n.append(l[d],u,u.name)}),this.client.upload("/version",{api:"labrinth",version:3,formData:n,timeout:ft})}async modifyVersion(e,t){return this.client.request(`/version/${e}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async deleteVersion(e){return this.client.request(`/version/${e}`,{api:"labrinth",version:2,method:"DELETE"})}addFilesToVersion(e,t){let r=new FormData,n=t.map(c=>c.file),s=t.map(c=>c.fileType||null),a=n.map((c,p)=>`${c.name}-${p}`),l=a.reduce((c,p,u)=>(c[p]=s[u],c),{});return r.append("data",JSON.stringify({file_types:l})),n.forEach((c,p)=>{r.append(a[p],c,c.name)}),this.client.upload(`/version/${e}/file`,{api:"labrinth",version:2,formData:r,timeout:ft})}};var Oe=class extends o{getModuleID(){return"labrinth_affiliate_internal"}async getAll(){return this.client.request("/affiliate",{api:"labrinth",version:"internal",method:"GET"})}async create(e){return this.client.request("/affiliate",{api:"labrinth",version:"internal",method:"PUT",body:e})}async get(e){return this.client.request(`/affiliate/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async delete(e){return this.client.request(`/affiliate/${e}`,{api:"labrinth",version:"internal",method:"DELETE"})}async patch(e,t){return this.client.request(`/affiliate/${e}`,{api:"labrinth",version:"internal",method:"PATCH",body:t})}};var $e=class extends o{getModuleID(){return"labrinth_blocked_users_internal"}async getStatus(e,t){return this.client.request(`/block/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{api:"labrinth",version:"internal",method:"GET"})}};var Ue=class extends o{getModuleID(){return"labrinth_blocked_users_v3"}async list(){return this.client.request("/blocks",{api:"labrinth",version:3,method:"GET"})}async block(e){return this.client.request(`/block/${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"POST"})}async unblock(e){return this.client.request(`/block/${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"DELETE"})}};var De=class extends o{getModuleID(){return"labrinth_campaign_internal"}async getPride26(){return this.client.request("/campaign/pride-26",{api:"labrinth",version:"internal",method:"GET",skipAuth:!0})}};var je=class extends o{getModuleID(){return"labrinth_tags_v2"}async getLicenses(){return this.client.request("/tag/license",{api:"labrinth",version:2,method:"GET"})}async getLicenseText(e){return this.client.request(`/tag/license/${e}`,{api:"labrinth",version:2,method:"GET"})}};var Ne=class extends o{getModuleID(){return"labrinth_teams_v2"}async addMember(e,t){return this.client.request(`/team/${e}/members`,{api:"labrinth",version:2,method:"POST",body:t})}async editMember(e,t,r){return this.client.request(`/team/${e}/members/${t}`,{api:"labrinth",version:2,method:"PATCH",body:r})}async removeMember(e,t){return this.client.request(`/team/${e}/members/${t}`,{api:"labrinth",version:2,method:"DELETE"})}async transferOwnership(e,t){return this.client.request(`/team/${e}/owner`,{api:"labrinth",version:2,method:"PATCH",body:t})}};var Fe=class extends o{getModuleID(){return"labrinth_teams_v3"}async getMultiple(e){return this.client.request(`/teams?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:3,method:"GET"})}};var Dt="https://launcher-meta.modrinth.com",Be=class extends o{getModuleID(){return"launchermeta_manifest_v0"}async getManifest(e,t=0){return this.client.request("/manifest.json",{api:Dt,version:`${e}/v${t}`,method:"GET",skipAuth:!0,headers:{"Content-Type":""}})}};var Ge=class extends o{getModuleID(){return"mclogs_insights_v1"}async analyse(e){return this.client.request("/analyse",{api:"https://api.mclo.gs",version:"1",method:"POST",body:new URLSearchParams({content:e}),headers:{"Content-Type":"application/x-www-form-urlencoded"},skipAuth:!0})}};var We=class extends o{getModuleID(){return"mclogs_logs_v1"}async create(e){return this.client.request("/log",{api:"https://api.mclo.gs",version:"1",method:"POST",body:new URLSearchParams({content:e}),headers:{"Content-Type":"application/x-www-form-urlencoded"},skipAuth:!0})}};var Pt="https://fill.papermc.io",Ve=class extends o{getModuleID(){return"paper_versions_v3"}async getProject(){return this.client.request("/projects/paper",{api:Pt,version:"v3",method:"GET",skipAuth:!0})}async getBuilds(e){return{builds:await this.client.request(`/projects/paper/versions/${e}/builds`,{api:Pt,version:"v3",method:"GET",skipAuth:!0})}}};var St="https://api.purpurmc.org",He=class extends o{getModuleID(){return"purpur_versions_v2"}async getProject(){return this.client.request("/purpur",{api:St,version:"v2",method:"GET",skipAuth:!0})}async getBuilds(e){return this.client.request(`/purpur/${e}`,{api:St,version:"v2",method:"GET",skipAuth:!0})}};var ze=class extends o{getModuleID(){return"sharedinstances_instances_v1"}async get(e){return this.client.request(`/instances/${encodeURIComponent(e)}`,{api:"sharedinstances",version:1,method:"GET"})}async getForUser(e){return this.client.request("/instances",{api:"sharedinstances",version:1,method:"GET",params:{user:e}})}async getUsers(e){return this.client.request(`/instances/${encodeURIComponent(e)}/users`,{api:"sharedinstances",version:1,method:"GET"})}async getLatestVersion(e){return this.client.request(`/instances/${encodeURIComponent(e)}/versions`,{api:"sharedinstances",version:1,method:"GET"})}async getVersion(e,t){return this.client.request(`/instances/${encodeURIComponent(e)}/versions/${t}`,{api:"sharedinstances",version:1,method:"GET"})}};var Ke=class extends o{getModuleID(){return"sharedinstances_invites_v1"}async get(e){return this.client.request(`/invites/${encodeURIComponent(e)}`,{api:"sharedinstances",version:1,method:"GET",skipAuth:!0,retry:!1})}};var Je=class extends o{getModuleID(){return"sharedinstances_moderation_v1"}async blacklistUsers(e){return this.client.request("/moderation/blacklist",{api:"sharedinstances",version:1,method:"POST",body:e})}async unblacklistUsers(e){return this.client.request("/moderation/blacklist",{api:"sharedinstances",version:1,method:"DELETE",body:e})}async deleteFile(e,t,r){return this.client.request(`/moderation/instances/${encodeURIComponent(e)}/versions/${t}/files/${encodeURIComponent(r)}`,{api:"sharedinstances",version:1,method:"DELETE"})}};var Qe=class extends o{getModuleID(){return"sharedinstances_users_v1"}async getBlacklistStatus(e){return this.client.request(`/blacklist/${encodeURIComponent(e)}`,{api:"sharedinstances",version:1,method:"GET"})}};var jt={archon_actions_v1:U,archon_backups_queue_v1:j,archon_backups_v1:D,archon_content_v1:N,archon_nodes_internal:F,archon_notices_v0:B,archon_options_v1:G,archon_properties_v1:W,archon_server_users_v1:V,archon_servers_internal:H,archon_servers_v0:z,archon_servers_v1:K,archon_transfers_internal:J,iso3166_data:Q,mclogs_insights_v1:Ge,mclogs_logs_v1:We,launchermeta_manifest_v0:Be,kyros_content_v1:X,kyros_files_v0:Y,kyros_files_v1:Z,kyros_logs_v1:ee,kyros_upload_sessions_v1:te,labrinth_affiliate_internal:Oe,labrinth_analytics_internal:re,labrinth_analytics_v3:ne,labrinth_auth_internal:se,labrinth_auth_v2:oe,labrinth_attribution_internal:ie,labrinth_billing_internal:ae,labrinth_blocked_users_internal:$e,labrinth_blocked_users_v3:Ue,labrinth_campaign_internal:De,labrinth_collections:le,labrinth_content_v3:ce,labrinth_external_projects_internal:ue,labrinth_friends_v3:pe,labrinth_geoip:de,labrinth_globals_internal:he,labrinth_images_v3:me,labrinth_moderation_internal:be,labrinth_notifications_v2:ve,labrinth_oauth_internal:ye,labrinth_organizations_v3:fe,labrinth_pats_v2:Pe,labrinth_limits_v3:ge,labrinth_payout_v3:Se,labrinth_payouts_v3:Ae,labrinth_projects_v2:_e,labrinth_projects_v3:Ee,labrinth_reports_v3:Re,labrinth_server_ping_internal:Te,labrinth_sessions_v2:ke,labrinth_state:xe,labrinth_tags_v2:je,labrinth_teams_v2:Ne,labrinth_teams_v3:Fe,labrinth_tech_review_internal:we,labrinth_threads_v3:Le,labrinth_users_v2:qe,labrinth_users_v3:Ce,labrinth_versions_v2:Ie,labrinth_versions_v3:Me,paper_versions_v3:Ve,purpur_versions_v2:He,sharedinstances_invites_v1:Ke,sharedinstances_instances_v1:ze,sharedinstances_moderation_v1:Je,sharedinstances_users_v1:Qe};function Nt(i){let e=i.split("_");if(e.length<2)throw new Error(`Invalid module ID "${i}". Expected format: <api>_<module> (e.g., "labrinth_projects_v2")`);let t=e[0],r=e.slice(1).join("_");return[t,r]}function At(){let i={};for(let[e,t]of Object.entries(jt)){let[r,n]=Nt(e);i[r]||(i[r]={}),i[r][n]=t}return i}var q=class{};var C=class extends q{constructor(t){super();this._moduleInstances=new Map;this._moduleNamespaces=new Map;this.config={timeout:1e4,labrinthBaseUrl:"https://api.modrinth.com",archonBaseUrl:"https://archon.modrinth.com",sharedInstancesBaseUrl:"https://shared-instances.modrinth.com",...t},this.features=t.features??[],this.initializeModules()}initializeModules(){let t=At();for(let[r,n]of Object.entries(t)){let s={};for(let[a,l]of Object.entries(n)){let c=`${r}_${a}`;Object.defineProperty(s,a,{get:()=>{if(!this._moduleInstances.has(c)){let p=new l(this),u=p.getModuleID();if(u!==c)throw new Error(`Module ID mismatch: registry expects "${c}" but module declares "${u}"`);this._moduleInstances.set(c,p)}return this._moduleInstances.get(c)},enumerable:!0,configurable:!1})}Object.defineProperty(this,r,{value:s,writable:!1,enumerable:!0,configurable:!1}),this._moduleNamespaces.set(r,s)}}async request(t,r){let n;r.api==="labrinth"?n=this.resolveBaseUrl(this.config.labrinthBaseUrl):r.api==="archon"?n=this.resolveBaseUrl(this.config.archonBaseUrl):r.api==="sharedinstances"?n=this.resolveBaseUrl(this.config.sharedInstancesBaseUrl):n=r.api;let s=this.buildUrl(t,n,r.version),a=await this.buildDefaultHeaders(),l={method:"GET",timeout:this.config.timeout,...r,headers:{...a,...r.headers}};this.attachArchonSentryCaptureHeader(l);let c=l.headers;c&&"Content-Type"in c&&c["Content-Type"]===""&&delete c["Content-Type"];let p=this.buildContext(s,t,l);try{let u=await this.executeFeatureChain(p);return await this.config.hooks?.onResponse?.(u,p),u}catch(u){let d=this.normalizeError(u,p);throw d.url??(d.url=p.url),await this.config.hooks?.onError?.(d,p),d}}async stream(t,r){let n;r.api==="labrinth"?n=this.resolveBaseUrl(this.config.labrinthBaseUrl):r.api==="archon"?n=this.resolveBaseUrl(this.config.archonBaseUrl):r.api==="sharedinstances"?n=this.resolveBaseUrl(this.config.sharedInstancesBaseUrl):n=r.api;let s=this.buildUrl(t,n,r.version),a=await this.buildDefaultHeaders(),l={method:"GET",retry:!1,circuitBreaker:!1,...r,headers:{...a,Accept:"text/event-stream",...r.headers}};this.attachArchonSentryCaptureHeader(l);let c=this.buildContext(s,t,l);try{return await this.executeFeatureChain(c,()=>this.executeStreamRequest(c.url,c.options))}catch(p){let u=this.normalizeError(p,c);throw u.url??(u.url=c.url),await this.config.hooks?.onError?.(u,c),u}}async executeFeatureChain(t,r=()=>this.executeRequest(t.url,t.options)){let n=this.features.filter(l=>l.shouldApply(t)),s=n.length,a=async()=>(s--,s>=0?n[s].execute(a,t):(await this.config.hooks?.onRequest?.(t),r()));return a()}async executeUploadFeatureChain(t,r,n){let s=this.features.filter(c=>c.shouldApply(t)),a=s.length,l=async()=>(a--,a>=0?s[a].execute(l,t):(await this.config.hooks?.onRequest?.(t),this.executeXHRUpload(t,r,n)));return l()}buildUrl(t,r,n){let s=r.replace(/\/$/,""),a="";n==="internal"?a="/_internal":typeof n=="number"?a=`/v${n}`:typeof n=="string"&&(a=`/${n}`);let l=t.startsWith("/")?t:`/${t}`;return`${s}${a}${l}`}resolveBaseUrl(t){return typeof t=="function"?t():t}buildContext(t,r,n){return{url:t,path:r,options:n,attempt:1,startTime:Date.now()}}buildUploadContext(t,r,n){let s,a;if("formData"in n&&n.formData)s={isUpload:!0,formData:n.formData,onProgress:n.onProgress},a=n.formData;else if("file"in n&&n.file)s={isUpload:!0,file:n.file,onProgress:n.onProgress},a=n.file;else throw new Error("Upload options must include either file or formData");return{url:t,path:r,options:{...n,method:"POST",body:a},attempt:1,startTime:Date.now(),metadata:s}}async buildDefaultHeaders(){let t={"Content-Type":"application/json",...this.config.headers},r=await this.resolveUserAgent();return r&&(t["User-Agent"]=r),t}async resolveUserAgent(){let t=this.config.userAgent;return typeof t=="function"?await t():t}attachArchonSentryCaptureHeader(t){t.api!=="archon"||!t.headers||!this.shouldCaptureArchonRequests()||(t.headers["modrinth-sentry-capture"]="1")}shouldCaptureArchonRequests(){let t=this.config.archonSentryCapture;return typeof t=="function"?t():t===!0}normalizeError(t,r){return t instanceof g?t:g.fromUnknown(t,r?.path)}createNormalizedError(t,r,n){return r&&n?L.fromResponse(r,n):new g(t.message,{statusCode:r,originalError:t,responseData:n})}addFeature(t){return this.features.push(t),this}removeFeature(t){let r=this.features.indexOf(t);return r!==-1&&this.features.splice(r,1),this}getFeatures(){return[...this.features]}};var f=class{constructor(e){this.config={enabled:!0,...e}}shouldApply(e){return this.config.enabled!==!1}get name(){return this.config.name??this.constructor.name}get enabled(){return this.config.enabled!==!1}};var I=class{constructor(e){this.client=e;this.connections=new Map}on(e,t,r){let n=this.getEventKey(e,t),s=r;return this.emitter.on(n,s),()=>{this.emitter.off(n,s)}}onAny(e,t){let r=this.getAnyEventKey(e),n=t;return this.emitter.on(r,n),()=>{this.emitter.off(r,n)}}onStatus(e,t){let r=this.getStatusEventKey(e),n=t;return this.emitter.on(r,n),()=>{this.emitter.off(r,n)}}getStatus(e){let t=this.connections.get(e);return t?this.connectionToStatus(t):null}emitSyncEvent(e,t){this.emitter.emit(this.getEventKey(e,t.type),t),this.emitter.emit(this.getAnyEventKey(e),t)}updateStatus(e,t,r){e.status=t,e.error=r,this.emitter.emit(this.getStatusEventKey(e.serverId),this.connectionToStatus(e))}clearListeners(e){this.emitter.all.forEach((t,r)=>{r.toString().startsWith(`${e}:`)&&this.emitter.all.delete(r)})}connectionToStatus(e){return{state:e.status,connected:e.status==="connected",reconnecting:e.status==="reconnecting",reconnectAttempts:e.reconnectAttempts,retryDelay:e.retryDelay,lastEventId:e.lastEventId,error:e.error}}getEventKey(e,t){return`${e}:${t}`}getAnyEventKey(e){return`${e}:*`}getStatusEventKey(e){return`${e}:__status`}};var M=class{constructor(e){this.client=e;this.connections=new Map;this.MAX_RECONNECT_ATTEMPTS=10;this.RECONNECT_BASE_DELAY=1e3;this.RECONNECT_MAX_DELAY=3e4;this.AUTHENTICATION_TIMEOUT=3e4}async safeConnect(e,t){let r=this.getStatus(e);if(r?.connected&&!t?.force)return;if(r&&!r.connected&&!t?.force){await this.waitForAuthentication(e);return}t?.force&&r&&this.disconnect(e);let n=await this.client.archon.servers_v0.getWebSocketAuth(e);await this.connect(e,n)}async waitForAuthentication(e){await new Promise((t,r)=>{let n=()=>{},s=setTimeout(()=>{n(),r(new Error(`WebSocket authentication timed out for server ${e}`))},this.AUTHENTICATION_TIMEOUT);n=this.on(e,"auth-ok",()=>{clearTimeout(s),n(),t()}),this.getStatus(e)?.connected&&(clearTimeout(s),n(),t())})}on(e,t,r){let n=`${e}:${t}`;return this.emitter.on(n,r),()=>{this.emitter.off(n,r)}}getStatus(e){let t=this.connections.get(e);return t?{connected:t.socket.readyState===WebSocket.OPEN&&t.authenticated,reconnecting:t.isReconnecting,reconnectAttempts:t.reconnectAttempts}:null}getReconnectDelay(e){return Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,e),this.RECONNECT_MAX_DELAY)+Math.random()*1e3}};var et=class extends f{async execute(e,t){let r=await this.getToken();if(r){let n=this.config.headerName??"Authorization",s=this.config.tokenPrefix??"Bearer",a=s?`${s} ${r}`:r;t.options.headers={...t.options.headers,[n]:a}}return e()}shouldApply(e){if(e.options.skipAuth)return!1;let t=this.config.headerName??"Authorization";return e.options.headers?.[t]?!1:super.shouldApply(e)}async getToken(){let{token:e}=this.config;return typeof e=="function"?await e():e}};var Xe=class{constructor(){this.state=new Map}get(e){return this.state.get(e)}set(e,t){this.state.set(e,t)}clear(e){this.state.delete(e)}},tt=class extends f{constructor(e){super(e),this.config={enabled:!0,name:"circuit-breaker",maxFailures:3,resetTimeout:3e4,failureStatusCodes:[500,502,503,504],...e},this.storage=e?.storage??new Xe}async execute(e,t){let r=this.getCircuitKey(t);if(this.isCircuitOpen(r))throw new g("Circuit breaker open - too many recent failures",{statusCode:503,context:t.path});try{let n=await e();return this.recordSuccess(r),n}catch(n){throw this.isFailureError(n)&&this.recordFailure(r),n}}shouldApply(e){return e.options.circuitBreaker===!1?!1:super.shouldApply(e)}getCircuitKey(e){if(this.config.getCircuitKey)return this.config.getCircuitKey(e.url,e.options.method??"GET");let t=e.options.method??"GET",r=e.path.split("?")[0];return`${t}_${r}`}isCircuitOpen(e){let t=this.storage.get(e);return t?Date.now()-t.lastFailure>this.config.resetTimeout?(this.storage.clear?.(e),!1):t.failures>=this.config.maxFailures:!1}recordSuccess(e){this.storage.clear?.(e)}recordFailure(e){let t=Date.now(),r=this.storage.get(e);r?this.storage.set(e,{failures:r.failures+1,lastFailure:t}):this.storage.set(e,{failures:1,lastFailure:t})}isFailureError(e){return e instanceof g&&e.statusCode?this.config.failureStatusCodes.includes(e.statusCode):!1}getCircuitState(e){return this.storage.get(e)}resetCircuit(e){this.storage.clear?.(e)}};var rt=class extends f{constructor(){super(...arguments);this.refreshPromise=null}shouldApply(t){return t.options.useNodeAuth===!0&&this.config.enabled!==!1}async refreshAuthWithLock(){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=this.config.refreshAuth().finally(()=>{this.refreshPromise=null}),this.refreshPromise)}async execute(t,r){let s=0,a=this.config.getAuth();if((!a||this.isTokenExpired(a.token))&&(await this.refreshAuthWithLock(),a=this.config.getAuth()),!a)throw new Error("Failed to obtain node authentication");for(this.applyAuth(r,a);;)try{return await t()}catch(l){if(l instanceof g&&l.statusCode===401){if(s++,s>=3)throw new Error("Node authentication failed after 3 retries. Please re-authenticate.");if(await this.refreshAuthWithLock(),a=this.config.getAuth(),!a)throw new Error("Failed to refresh node authentication");this.applyAuth(r,a);continue}throw l}}applyAuth(t,r){let n=P(r.url);t.url=this.buildUrl(t.path,n,t.options.version),t.options.headers={...t.options.headers,Authorization:`Bearer ${r.token}`},t.options.skipAuth=!0}buildUrl(t,r,n){let s=r.replace(/\/$/,""),a="";n==="internal"?a="/_internal":typeof n=="number"?a=`/v${n}`:typeof n=="string"&&(a=`/${n}`);let l=t.startsWith("/")?t:`/${t}`;return`${s}${a}${l}`}isTokenExpired(t){try{let r=JSON.parse(atob(t.split(".")[1]));if(!r.exp)return!1;let n=r.exp*1e3;return Date.now()>=n-1e4}catch{return!1}}};var _t=1,nt=class extends f{async execute(e,t){return t.options.headers={...t.options.headers,"X-Panel-Version":String(_t)},e()}shouldApply(e){return e.options.api==="labrinth"||e.options.api==="archon"}};var it=class extends f{constructor(e){super(e),this.config={enabled:!0,name:"retry",maxAttempts:3,backoffStrategy:"exponential",initialDelay:1e3,maxDelay:15e3,retryableStatusCodes:[408,429,500,502,503,504],retryOnNetworkError:!0,...e}}async execute(e,t){let r=null,n=this.getMaxAttempts(t);for(let s=1;s<=n;s++){t.attempt=s;try{return await e()}catch(a){if(r=a,!this.shouldRetryError(a,s,n)||s>=n)throw a;let c=this.calculateDelay(s);console.warn(`[${this.name}] Retrying request to ${t.path} (attempt ${s+1}/${n}) after ${c}ms`),await this.sleep(c)}}throw r??new Error("Max retry attempts reached")}shouldApply(e){return e.options.retry===!1?!1:super.shouldApply(e)}shouldRetryError(e,t,r){return this.config.shouldRetry?this.config.shouldRetry(e,t):this.config.retryOnNetworkError&&this.isNetworkError(e)?!0:e instanceof g&&e.statusCode?this.config.retryableStatusCodes.includes(e.statusCode):!1}isNetworkError(e){let t=[/network/i,/timeout/i,/ECONNREFUSED/i,/ENOTFOUND/i,/ETIMEDOUT/i,/ECONNRESET/i],r=e instanceof Error?e.message:String(e);return t.some(n=>n.test(r))}getMaxAttempts(e){return typeof e.options.retry=="number"?e.options.retry:this.config.maxAttempts}calculateDelay(e){let{backoffStrategy:t,initialDelay:r,maxDelay:n}=this.config,s;switch(t){case"exponential":s=r*Math.pow(2,e-1);break;case"linear":s=r*e;break;case"constant":s=r;break;default:s=r}return s+=Math.random()*1e3,Math.min(s,n)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var st=class extends f{async execute(e,t){let r=t.options.method??"GET",n=t.options.api,s=t.options.version,a=`[${r}] [${n}_v${s}]`;console.debug(`${a} ${t.url} SENT`);try{let l=await e();try{let c=l?JSON.stringify(l).length:0;console.debug(`${a} ${t.url} RECEIVED ${c} bytes`)}catch{console.debug(`${a} ${t.url} RECEIVED`)}return l}catch(l){let c=Ft(l);throw console.debug(`${a} ${t.url} FAILED${c?` \u2014 ${c}`:""}`),l}}};function Ft(i){if(!i||typeof i!="object")return typeof i=="string"?i:"";let e=i,t=e.status??e.statusCode??e.response?.status,r=e.statusText??e.response?.statusText,n=e.responseData??e.data??e.response?._data,s=[];return t!==void 0&&s.push(r?`${t} ${r}`:String(t)),n!==void 0?s.push(`body: ${Bt(n)}`):e.message&&s.push(e.message),s.join(" ")}function Bt(i){if(typeof i=="string")return i;try{return JSON.stringify(i)}catch{return String(i)}}var Et;(e=>{let i;(r=>{let t;(s=>s.UserScope={NONE:"",SERVER_ADMIN:"SERVER_ADMIN",BASE_READ:"BASE_READ",POWER_ACTIONS:"POWER_ACTIONS",EXEC_COMMANDS:"EXEC_COMMANDS",FILES_WRITE:"FILES_WRITE",SETUP:"SETUP",BACKUPS:"BACKUPS",ADVANCED:"ADVANCED",RESET_SERVER:"RESET_SERVER",MANAGE_USERS:"MANAGE_USERS",SUPPORT_AGENT:"SUPPORT_AGENT",INFRA_MANAGER:"INFRA_MANAGER",INFRA_MANAGER_READ:"INFRA_MANAGER_READ",INFRA_SERVERS_XFER:"INFRA_SERVERS_XFER",INFRA_USERS:"INFRA_USERS"})(t=r.v1||(r.v1={}))})(i=e.ServerUsers||(e.ServerUsers={}))})(Et||(Et={}));import{$fetch as zt,FetchError as Kt}from"ofetch";function R(i,e){if(!e)return i;let t={};for(let[n,s]of Object.entries(e))s!=null&&(t[n]=String(s));let r=new URLSearchParams(t).toString();return r?`${i}${i.includes("?")?"&":"?"}${r}`:i}function T(i){if(i)return typeof i=="object"&&!(i instanceof FormData)&&!(i instanceof URLSearchParams)&&!(i instanceof Blob)&&!(i instanceof ArrayBuffer)&&!ArrayBuffer.isView(i)?JSON.stringify(i):i}async function k(i){let e=i.headers.get("content-type")?.toLowerCase()??"";try{if(e.includes("application/json")||e.includes("+json"))return await i.json();let t=await i.text();if(!t)return;try{return JSON.parse(t)}catch{return t}}catch{return}}import Gt from"mitt";var O=class{constructor(){this.buffer="";this.eventName="";this.data=""}feed(e){this.buffer+=e;let t=[];for(;;){let r=this.findLineEnd();if(!r)break;let{line:n,length:s}=r;this.buffer=this.buffer.slice(s),this.processLine(n,t)}return t}end(){let e=[];return this.buffer.length>0&&(this.processLine(this.buffer.endsWith("\r")?this.buffer.slice(0,-1):this.buffer,e),this.buffer=""),this.dispatch(e),e}findLineEnd(){let e=this.buffer.indexOf(`
5
+ `).find(r=>r.startsWith("loc="))?.slice(4).toUpperCase();return t?.match(/^[A-Z]{2}$/)?t:void 0}};var he=class extends o{getModuleID(){return"labrinth_globals_internal"}async get(){return this.client.request("/globals",{api:"labrinth",version:"internal",method:"GET",skipAuth:!0})}};function It(i,e){let t={ext:i,context:e.context};switch(e.context){case"project":t.project_id=e.project_id;break;case"version":t.version_id=e.version_id;break;case"thread_message":t.thread_message_id=e.thread_message_id;break;case"report":e.report_id&&(t.report_id=e.report_id);break}return t}var me=class extends o{getModuleID(){return"labrinth_images_v3"}uploadImage(e,t,r){return this.client.upload("/image",{api:"labrinth",version:3,file:e,params:It(t,r)})}};var ge=class extends o{getModuleID(){return"labrinth_limits_v3"}async getProjectLimits(){return this.client.request("/limits/projects",{api:"labrinth",version:3,method:"GET"})}async getOrganizationLimits(){return this.client.request("/limits/organizations",{api:"labrinth",version:3,method:"GET"})}async getCollectionLimits(){return this.client.request("/limits/collections",{api:"labrinth",version:3,method:"GET"})}};var be=class extends o{getModuleID(){return"labrinth_moderation_internal"}async getProjects(e={}){return this.client.request("/moderation/projects",{api:"labrinth",version:"internal",method:"GET",params:e,timeout:20*1e3})}async getProjectIds(e={}){return this.client.request("/moderation/projects/ids",{api:"labrinth",version:"internal",method:"GET",params:e})}async acquireLock(e){return this.client.request(`/moderation/lock/${e}`,{api:"labrinth",version:"internal",method:"POST"})}async overrideLock(e){return this.client.request(`/moderation/lock/${e}/override`,{api:"labrinth",version:"internal",method:"POST"})}async releaseLock(e,t){return this.client.request(`/moderation/lock/${e}`,{api:"labrinth",version:"internal",method:"DELETE",headers:t?{Authorization:`Bearer ${t}`}:void 0})}async checkLock(e){return this.client.request(`/moderation/lock/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async lockUser(e,t){return this.client.request(`/admin/user/${e}/lock`,{api:"labrinth",version:"internal",method:"PUT",body:{reason:t}})}async unlockUser(e){return this.client.request(`/admin/user/${e}/lock`,{api:"labrinth",version:"internal",method:"DELETE"})}async setUserRestrictions(e,t){return this.client.request(`/moderation/user/${e}/restrictions`,{api:"labrinth",version:"internal",method:"PUT",body:t})}async clearUserRestrictions(e){return this.client.request(`/moderation/user/${e}/restrictions`,{api:"labrinth",version:"internal",method:"DELETE"})}async revokeUserSessions(e){return this.client.request(`/admin/user/${e}/sessions`,{api:"labrinth",version:"internal",method:"DELETE"})}async forceUserPasswordReset(e,t){return this.client.request(`/admin/user/${e}/password-reset`,{api:"labrinth",version:"internal",method:"POST",body:{email:t}})}async resetUser2fa(e){return this.client.request(`/admin/user/${e}/2fa`,{api:"labrinth",version:"internal",method:"DELETE"})}async setProjectJudgements(e){return this.client.request("/moderation/project",{api:"labrinth",version:"internal",method:"POST",body:e})}};var ve=class extends o{getModuleID(){return"labrinth_notifications_v2"}async getUserNotifications(e){return this.client.request(`/user/${e}/notifications`,{api:"labrinth",version:2,method:"GET"})}async getMultiple(e){return this.client.request(`/notifications?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:2,method:"GET"})}async markAsRead(e){return this.client.request(`/notification/${e}`,{api:"labrinth",version:2,method:"PATCH"})}async markMultipleAsRead(e){return this.client.request("/notifications",{api:"labrinth",version:2,method:"PATCH",params:{ids:JSON.stringify([...new Set(e)])}})}async delete(e){return this.client.request(`/notification/${e}`,{api:"labrinth",version:2,method:"DELETE"})}async deleteMultiple(e){return this.client.request("/notifications",{api:"labrinth",version:2,method:"DELETE",params:{ids:JSON.stringify([...new Set(e)])}})}};var ye=class extends o{getModuleID(){return"labrinth_oauth_internal"}async getUserApps(e){return this.client.request(`/user/${e}/oauth_apps`,{api:"labrinth",version:3,method:"GET"})}async getApp(e){return this.client.request(`/oauth/app/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async getApps(e){return e.length===0?[]:(await Promise.all(e.map(r=>this.getApp(r).catch(()=>null)))).filter(r=>r!==null)}async createApp(e){return this.client.request("/oauth/app",{api:"labrinth",version:"internal",method:"POST",body:e})}async editApp(e,t){return this.client.request(`/oauth/app/${e}`,{api:"labrinth",version:"internal",method:"PATCH",body:t})}async deleteApp(e){return this.client.request(`/oauth/app/${e}`,{api:"labrinth",version:"internal",method:"DELETE"})}async uploadAppIcon(e,t,r){return this.client.request(`/oauth/app/${e}/icon`,{api:"labrinth",version:"internal",method:"PATCH",params:{ext:r},body:t})}async getAuthorizations(){return this.client.request("/oauth/authorizations",{api:"labrinth",version:"internal",method:"GET"})}async revokeAuthorization(e){return this.client.request("/oauth/authorizations",{api:"labrinth",version:"internal",method:"DELETE",params:{client_id:e}})}async authorize(e){return this.client.request("/oauth/authorize",{api:"labrinth",version:"internal",method:"GET",params:e})}async accept(e){return this.client.request("/oauth/accept",{api:"labrinth",version:"internal",method:"POST",body:e})}async reject(e){return this.client.request("/oauth/reject",{api:"labrinth",version:"internal",method:"POST",body:e})}};var fe=class extends o{getModuleID(){return"labrinth_organizations_v3"}async get(e){return this.client.request(`/organization/${e}`,{api:"labrinth",version:3,method:"GET"})}async getProjects(e){return this.client.request(`/organization/${e}/projects`,{api:"labrinth",version:3,method:"GET"})}async getMultiple(e){return this.client.request(`/organizations?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:3,method:"GET"})}async addProject(e,t){return this.client.request(`/organization/${e}/projects`,{api:"labrinth",version:3,method:"POST",body:t})}async removeProject(e,t,r){return this.client.request(`/organization/${e}/projects/${t}`,{api:"labrinth",version:3,method:"DELETE",body:r})}};var Pe=class extends o{getModuleID(){return"labrinth_pats_v2"}async list(){return this.client.request("/pat",{api:"labrinth",version:2,method:"GET"})}async create(e){return this.client.request("/pat",{api:"labrinth",version:2,method:"POST",body:e})}async modify(e,t){return this.client.request(`/pat/${e}`,{api:"labrinth",version:2,method:"PATCH",body:t})}async delete(e){return this.client.request(`/pat/${e}`,{api:"labrinth",version:2,method:"DELETE"})}};var Se=class extends o{getModuleID(){return"labrinth_payout_v3"}async getBalance(){let e=await this.client.request("/payout/balance",{api:"labrinth",version:3,method:"GET"});return{...e,available:Number(e.available),withdrawn_lifetime:Number(e.withdrawn_lifetime),withdrawn_ytd:Number(e.withdrawn_ytd),pending:Number(e.pending),dates:Object.fromEntries(Object.entries(e.dates).map(([t,r])=>[t,Number(r)]))}}async getHistory(){return(await this.client.request("/payout/history",{api:"labrinth",version:3,method:"GET"})).map(t=>t.type==="withdrawal"?{...t,amount:Number(t.amount),fee:t.fee===null?null:Number(t.fee)}:{...t,amount:Number(t.amount)})}async getMethods(e){return this.client.request("/payout/methods",{api:"labrinth",version:3,method:"GET",params:e?{country:e}:void 0})}async cancel(e){return this.client.request(`/payout/${e}`,{api:"labrinth",version:3,method:"DELETE"})}};var Ae=class extends o{getModuleID(){return"labrinth_payouts_v3"}async getPlatformRevenue(e){return this.client.request("/payout/platform_revenue",{api:"labrinth",version:3,method:"GET",params:e})}};var _e=class extends o{getModuleID(){return"labrinth_projects_v2"}async get(e){return this.client.request(`/project/${e}`,{api:"labrinth",version:2,method:"GET"})}async check(e){let t=encodeURIComponent(e);return this.client.request(`/project/${t}/check`,{api:"labrinth",version:2,method:"GET"})}async getMultiple(e){return this.client.request("/projects",{api:"labrinth",version:2,method:"GET",params:{ids:JSON.stringify(e)}})}async search(e){return this.client.request("/search",{api:"labrinth",version:2,method:"GET",params:{...e,facets:e.facets?JSON.stringify(e.facets):void 0,new_filters:e.new_filters??void 0}})}async edit(e,t){return this.client.request(`/project/${e}`,{api:"labrinth",version:2,method:"PATCH",body:t})}async delete(e){return this.client.request(`/project/${e}`,{api:"labrinth",version:2,method:"DELETE"})}async getDependencies(e){return this.client.request(`/project/${e}/dependencies`,{api:"labrinth",version:2,method:"GET"})}async createGalleryImage(e,t,r){let n={ext:r.ext,featured:String(r.featured)};return r.title&&(n.title=r.title),r.description&&(n.description=r.description),r.ordering!==void 0&&(n.ordering=String(r.ordering)),this.client.request(`/project/${e}/gallery`,{api:"labrinth",version:2,method:"POST",params:n,body:t})}async editGalleryImage(e,t,r){let n={url:t,featured:String(r.featured)};return r.title&&(n.title=r.title),r.description&&(n.description=r.description),r.ordering!==void 0&&(n.ordering=String(r.ordering)),this.client.request(`/project/${e}/gallery`,{api:"labrinth",version:2,method:"PATCH",params:n})}async deleteGalleryImage(e,t){return this.client.request(`/project/${e}/gallery`,{api:"labrinth",version:2,method:"DELETE",params:{url:t}})}async getRandom(e){return this.client.request("/projects_random",{api:"labrinth",version:2,method:"GET",params:{count:String(e)}})}async bulkEdit(e,t){return this.client.request("/projects",{api:"labrinth",version:2,method:"PATCH",params:{ids:JSON.stringify(e)},body:t})}};function Ze(i){if(typeof i!="object"||i===null)return!1;let e=i;return typeof e.error=="string"&&typeof e.description=="string"}var g=class i extends Error{constructor(e,t){super(e),this.name="ModrinthApiError",this.statusCode=t?.statusCode,this.originalError=t?.originalError,this.responseData=t?.responseData,this.context=t?.context,Error.captureStackTrace&&Error.captureStackTrace(this,i)}static fromUnknown(e,t){return e instanceof i?e:e instanceof Error?new i(e.message,{originalError:e,context:t}):new i(String(e),{context:t})}},L=class i extends g{constructor(e,t){let r=t?.v1Error?Mt(t.v1Error):e;super(r,t),this.name="ModrinthServerError",this.v1Error=t?.v1Error,Error.captureStackTrace&&Error.captureStackTrace(this,i)}static fromResponse(e,t,r){let n=Ze(t)?t:void 0,s=typeof t=="string"&&/<!doctype html|<html/i.test(t),a=typeof t=="string"&&!s?t:`HTTP ${e}`;return new i(a,{statusCode:e,responseData:s?void 0:t,context:r,v1Error:n})}static fromUnknown(e,t){return e instanceof i?e:e instanceof g?new i(e.message,{statusCode:e.statusCode,originalError:e.originalError,responseData:e.responseData,context:t??e.context}):e instanceof Error?new i(e.message,{originalError:e,context:t}):new i(String(e),{context:t})}};function Mt(i){return $t(i.details)??i.description}function $t(i){if(typeof i=="string")return i.trim()||void 0;if(Array.isArray(i))return i.findLast(e=>typeof e!="string"?!1:!!e.trim())?.trim()}var Ee=class extends o{getModuleID(){return"labrinth_projects_v3"}async get(e){return this.client.request(`/project/${e}`,{api:"labrinth",version:3,method:"GET"})}async validate(e){return this.client.request(`/project/${e}/validate`,{api:"labrinth",version:3,method:"GET"})}async getDependencies(e){return this.client.request(`/project/${e}/dependencies`,{api:"labrinth",version:3,method:"GET"})}async getMultiple(e){return this.client.request("/projects",{api:"labrinth",version:3,method:"GET",params:{ids:JSON.stringify(e)}})}async search(e,t){return this.client.request("/search",{api:"labrinth",version:3,method:"GET",headers:t?.headers,params:{...e,facets:e.facets?JSON.stringify(e.facets):void 0}})}async edit(e,t){return this.client.request(`/project/${e}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async getOrganization(e){try{return await this.client.request(`/project/${e}/organization`,{api:"labrinth",version:3,method:"GET"})}catch(t){if(t instanceof g&&t.statusCode===404)return null;throw t}}async getMembers(e){return this.client.request(`/project/${e}/members`,{api:"labrinth",version:3,method:"GET"})}async createServerProject(e){return this.client.request("/project",{api:"labrinth",version:3,method:"PUT",body:e})}async deleteProject(e){return this.client.request(`/project/${e}`,{api:"labrinth",version:3,method:"DELETE"})}async changeIcon(e,t,r){return this.client.request(`/project/${e}/icon`,{api:"labrinth",version:3,method:"PATCH",params:{ext:r},body:t})}async deleteIcon(e){return this.client.request(`/project/${e}/icon`,{api:"labrinth",version:3,method:"DELETE"})}async createGalleryImage(e,t,r){let n={ext:r.ext,featured:String(r.featured)};return r.name&&(n.name=r.name),r.description&&(n.description=r.description),r.ordering!==void 0&&(n.ordering=String(r.ordering)),this.client.request(`/project/${e}/gallery`,{api:"labrinth",version:3,method:"POST",params:n,body:t})}async deleteGalleryImage(e){return this.client.request("/project-gallery",{api:"labrinth",version:3,method:"DELETE",params:{url:e}})}async getDisclosures(e){return this.client.request(`/project/${e}/disclosures`,{api:"labrinth",version:3,method:"GET"})}async modifyDisclosures(e,t){return this.client.request(`/project/${e}/disclosures`,{api:"labrinth",version:3,method:"PATCH",body:t})}};var Re=class extends o{getModuleID(){return"labrinth_reports_v3"}async get(e){return this.client.request(`/report/${e}`,{api:"labrinth",version:3,method:"GET"})}async list(e){let t={};return e?.count!=null&&(t.count=String(e.count)),e?.offset!=null&&(t.offset=String(e.offset)),e?.all!=null&&(t.all=String(e.all)),this.client.request("/report",{api:"labrinth",version:3,method:"GET",params:Object.keys(t).length>0?t:void 0})}async getMultiple(e){return this.client.request(`/reports?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:3,method:"GET"})}async create(e){return this.client.request("/report",{api:"labrinth",version:3,method:"POST",body:e})}async edit(e,t){return this.client.request(`/report/${e}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async delete(e){return this.client.request(`/report/${e}`,{api:"labrinth",version:3,method:"DELETE"})}};var Te=class extends o{getModuleID(){return"labrinth_server_ping_internal"}async pingMinecraftJava(e){return this.client.request("/server-ping/minecraft-java",{api:"labrinth",version:"internal",method:"POST",body:e})}};var ke=class extends o{getModuleID(){return"labrinth_sessions_v2"}async list(){return this.client.request("/session/list",{api:"labrinth",version:2,method:"GET"})}async delete(e){return this.client.request(`/session/${e}`,{api:"labrinth",version:2,method:"DELETE"})}};var vt="YV97U1kk",yt="M4c3ITvd",Ot=60;function Ut(i,e){let t=i.slice();for(let r=t.length-1;r>0;r--){let n=Math.floor(Math.random()*(r+1)),s=t[r];t[r]=t[n],t[n]=s}return t.slice(0,e)}var xe=class extends o{getModuleID(){return"labrinth_state"}async fetchHomePageProjects(){let e=await this.client.labrinth.collections.get(vt),t=Ut(e.projects??[],Ot);return t.length===0?[]:this.client.labrinth.projects_v2.getMultiple(t)}async build(){let e=[],t=(h,kt,xt)=>(console.error("Error fetching state data:",h),e.push({endpoint:xt,error:h}),kt),[r,n,s,a,l,c,p,u,d,m,b,v,y,x]=await Promise.all([this.client.request("/tag/category",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/category")),this.client.request("/tag/loader",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/loader")),this.client.request("/tag/game_version",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/game_version")),this.client.request("/tag/donation_platform",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/donation_platform")),this.client.request("/tag/report_type",{api:"labrinth",version:2,method:"GET"}).catch(h=>t(h,[],"/v2/tag/report_type")),this.fetchHomePageProjects().catch(h=>t(h,[],`/v3/collection/${vt}`)),this.client.request("/search",{api:"labrinth",version:2,method:"GET",params:{limit:"3",query:"leave",index:"relevance"}}).catch(h=>t(h,{},"/v2/search")),this.client.request("/search",{api:"labrinth",version:2,method:"GET",params:{limit:"3",query:"",index:"updated"}}).catch(h=>t(h,{},"/v2/search")),this.client.labrinth.collections.get(yt).then(h=>h.projects??[]).catch(h=>t(h,[],`/v3/collection/${yt}`)),this.client.labrinth.billing_internal.getProducts().catch(h=>t(h,[],"/_internal/billing/products")),this.client.request("/mural/bank-details",{api:"labrinth",version:"internal",method:"GET"}).catch(h=>t(h,null,"/_internal/mural/bank-details")),this.client.iso3166.data.build().catch(h=>t(h,{countries:[],subdivisions:{}},"iso3166/data")),this.client.request("/payout/methods",{api:"labrinth",version:3,method:"GET"}).catch(h=>t(h,[],"/v3/payout/methods")),this.client.request("/globals",{api:"labrinth",version:"internal",method:"GET"}).catch(h=>t(h,null,"/_internal/globals"))]),E=Object.fromEntries(y.filter(h=>h.type==="tremendous").map(h=>[h.id,{name:h.name,image_url:h.image_logo_url}]));return{categories:r,loaders:n,gameVersions:s,donationPlatforms:a,reportTypes:l,homePageProjects:c,homePageSearch:p,homePageNotifs:u,prideProjectIds:d,products:m,muralBankDetails:b?.bankDetails??{},tremendousIdMap:E,countries:v.countries,subdivisions:v.subdivisions,taxComplianceThresholds:x?.tax_compliance_thresholds??{},errors:e}}};var we=class extends o{getModuleID(){return"labrinth_tech_review_internal"}async getRules(){return this.client.request("/moderation/tech-review/rules",{api:"labrinth",version:"internal",method:"GET"})}async getRuleSchema(){return this.client.request("/moderation/tech-review/rules/schema",{api:"labrinth",version:"internal",method:"GET"})}async getIssueTypeSchema(){return this.client.request("/delphi/issue_type/schema",{api:"labrinth",version:"internal",method:"GET"})}async getDetailRuleInput(e){return this.client.request(`/moderation/tech-review/rules/details/${e}/input`,{api:"labrinth",version:"internal",method:"GET"})}async getRuleAffectedDetails(e,t={}){return this.client.request(`/moderation/tech-review/rules/${e}/effects`,{api:"labrinth",version:"internal",method:"GET",params:t})}async testRule(e){return this.client.request("/moderation/tech-review/rules/test",{api:"labrinth",version:"internal",method:"POST",body:e})}async createRule(e){return this.client.request("/moderation/tech-review/rules",{api:"labrinth",version:"internal",method:"POST",body:e})}async updateRule(e,t){return this.client.request(`/moderation/tech-review/rules/${e}`,{api:"labrinth",version:"internal",method:"PUT",body:t})}async deleteRule(e){return this.client.request(`/moderation/tech-review/rules/${e}`,{api:"labrinth",version:"internal",method:"DELETE"})}async scanRules(e){return this.client.stream("/moderation/tech-review/rules/scan",{api:"labrinth",version:"internal",method:"POST",signal:e})}async searchProjects(e){return this.client.request("/moderation/tech-review/search",{api:"labrinth",version:"internal",method:"POST",body:e})}async getReport(e){return this.client.request(`/moderation/tech-review/report/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async getIssue(e,t={}){return this.client.request(`/moderation/tech-review/issue/${e}`,{api:"labrinth",version:"internal",method:"GET",params:t})}async updateIssueDetail(e,t){return this.updateIssueDetails([{detail_id:e,verdict:t.verdict}])}async updateIssueDetails(e){return this.client.request("/moderation/tech-review/issue-detail",{api:"labrinth",version:"internal",method:"PATCH",body:e})}async updateGlobalIssueDetails(e){return this.client.request("/moderation/tech-review/global-traces",{api:"labrinth",version:"internal",method:"POST",body:e})}async searchGlobalIssueDetails(e){return this.client.request("/moderation/tech-review/global-traces/search",{api:"labrinth",version:"internal",method:"POST",body:e})}async getGlobalIssueDetail(e){return this.client.request("/moderation/tech-review/global-traces/local-traces",{api:"labrinth",version:"internal",method:"POST",body:e})}async submitProject(e,t){return this.client.request(`/moderation/tech-review/submit/${e}`,{api:"labrinth",version:"internal",method:"POST",body:t})}async getProjectReport(e){return this.client.request(`/moderation/tech-review/project/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async getUsersFlaggedProjects(e){return this.client.request("/moderation/tech-review/users/flagged-projects",{api:"labrinth",version:"internal",method:"GET",params:{ids:JSON.stringify(e)}})}async getOrganizationFlaggedProjects(e){return this.client.request(`/moderation/tech-review/organization/${e}/flagged-projects`,{api:"labrinth",version:"internal",method:"GET"})}};var Le=class extends o{getModuleID(){return"labrinth_threads_v3"}async getThread(e){return this.client.request(`/thread/${e}`,{api:"labrinth",version:3,method:"GET"})}async getMultiple(e){return this.client.request(`/threads?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:3,method:"GET"})}async sendMessage(e,t){return this.client.request(`/thread/${e}`,{api:"labrinth",version:3,method:"POST",body:t,retry:!1})}async createIssues(e,t){return this.client.request(`/thread/${e}/issue`,{api:"labrinth",version:3,method:"PUT",body:t,retry:!1})}async editIssueFacet(e,t){return this.client.request(`/thread/issue/facet/${e}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async user_addressed(e){return this.editIssueFacet(e,{user_addressed:!0})}async moderator_verified(e){return this.editIssueFacet(e,{moderator_verified:!0})}async deleteMessage(e){return this.client.request(`/message/${e}`,{api:"labrinth",version:3,method:"DELETE"})}};var qe=class extends o{getModuleID(){return"labrinth_users_v2"}async get(e){return this.client.request(`/user/${e}`,{api:"labrinth",version:2,method:"GET"})}async getMultiple(e){return this.client.request(`/users?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:2,method:"GET"})}async getProjects(e){return this.client.request(`/user/${e}/projects`,{api:"labrinth",version:2,method:"GET"})}async getOrganizations(e){return this.client.request(`/user/${e}/organizations`,{api:"labrinth",version:3,method:"GET"})}async getCollections(e){return this.client.request(`/user/${e}/collections`,{api:"labrinth",version:3,method:"GET"})}async getNotifications(e){return this.client.request(`/user/${e}/notifications`,{api:"labrinth",version:2,method:"GET"})}async getFollowedProjects(e){return this.client.request(`/user/${e}/follows`,{api:"labrinth",version:2,method:"GET"})}async patch(e,t){return this.client.request(`/user/${e}`,{api:"labrinth",version:2,method:"PATCH",body:t})}async changeIcon(e,t,r){return this.client.request(`/user/${e}/icon`,{api:"labrinth",version:2,method:"PATCH",params:{ext:r},body:t})}async deleteIcon(e){return this.client.request(`/user/${e}/icon`,{api:"labrinth",version:2,method:"DELETE"})}};var Ce=class extends o{getModuleID(){return"labrinth_users_v3"}async getAuthenticated(){return this.client.request("/user",{api:"labrinth",version:3,method:"GET"})}async get(e){return this.client.request(`/user/${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"GET"})}async getPreferences(e){return this.client.request(`/user/${encodeURIComponent(e)}/preferences`,{api:"labrinth",version:3,method:"GET"})}async patchPreferences(e,t){return this.client.request(`/user/${encodeURIComponent(e)}/preferences`,{api:"labrinth",version:3,method:"PATCH",body:t})}async search(e){return this.client.request(`/users/search?query=${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"GET"})}async getProjects(e){return this.client.request(`/user/${encodeURIComponent(e)}/projects`,{api:"labrinth",version:3,method:"GET"})}async getFollowedProjects(e){return this.client.request(`/user/${encodeURIComponent(e)}/follows`,{api:"labrinth",version:3,method:"GET"})}async getAllProjects(e){return this.client.request(`/user/${encodeURIComponent(e)}/all-projects`,{api:"labrinth",version:3,method:"GET"})}};var Ie=class extends o{getModuleID(){return"labrinth_versions_v2"}async getProjectVersions(e,t){let r={};return t?.game_versions?.length&&(r.game_versions=JSON.stringify(t.game_versions)),t?.loaders?.length&&(r.loaders=JSON.stringify(t.loaders)),t?.include_changelog===!1&&(r.include_changelog="false"),t?.limit!=null&&(r.limit=String(t.limit)),t?.offset!=null&&(r.offset=String(t.offset)),this.client.request(`/project/${e}/version`,{api:"labrinth",version:2,method:"GET",params:Object.keys(r).length>0?r:void 0})}async getVersion(e){return this.client.request(`/version/${e}`,{api:"labrinth",version:2,method:"GET"})}async getVersionFromFileHash(e,t){return this.client.request(`/version_file/${e}`,{api:"labrinth",version:2,method:"GET",params:{algorithm:t}})}async getVersions(e,t){return this.client.request("/versions",{api:"labrinth",version:2,method:"GET",params:{ids:JSON.stringify(e),...t?.include_changelog===!1?{include_changelog:"false"}:{}}})}async getVersionFromIdOrNumber(e,t){return this.client.request(`/project/${e}/version/${t}`,{api:"labrinth",version:2,method:"GET"})}async deleteVersion(e){return this.client.request(`/version/${e}`,{api:"labrinth",version:2,method:"DELETE"})}};var ft=1800*1e3,Me=class extends o{getModuleID(){return"labrinth_versions_v3"}async getProjectVersions(e,t){let r={};return t?.game_versions?.length&&(r.game_versions=JSON.stringify(t.game_versions)),t?.loaders?.length&&(r.loaders=JSON.stringify(t.loaders)),t?.include_changelog===!1&&(r.include_changelog="false"),t?.limit!=null&&(r.limit=String(t.limit)),t?.offset!=null&&(r.offset=String(t.offset)),this.client.request(`/project/${e}/version`,{api:"labrinth",version:t?.apiVersion??2,method:"GET",params:Object.keys(r).length>0?r:void 0})}async getVersion(e){return this.client.request(`/version/${e}`,{api:"labrinth",version:3,method:"GET"})}async getVersions(e){return this.client.request("/versions",{api:"labrinth",version:3,method:"GET",params:{ids:JSON.stringify(e)}})}async getVersionFromIdOrNumber(e,t){return this.client.request(`/project/${e}/version/${t}`,{api:"labrinth",version:3,method:"GET"})}createVersion(e,t,r=null){let n=new FormData,s=t.map(u=>u.file),a=t.map(u=>u.fileType||null),l=s.map((u,d)=>`${u.name}-${d===0?"primary":d}`),c=l.reduce((u,d,m)=>(u[d]=a[m],u),{}),p={project_id:e.project_id,version_number:e.version_number,name:e.name||e.version_number,changelog:e.changelog,dependencies:e.dependencies||[],game_versions:e.game_versions,version_type:e.version_type,featured:!!e.featured,file_parts:l,file_types:c,primary_file:l[0],environment:e.environment,loaders:e.loaders};return r==="modpack"&&(p.mrpack_loaders=e.loaders,p.loaders=["mrpack"]),n.append("data",JSON.stringify(p)),s.forEach((u,d)=>{n.append(l[d],u,u.name)}),this.client.upload("/version",{api:"labrinth",version:3,formData:n,timeout:ft})}async modifyVersion(e,t){return this.client.request(`/version/${e}`,{api:"labrinth",version:3,method:"PATCH",body:t})}async deleteVersion(e){return this.client.request(`/version/${e}`,{api:"labrinth",version:2,method:"DELETE"})}addFilesToVersion(e,t){let r=new FormData,n=t.map(c=>c.file),s=t.map(c=>c.fileType||null),a=n.map((c,p)=>`${c.name}-${p}`),l=a.reduce((c,p,u)=>(c[p]=s[u],c),{});return r.append("data",JSON.stringify({file_types:l})),n.forEach((c,p)=>{r.append(a[p],c,c.name)}),this.client.upload(`/version/${e}/file`,{api:"labrinth",version:2,formData:r,timeout:ft})}};var $e=class extends o{getModuleID(){return"labrinth_affiliate_internal"}async getAll(){return this.client.request("/affiliate",{api:"labrinth",version:"internal",method:"GET"})}async create(e){return this.client.request("/affiliate",{api:"labrinth",version:"internal",method:"PUT",body:e})}async get(e){return this.client.request(`/affiliate/${e}`,{api:"labrinth",version:"internal",method:"GET"})}async delete(e){return this.client.request(`/affiliate/${e}`,{api:"labrinth",version:"internal",method:"DELETE"})}async patch(e,t){return this.client.request(`/affiliate/${e}`,{api:"labrinth",version:"internal",method:"PATCH",body:t})}};var Oe=class extends o{getModuleID(){return"labrinth_blocked_users_internal"}async getStatus(e,t){return this.client.request(`/block/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{api:"labrinth",version:"internal",method:"GET"})}};var Ue=class extends o{getModuleID(){return"labrinth_blocked_users_v3"}async list(){return this.client.request("/blocks",{api:"labrinth",version:3,method:"GET"})}async block(e){return this.client.request(`/block/${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"POST"})}async unblock(e){return this.client.request(`/block/${encodeURIComponent(e)}`,{api:"labrinth",version:3,method:"DELETE"})}};var De=class extends o{getModuleID(){return"labrinth_campaign_internal"}async getPride26(){return this.client.request("/campaign/pride-26",{api:"labrinth",version:"internal",method:"GET",skipAuth:!0})}};var je=class extends o{getModuleID(){return"labrinth_tags_v2"}async getLicenses(){return this.client.request("/tag/license",{api:"labrinth",version:2,method:"GET"})}async getLicenseText(e){return this.client.request(`/tag/license/${e}`,{api:"labrinth",version:2,method:"GET"})}};var Ne=class extends o{getModuleID(){return"labrinth_teams_v2"}async addMember(e,t){return this.client.request(`/team/${e}/members`,{api:"labrinth",version:2,method:"POST",body:t})}async editMember(e,t,r){return this.client.request(`/team/${e}/members/${t}`,{api:"labrinth",version:2,method:"PATCH",body:r})}async removeMember(e,t){return this.client.request(`/team/${e}/members/${t}`,{api:"labrinth",version:2,method:"DELETE"})}async transferOwnership(e,t){return this.client.request(`/team/${e}/owner`,{api:"labrinth",version:2,method:"PATCH",body:t})}};var Fe=class extends o{getModuleID(){return"labrinth_teams_v3"}async getMultiple(e){return this.client.request(`/teams?ids=${encodeURIComponent(JSON.stringify(e))}`,{api:"labrinth",version:3,method:"GET"})}};var Dt="https://launcher-meta.modrinth.com",Be=class extends o{getModuleID(){return"launchermeta_manifest_v0"}async getManifest(e,t=0){return this.client.request("/manifest.json",{api:Dt,version:`${e}/v${t}`,method:"GET",skipAuth:!0,headers:{"Content-Type":""}})}};var Ge=class extends o{getModuleID(){return"mclogs_insights_v1"}async analyse(e){return this.client.request("/analyse",{api:"https://api.mclo.gs",version:"1",method:"POST",body:new URLSearchParams({content:e}),headers:{"Content-Type":"application/x-www-form-urlencoded"},skipAuth:!0})}};var We=class extends o{getModuleID(){return"mclogs_logs_v1"}async create(e){return this.client.request("/log",{api:"https://api.mclo.gs",version:"1",method:"POST",body:new URLSearchParams({content:e}),headers:{"Content-Type":"application/x-www-form-urlencoded"},skipAuth:!0})}};var Pt="https://fill.papermc.io",Ve=class extends o{getModuleID(){return"paper_versions_v3"}async getProject(){return this.client.request("/projects/paper",{api:Pt,version:"v3",method:"GET",skipAuth:!0})}async getBuilds(e){return{builds:await this.client.request(`/projects/paper/versions/${e}/builds`,{api:Pt,version:"v3",method:"GET",skipAuth:!0})}}};var St="https://api.purpurmc.org",He=class extends o{getModuleID(){return"purpur_versions_v2"}async getProject(){return this.client.request("/purpur",{api:St,version:"v2",method:"GET",skipAuth:!0})}async getBuilds(e){return this.client.request(`/purpur/${e}`,{api:St,version:"v2",method:"GET",skipAuth:!0})}};var ze=class extends o{getModuleID(){return"sharedinstances_instances_v1"}async get(e){return this.client.request(`/instances/${encodeURIComponent(e)}`,{api:"sharedinstances",version:1,method:"GET"})}async getForUser(e){return this.client.request("/instances",{api:"sharedinstances",version:1,method:"GET",params:{user:e}})}async getUsers(e){return this.client.request(`/instances/${encodeURIComponent(e)}/users`,{api:"sharedinstances",version:1,method:"GET"})}async getLatestVersion(e){return this.client.request(`/instances/${encodeURIComponent(e)}/versions`,{api:"sharedinstances",version:1,method:"GET"})}async getVersion(e,t){return this.client.request(`/instances/${encodeURIComponent(e)}/versions/${t}`,{api:"sharedinstances",version:1,method:"GET"})}};var Ke=class extends o{getModuleID(){return"sharedinstances_invites_v1"}async get(e){return this.client.request(`/invites/${encodeURIComponent(e)}`,{api:"sharedinstances",version:1,method:"GET",skipAuth:!0,retry:!1})}};var Je=class extends o{getModuleID(){return"sharedinstances_moderation_v1"}async blacklistUsers(e){return this.client.request("/moderation/blacklist",{api:"sharedinstances",version:1,method:"POST",body:e})}async unblacklistUsers(e){return this.client.request("/moderation/blacklist",{api:"sharedinstances",version:1,method:"DELETE",body:e})}async deleteFile(e,t,r){return this.client.request(`/moderation/instances/${encodeURIComponent(e)}/versions/${t}/files/${encodeURIComponent(r)}`,{api:"sharedinstances",version:1,method:"DELETE"})}};var Qe=class extends o{getModuleID(){return"sharedinstances_users_v1"}async getBlacklistStatus(e){return this.client.request(`/blacklist/${encodeURIComponent(e)}`,{api:"sharedinstances",version:1,method:"GET"})}};var jt={archon_actions_v1:U,archon_backups_queue_v1:j,archon_backups_v1:D,archon_content_v1:N,archon_nodes_internal:F,archon_notices_v0:B,archon_options_v1:G,archon_properties_v1:W,archon_server_users_v1:V,archon_servers_internal:H,archon_servers_v0:z,archon_servers_v1:K,archon_transfers_internal:J,iso3166_data:Q,mclogs_insights_v1:Ge,mclogs_logs_v1:We,launchermeta_manifest_v0:Be,kyros_content_v1:X,kyros_files_v0:Y,kyros_files_v1:Z,kyros_logs_v1:ee,kyros_upload_sessions_v1:te,labrinth_affiliate_internal:$e,labrinth_analytics_internal:re,labrinth_analytics_v3:ne,labrinth_auth_internal:se,labrinth_auth_v2:oe,labrinth_attribution_internal:ie,labrinth_billing_internal:ae,labrinth_blocked_users_internal:Oe,labrinth_blocked_users_v3:Ue,labrinth_campaign_internal:De,labrinth_collections:le,labrinth_content_v3:ce,labrinth_external_projects_internal:ue,labrinth_friends_v3:pe,labrinth_geoip:de,labrinth_globals_internal:he,labrinth_images_v3:me,labrinth_moderation_internal:be,labrinth_notifications_v2:ve,labrinth_oauth_internal:ye,labrinth_organizations_v3:fe,labrinth_pats_v2:Pe,labrinth_limits_v3:ge,labrinth_payout_v3:Se,labrinth_payouts_v3:Ae,labrinth_projects_v2:_e,labrinth_projects_v3:Ee,labrinth_reports_v3:Re,labrinth_server_ping_internal:Te,labrinth_sessions_v2:ke,labrinth_state:xe,labrinth_tags_v2:je,labrinth_teams_v2:Ne,labrinth_teams_v3:Fe,labrinth_tech_review_internal:we,labrinth_threads_v3:Le,labrinth_users_v2:qe,labrinth_users_v3:Ce,labrinth_versions_v2:Ie,labrinth_versions_v3:Me,paper_versions_v3:Ve,purpur_versions_v2:He,sharedinstances_invites_v1:Ke,sharedinstances_instances_v1:ze,sharedinstances_moderation_v1:Je,sharedinstances_users_v1:Qe};function Nt(i){let e=i.split("_");if(e.length<2)throw new Error(`Invalid module ID "${i}". Expected format: <api>_<module> (e.g., "labrinth_projects_v2")`);let t=e[0],r=e.slice(1).join("_");return[t,r]}function At(){let i={};for(let[e,t]of Object.entries(jt)){let[r,n]=Nt(e);i[r]||(i[r]={}),i[r][n]=t}return i}var q=class{};var C=class extends q{constructor(t){super();this._moduleInstances=new Map;this._moduleNamespaces=new Map;this.config={timeout:1e4,labrinthBaseUrl:"https://api.modrinth.com",archonBaseUrl:"https://archon.modrinth.com",sharedInstancesBaseUrl:"https://shared-instances.modrinth.com",...t},this.features=t.features??[],this.initializeModules()}initializeModules(){let t=At();for(let[r,n]of Object.entries(t)){let s={};for(let[a,l]of Object.entries(n)){let c=`${r}_${a}`;Object.defineProperty(s,a,{get:()=>{if(!this._moduleInstances.has(c)){let p=new l(this),u=p.getModuleID();if(u!==c)throw new Error(`Module ID mismatch: registry expects "${c}" but module declares "${u}"`);this._moduleInstances.set(c,p)}return this._moduleInstances.get(c)},enumerable:!0,configurable:!1})}Object.defineProperty(this,r,{value:s,writable:!1,enumerable:!0,configurable:!1}),this._moduleNamespaces.set(r,s)}}async request(t,r){let n;r.api==="labrinth"?n=this.resolveBaseUrl(this.config.labrinthBaseUrl):r.api==="archon"?n=this.resolveBaseUrl(this.config.archonBaseUrl):r.api==="sharedinstances"?n=this.resolveBaseUrl(this.config.sharedInstancesBaseUrl):n=r.api;let s=this.buildUrl(t,n,r.version),a=await this.buildDefaultHeaders(),l={method:"GET",timeout:this.config.timeout,...r,headers:{...a,...r.headers}};this.attachArchonSentryCaptureHeader(l);let c=l.headers;c&&"Content-Type"in c&&c["Content-Type"]===""&&delete c["Content-Type"];let p=this.buildContext(s,t,l);try{let u=await this.executeFeatureChain(p);return await this.config.hooks?.onResponse?.(u,p),u}catch(u){let d=this.normalizeError(u,p);throw d.url??(d.url=p.url),await this.config.hooks?.onError?.(d,p),d}}async stream(t,r){let n;r.api==="labrinth"?n=this.resolveBaseUrl(this.config.labrinthBaseUrl):r.api==="archon"?n=this.resolveBaseUrl(this.config.archonBaseUrl):r.api==="sharedinstances"?n=this.resolveBaseUrl(this.config.sharedInstancesBaseUrl):n=r.api;let s=this.buildUrl(t,n,r.version),a=await this.buildDefaultHeaders(),l={method:"GET",retry:!1,circuitBreaker:!1,...r,headers:{...a,Accept:"text/event-stream",...r.headers}};this.attachArchonSentryCaptureHeader(l);let c=this.buildContext(s,t,l);try{return await this.executeFeatureChain(c,()=>this.executeStreamRequest(c.url,c.options))}catch(p){let u=this.normalizeError(p,c);throw u.url??(u.url=c.url),await this.config.hooks?.onError?.(u,c),u}}async executeFeatureChain(t,r=()=>this.executeRequest(t.url,t.options)){let n=this.features.filter(l=>l.shouldApply(t)),s=n.length,a=async()=>(s--,s>=0?n[s].execute(a,t):(await this.config.hooks?.onRequest?.(t),r()));return a()}async executeUploadFeatureChain(t,r,n){let s=this.features.filter(c=>c.shouldApply(t)),a=s.length,l=async()=>(a--,a>=0?s[a].execute(l,t):(await this.config.hooks?.onRequest?.(t),this.executeXHRUpload(t,r,n)));return l()}buildUrl(t,r,n){let s=r.replace(/\/$/,""),a="";n==="internal"?a="/_internal":typeof n=="number"?a=`/v${n}`:typeof n=="string"&&(a=`/${n}`);let l=t.startsWith("/")?t:`/${t}`;return`${s}${a}${l}`}resolveBaseUrl(t){return typeof t=="function"?t():t}buildContext(t,r,n){return{url:t,path:r,options:n,attempt:1,startTime:Date.now()}}buildUploadContext(t,r,n){let s,a;if("formData"in n&&n.formData)s={isUpload:!0,formData:n.formData,onProgress:n.onProgress},a=n.formData;else if("file"in n&&n.file)s={isUpload:!0,file:n.file,onProgress:n.onProgress},a=n.file;else throw new Error("Upload options must include either file or formData");return{url:t,path:r,options:{...n,method:"POST",body:a},attempt:1,startTime:Date.now(),metadata:s}}async buildDefaultHeaders(){let t={"Content-Type":"application/json",...this.config.headers},r=await this.resolveUserAgent();return r&&(t["User-Agent"]=r),t}async resolveUserAgent(){let t=this.config.userAgent;return typeof t=="function"?await t():t}attachArchonSentryCaptureHeader(t){t.api!=="archon"||!t.headers||!this.shouldCaptureArchonRequests()||(t.headers["modrinth-sentry-capture"]="1")}shouldCaptureArchonRequests(){let t=this.config.archonSentryCapture;return typeof t=="function"?t():t===!0}normalizeError(t,r){return t instanceof g?t:g.fromUnknown(t,r?.path)}createNormalizedError(t,r,n){return r&&n?L.fromResponse(r,n):new g(t.message,{statusCode:r,originalError:t,responseData:n})}addFeature(t){return this.features.push(t),this}removeFeature(t){let r=this.features.indexOf(t);return r!==-1&&this.features.splice(r,1),this}getFeatures(){return[...this.features]}};var f=class{constructor(e){this.config={enabled:!0,...e}}shouldApply(e){return this.config.enabled!==!1}get name(){return this.config.name??this.constructor.name}get enabled(){return this.config.enabled!==!1}};var I=class{constructor(e){this.client=e;this.connections=new Map}on(e,t,r){let n=this.getEventKey(e,t),s=r;return this.emitter.on(n,s),()=>{this.emitter.off(n,s)}}onAny(e,t){let r=this.getAnyEventKey(e),n=t;return this.emitter.on(r,n),()=>{this.emitter.off(r,n)}}onStatus(e,t){let r=this.getStatusEventKey(e),n=t;return this.emitter.on(r,n),()=>{this.emitter.off(r,n)}}getStatus(e){let t=this.connections.get(e);return t?this.connectionToStatus(t):null}emitSyncEvent(e,t){this.emitter.emit(this.getEventKey(e,t.type),t),this.emitter.emit(this.getAnyEventKey(e),t)}updateStatus(e,t,r){e.status=t,e.error=r,this.emitter.emit(this.getStatusEventKey(e.serverId),this.connectionToStatus(e))}clearListeners(e){this.emitter.all.forEach((t,r)=>{r.toString().startsWith(`${e}:`)&&this.emitter.all.delete(r)})}connectionToStatus(e){return{state:e.status,connected:e.status==="connected",reconnecting:e.status==="reconnecting",reconnectAttempts:e.reconnectAttempts,retryDelay:e.retryDelay,lastEventId:e.lastEventId,error:e.error}}getEventKey(e,t){return`${e}:${t}`}getAnyEventKey(e){return`${e}:*`}getStatusEventKey(e){return`${e}:__status`}};var M=class{constructor(e){this.client=e;this.connections=new Map;this.MAX_RECONNECT_ATTEMPTS=10;this.RECONNECT_BASE_DELAY=1e3;this.RECONNECT_MAX_DELAY=3e4;this.AUTHENTICATION_TIMEOUT=3e4}async safeConnect(e,t){let r=this.getStatus(e);if(r?.connected&&!t?.force)return;if(r&&!r.connected&&!t?.force){await this.waitForAuthentication(e);return}t?.force&&r&&this.disconnect(e);let n=await this.client.archon.servers_v0.getWebSocketAuth(e);await this.connect(e,n)}async waitForAuthentication(e){await new Promise((t,r)=>{let n=()=>{},s=setTimeout(()=>{n(),r(new Error(`WebSocket authentication timed out for server ${e}`))},this.AUTHENTICATION_TIMEOUT);n=this.on(e,"auth-ok",()=>{clearTimeout(s),n(),t()}),this.getStatus(e)?.connected&&(clearTimeout(s),n(),t())})}on(e,t,r){let n=`${e}:${t}`;return this.emitter.on(n,r),()=>{this.emitter.off(n,r)}}getStatus(e){let t=this.connections.get(e);return t?{connected:t.socket.readyState===WebSocket.OPEN&&t.authenticated,reconnecting:t.isReconnecting,reconnectAttempts:t.reconnectAttempts}:null}getReconnectDelay(e){return Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,e),this.RECONNECT_MAX_DELAY)+Math.random()*1e3}};var et=class extends f{async execute(e,t){let r=await this.getToken();if(r){let n=this.config.headerName??"Authorization",s=this.config.tokenPrefix??"Bearer",a=s?`${s} ${r}`:r;t.options.headers={...t.options.headers,[n]:a}}return e()}shouldApply(e){if(e.options.skipAuth)return!1;let t=this.config.headerName??"Authorization";return e.options.headers?.[t]?!1:super.shouldApply(e)}async getToken(){let{token:e}=this.config;return typeof e=="function"?await e():e}};var Xe=class{constructor(){this.state=new Map}get(e){return this.state.get(e)}set(e,t){this.state.set(e,t)}clear(e){this.state.delete(e)}},tt=class extends f{constructor(e){super(e),this.config={enabled:!0,name:"circuit-breaker",maxFailures:3,resetTimeout:3e4,failureStatusCodes:[500,502,503,504],...e},this.storage=e?.storage??new Xe}async execute(e,t){let r=this.getCircuitKey(t);if(this.isCircuitOpen(r))throw new g("Circuit breaker open - too many recent failures",{statusCode:503,context:t.path});try{let n=await e();return this.recordSuccess(r),n}catch(n){throw this.isFailureError(n)&&this.recordFailure(r),n}}shouldApply(e){return e.options.circuitBreaker===!1?!1:super.shouldApply(e)}getCircuitKey(e){if(this.config.getCircuitKey)return this.config.getCircuitKey(e.url,e.options.method??"GET");let t=e.options.method??"GET",r=e.path.split("?")[0];return`${t}_${r}`}isCircuitOpen(e){let t=this.storage.get(e);return t?Date.now()-t.lastFailure>this.config.resetTimeout?(this.storage.clear?.(e),!1):t.failures>=this.config.maxFailures:!1}recordSuccess(e){this.storage.clear?.(e)}recordFailure(e){let t=Date.now(),r=this.storage.get(e);r?this.storage.set(e,{failures:r.failures+1,lastFailure:t}):this.storage.set(e,{failures:1,lastFailure:t})}isFailureError(e){return e instanceof g&&e.statusCode?this.config.failureStatusCodes.includes(e.statusCode):!1}getCircuitState(e){return this.storage.get(e)}resetCircuit(e){this.storage.clear?.(e)}};var rt=class extends f{constructor(){super(...arguments);this.refreshPromise=null}shouldApply(t){return t.options.useNodeAuth===!0&&this.config.enabled!==!1}async refreshAuthWithLock(){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=this.config.refreshAuth().finally(()=>{this.refreshPromise=null}),this.refreshPromise)}async execute(t,r){let s=0,a=this.config.getAuth();if((!a||this.isTokenExpired(a.token))&&(await this.refreshAuthWithLock(),a=this.config.getAuth()),!a)throw new Error("Failed to obtain node authentication");for(this.applyAuth(r,a);;)try{return await t()}catch(l){if(l instanceof g&&l.statusCode===401){if(s++,s>=3)throw new Error("Node authentication failed after 3 retries. Please re-authenticate.");if(await this.refreshAuthWithLock(),a=this.config.getAuth(),!a)throw new Error("Failed to refresh node authentication");this.applyAuth(r,a);continue}throw l}}applyAuth(t,r){let n=P(r.url);t.url=this.buildUrl(t.path,n,t.options.version),t.options.headers={...t.options.headers,Authorization:`Bearer ${r.token}`},t.options.skipAuth=!0}buildUrl(t,r,n){let s=r.replace(/\/$/,""),a="";n==="internal"?a="/_internal":typeof n=="number"?a=`/v${n}`:typeof n=="string"&&(a=`/${n}`);let l=t.startsWith("/")?t:`/${t}`;return`${s}${a}${l}`}isTokenExpired(t){try{let r=JSON.parse(atob(t.split(".")[1]));if(!r.exp)return!1;let n=r.exp*1e3;return Date.now()>=n-1e4}catch{return!1}}};var _t=1,nt=class extends f{async execute(e,t){return t.options.headers={...t.options.headers,"X-Panel-Version":String(_t)},e()}shouldApply(e){return e.options.api==="labrinth"||e.options.api==="archon"}};var it=class extends f{constructor(e){super(e),this.config={enabled:!0,name:"retry",maxAttempts:3,backoffStrategy:"exponential",initialDelay:1e3,maxDelay:15e3,retryableStatusCodes:[408,429,500,502,503,504],retryOnNetworkError:!0,...e}}async execute(e,t){let r=null,n=this.getMaxAttempts(t);for(let s=1;s<=n;s++){t.attempt=s;try{return await e()}catch(a){if(r=a,!this.shouldRetryError(a,s,n)||s>=n)throw a;let c=this.calculateDelay(s);console.warn(`[${this.name}] Retrying request to ${t.path} (attempt ${s+1}/${n}) after ${c}ms`),await this.sleep(c)}}throw r??new Error("Max retry attempts reached")}shouldApply(e){return e.options.retry===!1?!1:super.shouldApply(e)}shouldRetryError(e,t,r){return this.config.shouldRetry?this.config.shouldRetry(e,t):this.config.retryOnNetworkError&&this.isNetworkError(e)?!0:e instanceof g&&e.statusCode?this.config.retryableStatusCodes.includes(e.statusCode):!1}isNetworkError(e){let t=[/network/i,/timeout/i,/ECONNREFUSED/i,/ENOTFOUND/i,/ETIMEDOUT/i,/ECONNRESET/i],r=e instanceof Error?e.message:String(e);return t.some(n=>n.test(r))}getMaxAttempts(e){return typeof e.options.retry=="number"?e.options.retry:this.config.maxAttempts}calculateDelay(e){let{backoffStrategy:t,initialDelay:r,maxDelay:n}=this.config,s;switch(t){case"exponential":s=r*Math.pow(2,e-1);break;case"linear":s=r*e;break;case"constant":s=r;break;default:s=r}return s+=Math.random()*1e3,Math.min(s,n)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var st=class extends f{async execute(e,t){let r=t.options.method??"GET",n=t.options.api,s=t.options.version,a=`[${r}] [${n}_v${s}]`;console.debug(`${a} ${t.url} SENT`);try{let l=await e();try{let c=l?JSON.stringify(l).length:0;console.debug(`${a} ${t.url} RECEIVED ${c} bytes`)}catch{console.debug(`${a} ${t.url} RECEIVED`)}return l}catch(l){let c=Ft(l);throw console.debug(`${a} ${t.url} FAILED${c?` \u2014 ${c}`:""}`),l}}};function Ft(i){if(!i||typeof i!="object")return typeof i=="string"?i:"";let e=i,t=e.status??e.statusCode??e.response?.status,r=e.statusText??e.response?.statusText,n=e.responseData??e.data??e.response?._data,s=[];return t!==void 0&&s.push(r?`${t} ${r}`:String(t)),n!==void 0?s.push(`body: ${Bt(n)}`):e.message&&s.push(e.message),s.join(" ")}function Bt(i){if(typeof i=="string")return i;try{return JSON.stringify(i)}catch{return String(i)}}var Et;(e=>{let i;(r=>{let t;(s=>s.UserScope={NONE:"",SERVER_ADMIN:"SERVER_ADMIN",BASE_READ:"BASE_READ",POWER_ACTIONS:"POWER_ACTIONS",EXEC_COMMANDS:"EXEC_COMMANDS",FILES_WRITE:"FILES_WRITE",SETUP:"SETUP",BACKUPS:"BACKUPS",ADVANCED:"ADVANCED",RESET_SERVER:"RESET_SERVER",MANAGE_USERS:"MANAGE_USERS",SUPPORT_AGENT:"SUPPORT_AGENT",INFRA_MANAGER:"INFRA_MANAGER",INFRA_MANAGER_READ:"INFRA_MANAGER_READ",INFRA_SERVERS_XFER:"INFRA_SERVERS_XFER",INFRA_USERS:"INFRA_USERS"})(t=r.v1||(r.v1={}))})(i=e.ServerUsers||(e.ServerUsers={}))})(Et||(Et={}));import{$fetch as zt,FetchError as Kt}from"ofetch";function R(i,e){if(!e)return i;let t={};for(let[n,s]of Object.entries(e))s!=null&&(t[n]=String(s));let r=new URLSearchParams(t).toString();return r?`${i}${i.includes("?")?"&":"?"}${r}`:i}function T(i){if(i)return typeof i=="object"&&!(i instanceof FormData)&&!(i instanceof URLSearchParams)&&!(i instanceof Blob)&&!(i instanceof ArrayBuffer)&&!ArrayBuffer.isView(i)?JSON.stringify(i):i}async function k(i){let e=i.headers.get("content-type")?.toLowerCase()??"";try{if(e.includes("application/json")||e.includes("+json"))return await i.json();let t=await i.text();if(!t)return;try{return JSON.parse(t)}catch{return t}}catch{return}}import Gt from"mitt";var $=class{constructor(){this.buffer="";this.eventName="";this.data=""}feed(e){this.buffer+=e;let t=[];for(;;){let r=this.findLineEnd();if(!r)break;let{line:n,length:s}=r;this.buffer=this.buffer.slice(s),this.processLine(n,t)}return t}end(){let e=[];return this.buffer.length>0&&(this.processLine(this.buffer.endsWith("\r")?this.buffer.slice(0,-1):this.buffer,e),this.buffer=""),this.dispatch(e),e}findLineEnd(){let e=this.buffer.indexOf(`
6
6
  `),t=this.buffer.indexOf("\r");if(e===-1&&t===-1)return null;if(t!==-1&&(e===-1||t<e)){if(t===this.buffer.length-1)return null;let r=this.buffer[t+1]===`
7
7
  `?t+2:t+1;return{line:this.buffer.slice(0,t),length:r}}return{line:this.buffer.slice(0,e),length:e+1}}processLine(e,t){if(e===""){this.dispatch(t);return}if(e.startsWith(":"))return;let r=e.indexOf(":"),n=r===-1?e:e.slice(0,r),s=r===-1?"":e.slice(r+1);switch(s.startsWith(" ")&&(s=s.slice(1)),n){case"event":this.eventName=s;break;case"data":this.data+=`${s}
8
8
  `;break;case"id":this.id=s;break;case"retry":{let a=Number(s);Number.isInteger(a)&&a>=0&&t.push({kind:"retry",retry:a});break}}}dispatch(e){if(!this.data){this.eventName="",this.id=void 0;return}e.push({kind:"event",id:this.id,event:this.eventName||void 0,data:this.data.endsWith(`
9
- `)?this.data.slice(0,-1):this.data}),this.eventName="",this.data="",this.id=void 0}};function ot(i){let e;try{e=JSON.parse(i)}catch{return null}return!e||typeof e!="object"||typeof e.type!="string"?null:e}var Wt=1e3,Rt=3e4,Vt=1e3,S=class extends I{constructor(){super(...arguments);this.emitter=Gt()}async safeConnectServer(t,r={}){let n=this.connections.get(t);if(n&&!r.force&&!n.stopped&&n.status!=="disconnected")return;n&&this.closeConnection(t);let s={serverId:t,intent:r.intent??"all",reconnectAttempts:0,retryDelay:Wt,stopped:!1,status:"idle"};this.connections.set(t,s),this.runConnection(s)}disconnect(t){this.closeConnection(t),this.clearListeners(t)}disconnectAll(){for(let t of this.connections.keys())this.disconnect(t)}async runConnection(t){for(;!t.stopped;){let r=t.status==="connected";this.updateStatus(t,r?"reconnecting":"connecting");let n=new AbortController;t.controller=n;let s;try{let a=await this.client.stream("/sync",{api:"archon",version:1,method:"GET",params:{scope:`server:${t.serverId}`,intent:this.intentToParam(t.intent)},headers:t.lastEventId?{"Last-Event-Id":t.lastEventId}:void 0,signal:n.signal,retry:!1,circuitBreaker:!1});if(t.stopped)return;t.reconnectAttempts=0,this.updateStatus(t,"connected"),s=await this.consumeStream(t,a)}catch(a){if(t.stopped||this.isAbortError(a))return;t.reconnectAttempts++,this.updateStatus(t,"error",a),console.warn(`[Sync] Connection failed for server ${t.serverId}:`,a)}finally{n.abort(),t.controller=void 0}if(t.stopped)return;if(s==="protocol-reconnect"){t.reconnectAttempts=0;continue}await this.waitForReconnect(t)}}async consumeStream(t,r){let n=r.getReader(),s=new TextDecoder,a=new O;try{for(;!t.stopped;){let{done:u,value:d}=await n.read();if(u)break;let m=s.decode(d,{stream:!0}),b=this.processParsedItems(t,a.feed(m));if(b==="protocol-reconnect")return await n.cancel(),t.controller?.abort(),b}let l=s.decode(),c=l?a.feed(l):[],p=this.processParsedItems(t,[...c,...a.end()]);if(p==="protocol-reconnect")return await n.cancel(),t.controller?.abort(),p}finally{n.releaseLock()}return"closed"}processParsedItems(t,r){for(let n of r){if(n.kind==="retry"){t.retryDelay=Math.min(n.retry,Rt);continue}this.updateLastEventId(t,n.id);let s=ot(n.data);if(!s){console.warn("[Sync] Dropping malformed SSE payload:",{serverId:t.serverId,event:n.event,data:n.data});continue}if(this.emitSyncEvent(t.serverId,s),s.type==="protocol.reset"||s.type==="protocol.invalid")return t.lastEventId=void 0,"protocol-reconnect"}return"closed"}async waitForReconnect(t){if(t.stopped)return;this.updateStatus(t,"reconnecting");let r=this.getReconnectDelay(t);await new Promise(n=>{t.reconnectResolve=n,t.reconnectTimer=setTimeout(()=>{t.reconnectTimer=void 0,t.reconnectResolve=void 0,n()},r)})}closeConnection(t){let r=this.connections.get(t);r&&(r.stopped=!0,r.controller?.abort(),r.reconnectTimer&&(clearTimeout(r.reconnectTimer),r.reconnectTimer=void 0),r.reconnectResolve?.(),r.reconnectResolve=void 0,this.updateStatus(r,"disconnected"),this.connections.delete(t))}getReconnectDelay(t){let r=t.retryDelay*Math.pow(2,Math.max(t.reconnectAttempts-1,0));return Math.min(r,Rt)+Math.random()*Vt}updateLastEventId(t,r){r!==void 0&&(t.lastEventId=r||void 0)}intentToParam(t){return Array.isArray(t)?t.join(","):t}isAbortError(t){return t instanceof Error?t.name==="AbortError"||t.message.toLowerCase().includes("abort"):!1}};import Ht from"mitt";var Tt=1e3,_=class extends M{constructor(){super(...arguments);this.emitter=Ht()}async connect(t,r){return this.connections.has(t)&&this.closeConnection(t),new Promise((n,s)=>{let a=!1,l=null,c=()=>{a||(a=!0,l&&clearTimeout(l),n())},p=u=>{a||(a=!0,l&&clearTimeout(l),s(u))};try{let u=new WebSocket(Ye(r.url)),d={serverId:t,socket:u,authenticated:!1,reconnectAttempts:0,reconnectTimer:void 0,isReconnecting:!1};this.connections.set(t,d),l=setTimeout(()=>{p(new Error(`WebSocket authentication timed out for server ${t}`)),this.connections.get(t)===d&&this.closeConnection(t)},this.AUTHENTICATION_TIMEOUT),u.onopen=()=>{u.send(JSON.stringify({event:"auth",jwt:r.token})),d.reconnectAttempts=0,d.isReconnecting=!1},u.onmessage=m=>{try{let b=JSON.parse(m.data);b.event==="auth-ok"?d.authenticated=!0:b.event==="auth-incorrect"&&(d.authenticated=!1);let v=`${t}:${b.event}`;this.emitter.emit(v,b),b.event==="auth-ok"&&c(),(b.event==="auth-expiring"||b.event==="auth-incorrect")&&this.handleAuthExpiring(t).catch(console.error)}catch(b){console.error("[WebSocket] Failed to parse message:",b)}},u.onclose=m=>{d.authenticated=!1,console.debug(`[WebSocket] Closed for server ${t}:`,{code:m.code,reason:m.reason,wasClean:m.wasClean}),p(new Error(`WebSocket closed before authentication for server ${t} (code: ${m.code})`)),m.code!==Tt&&this.scheduleReconnect(t,r)},u.onerror=m=>{let b=u.url,v=u.readyState;console.error(`[WebSocket] Error for server ${t}:`,{url:b,readyState:v,readyStateLabel:["CONNECTING","OPEN","CLOSING","CLOSED"][v],type:m.type}),p(new Error(`WebSocket connection failed for server ${t} (readyState: ${v})`))}}catch(u){p(u)}})}disconnect(t){this.closeConnection(t),this.emitter.all.forEach((r,n)=>{n.toString().startsWith(`${t}:`)&&this.emitter.all.delete(n)})}closeConnection(t){let r=this.connections.get(t);r&&(r.reconnectTimer&&(clearTimeout(r.reconnectTimer),r.reconnectTimer=void 0),(r.socket.readyState===WebSocket.OPEN||r.socket.readyState===WebSocket.CONNECTING)&&r.socket.close(Tt,"Client disconnecting"),this.connections.delete(t))}disconnectAll(){for(let t of this.connections.keys())this.disconnect(t)}send(t,r){let n=this.connections.get(t);if(!n||n.socket.readyState!==WebSocket.OPEN){console.warn(`Cannot send message: WebSocket not connected for server ${t}`);return}n.socket.send(JSON.stringify(r))}scheduleReconnect(t,r){let n=this.connections.get(t);if(!n)return;if(n.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){this.disconnect(t);return}n.isReconnecting=!0,n.reconnectAttempts++;let s=this.getReconnectDelay(n.reconnectAttempts);n.reconnectTimer=setTimeout(()=>{this.connect(t,r).catch(a=>{console.error(`[WebSocket] Reconnection failed for server ${t}:`,a)})},s)}async handleAuthExpiring(t){try{let r=await this.client.archon.servers_v0.getWebSocketAuth(t),n=this.connections.get(t);n&&n.socket.readyState===WebSocket.OPEN&&n.socket.send(JSON.stringify({event:"auth",jwt:r.token}))}catch(r){console.error(`[WebSocket] Failed to refresh auth for server ${t}:`,r),this.disconnect(t)}}};var A=class extends C{upload(e,t){let r;t.api==="labrinth"?r=this.resolveBaseUrl(this.config.labrinthBaseUrl):t.api==="archon"?r=this.resolveBaseUrl(this.config.archonBaseUrl):t.api==="sharedinstances"?r=this.resolveBaseUrl(this.config.sharedInstancesBaseUrl):r=t.api;let n=this.buildUrl(e,r,t.version),s=[];t.onProgress&&s.push(t.onProgress);let a=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>a.abort());let l,c={promise:(async()=>{let p="formData"in t&&t.formData instanceof FormData,u=await this.buildDefaultHeaders();p?delete u["Content-Type"]:u["Content-Type"]="application/octet-stream";let d={retry:!1,...t,headers:{...u,...t.headers}};this.attachArchonSentryCaptureHeader(d);let m=this.buildUploadContext(n,e,d);if(l=m,a.signal.aborted)throw new g("Upload cancelled");let b=await this.executeUploadFeatureChain(m,s,a);return await this.config.hooks?.onResponse?.(b,m),b})().catch(async p=>{let u=this.normalizeError(p,l);throw u.url??(u.url=l?.url),l&&await this.config.hooks?.onError?.(u,l),u}),onProgress:p=>(s.push(p),c),cancel:()=>a.abort()};return c}executeXHRUpload(e,t,r){return new Promise((n,s)=>{let a=new XMLHttpRequest,l=e.metadata;a.upload.addEventListener("progress",u=>{if(u.lengthComputable){let d={loaded:u.loaded,total:u.total,progress:u.loaded/u.total};t.forEach(m=>m(d))}}),a.addEventListener("load",()=>{if(a.status>=200&&a.status<300)try{n(a.response?JSON.parse(a.response):void 0)}catch{n(void 0)}else s(this.createUploadError(a))}),a.addEventListener("error",()=>s(new g("Upload failed"))),a.addEventListener("abort",()=>s(new g("Upload cancelled"))),a.addEventListener("timeout",()=>s(new g("Upload timed out"))),e.options.timeout!==void 0&&(a.timeout=e.options.timeout);let c=e.url;if(e.options.params){let u=new URLSearchParams(Object.entries(e.options.params).map(([d,m])=>[d,String(m)])).toString();c+=(c.includes("?")?"&":"?")+u}a.open("POST",c);for(let[u,d]of Object.entries(e.options.headers??{}))a.setRequestHeader(u,d);let p="formData"in l?l.formData:l.file;a.send(p),r.signal.addEventListener("abort",()=>a.abort())})}createUploadError(e){let t;try{t=e.response?JSON.parse(e.response):void 0}catch{t=e.responseText}return this.createNormalizedError(new Error(`Upload failed with status ${e.status}`),e.status,t)}};var at=class extends A{constructor(e){super(e),Object.defineProperty(this.archon,"sockets",{value:new _(this),writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.archon,"sync",{value:new S(this),writable:!1,enumerable:!0,configurable:!1})}async executeRequest(e,t){try{return await zt(e,{method:t.method??"GET",headers:t.headers,body:t.body,params:t.params,timeout:t.timeout,signal:t.signal})}catch(r){throw this.normalizeError(r)}}async executeStreamRequest(e,t){try{let r=await fetch(R(e,t.params),{method:t.method??"GET",headers:t.headers,body:T(t.body),signal:t.signal});if(!r.ok)throw this.createNormalizedError(new Error(`HTTP ${r.status}: ${r.statusText}`),r.status,await k(r));if(!r.body)throw new g("Streaming response has no readable body",{statusCode:r.status});return r.body}catch(r){throw this.normalizeError(r)}}normalizeError(e){return e instanceof Kt?this.createNormalizedError(e,e.response?.status,e.data):super.normalizeError(e)}};import{FetchError as Jt}from"ofetch";var lt=class{constructor(){let e=useState("circuit-breaker-state",()=>new Map);this.state=e.value}get(e){return this.state.get(e)}set(e,t){this.state.set(e,t)}clear(e){this.state.delete(e)}},ct=class extends A{constructor(e){super(e),Object.defineProperty(this.archon,"sockets",{value:new _(this),writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.archon,"sync",{value:new S(this),writable:!1,enumerable:!0,configurable:!1})}async resolveRateLimitKey(){if(this.rateLimitKeyResolved!==void 0)return this.rateLimitKeyResolved;let e=this.config.rateLimitKey;return typeof e=="string"?this.rateLimitKeyResolved=e:typeof e=="function"&&(this.rateLimitKeyPromise||(this.rateLimitKeyPromise=e()),this.rateLimitKeyResolved=await this.rateLimitKeyPromise),this.rateLimitKeyResolved}async request(e,t){return import.meta.server&&await this.resolveRateLimitKey(),super.request(e,t)}upload(e,t){if(import.meta.server)throw new g("upload() is not supported during SSR");return super.upload(e,t)}async executeRequest(e,t){try{return await $fetch(e,{method:t.method??"GET",headers:t.headers,body:t.body,params:t.params,timeout:t.timeout,signal:t.signal,cache:import.meta.server?void 0:"no-store"})}catch(r){throw this.normalizeError(r)}}async executeStreamRequest(e,t){try{let r=await fetch(R(e,t.params),{method:t.method??"GET",headers:t.headers,body:T(t.body),signal:t.signal,cache:import.meta.server?void 0:"no-store"});if(!r.ok)throw this.createNormalizedError(new Error(`HTTP ${r.status}: ${r.statusText}`),r.status,await k(r));if(!r.body)throw new g("Streaming response has no readable body",{statusCode:r.status});return r.body}catch(r){throw this.normalizeError(r)}}normalizeError(e){return e instanceof Jt?this.createNormalizedError(e,e.response?.status,e.data):super.normalizeError(e)}async buildDefaultHeaders(){let e={...await super.buildDefaultHeaders()};return import.meta.server&&this.rateLimitKeyResolved&&(e["x-ratelimit-key"]=this.rateLimitKeyResolved),e}};var ut=class extends A{constructor(e){super(e),Object.defineProperty(this.archon,"sockets",{value:new _(this),writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.archon,"sync",{value:new S(this),writable:!1,enumerable:!0,configurable:!1})}async executeRequest(e,t){try{let{fetch:r}=await import("@tauri-apps/plugin-http"),n=T(t.body),s=R(e,t.params),a=await r(s,{method:t.method??"GET",headers:t.headers,body:n});if(!a.ok){let p;try{p=await a.json()}catch{p=void 0}let u=new Error(`HTTP ${a.status}: ${a.statusText}`);throw u.statusCode=a.status,u.responseData=p,u}let l=a.headers.get("content-type")?.toLowerCase()??"";if(s.includes("/fs/download"))return await a.blob();if(l.startsWith("image/")||l.startsWith("audio/")||l.startsWith("video/")||l.includes("application/octet-stream"))return await a.blob();if(a.status===204||a.status===205)return;if(l.includes("application/json")||l.includes("+json"))return await a.json();let c=await a.text();if(!c)return;try{return JSON.parse(c)}catch{return c}}catch(r){throw this.normalizeError(r)}}async executeStreamRequest(e,t){try{let{fetch:r}=await import("@tauri-apps/plugin-http"),n=await r(R(e,t.params),{method:t.method??"GET",headers:t.headers,body:T(t.body),signal:t.signal});if(!n.ok)throw this.createNormalizedError(new Error(`HTTP ${n.status}: ${n.statusText}`),n.status,await k(n));if(!n.body)throw this.createNormalizedError(new Error("Streaming response has no readable body"),n.status,void 0);return n.body}catch(r){throw this.normalizeError(r)}}normalizeError(e){if(e instanceof Error){let t=e,r=t.statusCode,n=t.responseData;return this.createNormalizedError(e,r,n)}return super.normalizeError(e)}};var $={getAuth:null,refreshAuth:null};function Qt(i,e){$.getAuth=i,$.refreshAuth=e}function Xt(){$.getAuth=null,$.refreshAuth=null}async function Yt(i,e){try{return await i()}catch(t){if(t instanceof g&&t.statusCode===401)return await e(),await i();throw t}}async function Zt(i,e={}){let t=e.count??5,r=e.intervalMs??200,n=e.settleDelayMs??1e3,s=e.timeoutMs??t*r+n+1e3;return e.signal?.aborted?-1:await new Promise(a=>{let l=[],c=new Set,p,u=!1,d=(y,x)=>{let E=setTimeout(()=>{c.delete(E),y()},x);return c.add(E),E},m=()=>{for(let y of c)clearTimeout(y);c.clear(),e.signal?.removeEventListener("abort",v),p&&(p.readyState===WebSocket.CONNECTING||p.readyState===WebSocket.OPEN)&&p.close()},b=y=>{u||(u=!0,m(),a(y))},v=()=>b(-1);e.signal?.addEventListener("abort",v,{once:!0});try{p=new WebSocket(i)}catch{b(-1);return}d(()=>b(-1),s),p.onopen=()=>{for(let y=0;y<t;y++)d(()=>{p?.readyState===WebSocket.OPEN&&p.send(String(performance.now()))},y*r);d(()=>{let y=l.length>0?Math.round([...l].sort((x,E)=>x-E)[Math.floor(l.length/2)]):-1;b(y)},t*r+n)},p.onmessage=y=>{l.push(performance.now()-Number(y.data))},p.onerror=()=>b(-1),p.onclose=()=>{!u&&l.length===0&&b(-1)}})}export{f as AbstractFeature,C as AbstractModrinthClient,I as AbstractSyncClient,q as AbstractUploadClient,M as AbstractWebSocketClient,Et as Archon,et as AuthFeature,tt as CircuitBreakerFeature,at as GenericModrinthClient,S as GenericSyncClient,Xe as InMemoryCircuitBreakerStorage,g as ModrinthApiError,L as ModrinthServerError,rt as NodeAuthFeature,lt as NuxtCircuitBreakerStorage,ct as NuxtModrinthClient,_t as PANEL_VERSION,nt as PanelVersionFeature,it as RetryFeature,O as SseParser,ut as TauriModrinthClient,st as VerboseLoggingFeature,A as XHRUploadClient,Xt as clearNodeAuthState,Ye as getNodeWebSocketUrl,Ze as isModrinthErrorResponse,$ as nodeAuthState,ot as parseSyncEventData,Zt as pingWebSocketUrl,Qt as setNodeAuthState,Yt as withJWTRetry};
9
+ `)?this.data.slice(0,-1):this.data}),this.eventName="",this.data="",this.id=void 0}};function ot(i){let e;try{e=JSON.parse(i)}catch{return null}return!e||typeof e!="object"||typeof e.type!="string"?null:e}var Wt=1e3,Rt=3e4,Vt=1e3,S=class extends I{constructor(){super(...arguments);this.emitter=Gt()}async safeConnectServer(t,r={}){let n=this.connections.get(t);if(n&&!r.force&&!n.stopped&&n.status!=="disconnected")return;n&&this.closeConnection(t);let s={serverId:t,intent:r.intent??"all",reconnectAttempts:0,retryDelay:Wt,stopped:!1,status:"idle"};this.connections.set(t,s),this.runConnection(s)}disconnect(t){this.closeConnection(t),this.clearListeners(t)}disconnectAll(){for(let t of this.connections.keys())this.disconnect(t)}async runConnection(t){for(;!t.stopped;){let r=t.status==="connected";this.updateStatus(t,r?"reconnecting":"connecting");let n=new AbortController;t.controller=n;let s;try{let a=await this.client.stream("/sync",{api:"archon",version:1,method:"GET",params:{scope:`server:${t.serverId}`,intent:this.intentToParam(t.intent)},headers:t.lastEventId?{"Last-Event-Id":t.lastEventId}:void 0,signal:n.signal,retry:!1,circuitBreaker:!1});if(t.stopped)return;t.reconnectAttempts=0,this.updateStatus(t,"connected"),s=await this.consumeStream(t,a)}catch(a){if(t.stopped||this.isAbortError(a))return;t.reconnectAttempts++,this.updateStatus(t,"error",a),console.warn(`[Sync] Connection failed for server ${t.serverId}:`,a)}finally{n.abort(),t.controller=void 0}if(t.stopped)return;if(s==="protocol-reconnect"){t.reconnectAttempts=0;continue}await this.waitForReconnect(t)}}async consumeStream(t,r){let n=r.getReader(),s=new TextDecoder,a=new $;try{for(;!t.stopped;){let{done:u,value:d}=await n.read();if(u)break;let m=s.decode(d,{stream:!0}),b=this.processParsedItems(t,a.feed(m));if(b==="protocol-reconnect")return await n.cancel(),t.controller?.abort(),b}let l=s.decode(),c=l?a.feed(l):[],p=this.processParsedItems(t,[...c,...a.end()]);if(p==="protocol-reconnect")return await n.cancel(),t.controller?.abort(),p}finally{n.releaseLock()}return"closed"}processParsedItems(t,r){for(let n of r){if(n.kind==="retry"){t.retryDelay=Math.min(n.retry,Rt);continue}this.updateLastEventId(t,n.id);let s=ot(n.data);if(!s){console.warn("[Sync] Dropping malformed SSE payload:",{serverId:t.serverId,event:n.event,data:n.data});continue}if(this.emitSyncEvent(t.serverId,s),s.type==="protocol.reset"||s.type==="protocol.invalid")return t.lastEventId=void 0,"protocol-reconnect"}return"closed"}async waitForReconnect(t){if(t.stopped)return;this.updateStatus(t,"reconnecting");let r=this.getReconnectDelay(t);await new Promise(n=>{t.reconnectResolve=n,t.reconnectTimer=setTimeout(()=>{t.reconnectTimer=void 0,t.reconnectResolve=void 0,n()},r)})}closeConnection(t){let r=this.connections.get(t);r&&(r.stopped=!0,r.controller?.abort(),r.reconnectTimer&&(clearTimeout(r.reconnectTimer),r.reconnectTimer=void 0),r.reconnectResolve?.(),r.reconnectResolve=void 0,this.updateStatus(r,"disconnected"),this.connections.delete(t))}getReconnectDelay(t){let r=t.retryDelay*Math.pow(2,Math.max(t.reconnectAttempts-1,0));return Math.min(r,Rt)+Math.random()*Vt}updateLastEventId(t,r){r!==void 0&&(t.lastEventId=r||void 0)}intentToParam(t){return Array.isArray(t)?t.join(","):t}isAbortError(t){return t instanceof Error?t.name==="AbortError"||t.message.toLowerCase().includes("abort"):!1}};import Ht from"mitt";var Tt=1e3,_=class extends M{constructor(){super(...arguments);this.emitter=Ht()}async connect(t,r){return this.connections.has(t)&&this.closeConnection(t),new Promise((n,s)=>{let a=!1,l=null,c=()=>{a||(a=!0,l&&clearTimeout(l),n())},p=u=>{a||(a=!0,l&&clearTimeout(l),s(u))};try{let u=new WebSocket(Ye(r.url)),d={serverId:t,socket:u,authenticated:!1,reconnectAttempts:0,reconnectTimer:void 0,isReconnecting:!1};this.connections.set(t,d),l=setTimeout(()=>{p(new Error(`WebSocket authentication timed out for server ${t}`)),this.connections.get(t)===d&&this.closeConnection(t)},this.AUTHENTICATION_TIMEOUT),u.onopen=()=>{u.send(JSON.stringify({event:"auth",jwt:r.token})),d.reconnectAttempts=0,d.isReconnecting=!1},u.onmessage=m=>{try{let b=JSON.parse(m.data);b.event==="auth-ok"?d.authenticated=!0:b.event==="auth-incorrect"&&(d.authenticated=!1);let v=`${t}:${b.event}`;this.emitter.emit(v,b),b.event==="auth-ok"&&c(),(b.event==="auth-expiring"||b.event==="auth-incorrect")&&this.handleAuthExpiring(t).catch(console.error)}catch(b){console.error("[WebSocket] Failed to parse message:",b)}},u.onclose=m=>{d.authenticated=!1,console.debug(`[WebSocket] Closed for server ${t}:`,{code:m.code,reason:m.reason,wasClean:m.wasClean}),p(new Error(`WebSocket closed before authentication for server ${t} (code: ${m.code})`)),m.code!==Tt&&this.scheduleReconnect(t,r)},u.onerror=m=>{let b=u.url,v=u.readyState;console.error(`[WebSocket] Error for server ${t}:`,{url:b,readyState:v,readyStateLabel:["CONNECTING","OPEN","CLOSING","CLOSED"][v],type:m.type}),p(new Error(`WebSocket connection failed for server ${t} (readyState: ${v})`))}}catch(u){p(u)}})}disconnect(t){this.closeConnection(t),this.emitter.all.forEach((r,n)=>{n.toString().startsWith(`${t}:`)&&this.emitter.all.delete(n)})}closeConnection(t){let r=this.connections.get(t);r&&(r.reconnectTimer&&(clearTimeout(r.reconnectTimer),r.reconnectTimer=void 0),(r.socket.readyState===WebSocket.OPEN||r.socket.readyState===WebSocket.CONNECTING)&&r.socket.close(Tt,"Client disconnecting"),this.connections.delete(t))}disconnectAll(){for(let t of this.connections.keys())this.disconnect(t)}send(t,r){let n=this.connections.get(t);if(!n||n.socket.readyState!==WebSocket.OPEN){console.warn(`Cannot send message: WebSocket not connected for server ${t}`);return}n.socket.send(JSON.stringify(r))}scheduleReconnect(t,r){let n=this.connections.get(t);if(!n)return;if(n.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){this.disconnect(t);return}n.isReconnecting=!0,n.reconnectAttempts++;let s=this.getReconnectDelay(n.reconnectAttempts);n.reconnectTimer=setTimeout(()=>{this.connect(t,r).catch(a=>{console.error(`[WebSocket] Reconnection failed for server ${t}:`,a)})},s)}async handleAuthExpiring(t){try{let r=await this.client.archon.servers_v0.getWebSocketAuth(t),n=this.connections.get(t);n&&n.socket.readyState===WebSocket.OPEN&&n.socket.send(JSON.stringify({event:"auth",jwt:r.token}))}catch(r){console.error(`[WebSocket] Failed to refresh auth for server ${t}:`,r),this.disconnect(t)}}};var A=class extends C{upload(e,t){let r;t.api==="labrinth"?r=this.resolveBaseUrl(this.config.labrinthBaseUrl):t.api==="archon"?r=this.resolveBaseUrl(this.config.archonBaseUrl):t.api==="sharedinstances"?r=this.resolveBaseUrl(this.config.sharedInstancesBaseUrl):r=t.api;let n=this.buildUrl(e,r,t.version),s=[];t.onProgress&&s.push(t.onProgress);let a=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>a.abort());let l,c={promise:(async()=>{let p="formData"in t&&t.formData instanceof FormData,u=await this.buildDefaultHeaders();p?delete u["Content-Type"]:u["Content-Type"]="application/octet-stream";let d={retry:!1,...t,headers:{...u,...t.headers}};this.attachArchonSentryCaptureHeader(d);let m=this.buildUploadContext(n,e,d);if(l=m,a.signal.aborted)throw new g("Upload cancelled");let b=await this.executeUploadFeatureChain(m,s,a);return await this.config.hooks?.onResponse?.(b,m),b})().catch(async p=>{let u=this.normalizeError(p,l);throw u.url??(u.url=l?.url),l&&await this.config.hooks?.onError?.(u,l),u}),onProgress:p=>(s.push(p),c),cancel:()=>a.abort()};return c}executeXHRUpload(e,t,r){return new Promise((n,s)=>{let a=new XMLHttpRequest,l=e.metadata;a.upload.addEventListener("progress",u=>{if(u.lengthComputable){let d={loaded:u.loaded,total:u.total,progress:u.loaded/u.total};t.forEach(m=>m(d))}}),a.addEventListener("load",()=>{if(a.status>=200&&a.status<300)try{n(a.response?JSON.parse(a.response):void 0)}catch{n(void 0)}else s(this.createUploadError(a))}),a.addEventListener("error",()=>s(new g("Upload failed"))),a.addEventListener("abort",()=>s(new g("Upload cancelled"))),a.addEventListener("timeout",()=>s(new g("Upload timed out"))),e.options.timeout!==void 0&&(a.timeout=e.options.timeout);let c=e.url;if(e.options.params){let u=new URLSearchParams(Object.entries(e.options.params).map(([d,m])=>[d,String(m)])).toString();c+=(c.includes("?")?"&":"?")+u}a.open("POST",c);for(let[u,d]of Object.entries(e.options.headers??{}))a.setRequestHeader(u,d);let p="formData"in l?l.formData:l.file;a.send(p),r.signal.addEventListener("abort",()=>a.abort())})}createUploadError(e){let t;try{t=e.response?JSON.parse(e.response):void 0}catch{t=e.responseText}return this.createNormalizedError(new Error(`Upload failed with status ${e.status}`),e.status,t)}};var at=class extends A{constructor(e){super(e),Object.defineProperty(this.archon,"sockets",{value:new _(this),writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.archon,"sync",{value:new S(this),writable:!1,enumerable:!0,configurable:!1})}async executeRequest(e,t){try{return await zt(e,{method:t.method??"GET",headers:t.headers,body:t.body,params:t.params,timeout:t.timeout,signal:t.signal})}catch(r){throw this.normalizeError(r)}}async executeStreamRequest(e,t){try{let r=await fetch(R(e,t.params),{method:t.method??"GET",headers:t.headers,body:T(t.body),signal:t.signal});if(!r.ok)throw this.createNormalizedError(new Error(`HTTP ${r.status}: ${r.statusText}`),r.status,await k(r));if(!r.body)throw new g("Streaming response has no readable body",{statusCode:r.status});return r.body}catch(r){throw this.normalizeError(r)}}normalizeError(e){return e instanceof Kt?this.createNormalizedError(e,e.response?.status,e.data):super.normalizeError(e)}};import{FetchError as Jt}from"ofetch";var lt=class{constructor(){let e=useState("circuit-breaker-state",()=>new Map);this.state=e.value}get(e){return this.state.get(e)}set(e,t){this.state.set(e,t)}clear(e){this.state.delete(e)}},ct=class extends A{constructor(e){super(e),Object.defineProperty(this.archon,"sockets",{value:new _(this),writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.archon,"sync",{value:new S(this),writable:!1,enumerable:!0,configurable:!1})}async resolveRateLimitKey(){if(this.rateLimitKeyResolved!==void 0)return this.rateLimitKeyResolved;let e=this.config.rateLimitKey;return typeof e=="string"?this.rateLimitKeyResolved=e:typeof e=="function"&&(this.rateLimitKeyPromise||(this.rateLimitKeyPromise=e()),this.rateLimitKeyResolved=await this.rateLimitKeyPromise),this.rateLimitKeyResolved}async request(e,t){return import.meta.server&&await this.resolveRateLimitKey(),super.request(e,t)}upload(e,t){if(import.meta.server)throw new g("upload() is not supported during SSR");return super.upload(e,t)}async executeRequest(e,t){try{return await $fetch(e,{method:t.method??"GET",headers:t.headers,body:t.body,params:t.params,timeout:t.timeout,signal:t.signal,cache:import.meta.server?void 0:"no-store"})}catch(r){throw this.normalizeError(r)}}async executeStreamRequest(e,t){try{let r=await fetch(R(e,t.params),{method:t.method??"GET",headers:t.headers,body:T(t.body),signal:t.signal,cache:import.meta.server?void 0:"no-store"});if(!r.ok)throw this.createNormalizedError(new Error(`HTTP ${r.status}: ${r.statusText}`),r.status,await k(r));if(!r.body)throw new g("Streaming response has no readable body",{statusCode:r.status});return r.body}catch(r){throw this.normalizeError(r)}}normalizeError(e){return e instanceof Jt?this.createNormalizedError(e,e.response?.status,e.data):super.normalizeError(e)}async buildDefaultHeaders(){let e={...await super.buildDefaultHeaders()};return import.meta.server&&this.rateLimitKeyResolved&&(e["x-ratelimit-key"]=this.rateLimitKeyResolved),e}};var ut=class extends A{constructor(e){super(e),Object.defineProperty(this.archon,"sockets",{value:new _(this),writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.archon,"sync",{value:new S(this),writable:!1,enumerable:!0,configurable:!1})}async executeRequest(e,t){try{let{fetch:r}=await import("@tauri-apps/plugin-http"),n=T(t.body),s=R(e,t.params),a=await r(s,{method:t.method??"GET",headers:t.headers,body:n});if(!a.ok){let p;try{p=await a.json()}catch{p=void 0}let u=new Error(`HTTP ${a.status}: ${a.statusText}`);throw u.statusCode=a.status,u.responseData=p,u}let l=a.headers.get("content-type")?.toLowerCase()??"";if(s.includes("/fs/download"))return await a.blob();if(l.startsWith("image/")||l.startsWith("audio/")||l.startsWith("video/")||l.includes("application/octet-stream"))return await a.blob();if(a.status===204||a.status===205)return;if(l.includes("application/json")||l.includes("+json"))return await a.json();let c=await a.text();if(!c)return;try{return JSON.parse(c)}catch{return c}}catch(r){throw this.normalizeError(r)}}async executeStreamRequest(e,t){try{let{fetch:r}=await import("@tauri-apps/plugin-http"),n=await r(R(e,t.params),{method:t.method??"GET",headers:t.headers,body:T(t.body),signal:t.signal});if(!n.ok)throw this.createNormalizedError(new Error(`HTTP ${n.status}: ${n.statusText}`),n.status,await k(n));if(!n.body)throw this.createNormalizedError(new Error("Streaming response has no readable body"),n.status,void 0);return n.body}catch(r){throw this.normalizeError(r)}}normalizeError(e){if(e instanceof Error){let t=e,r=t.statusCode,n=t.responseData;return this.createNormalizedError(e,r,n)}return super.normalizeError(e)}};var O={getAuth:null,refreshAuth:null};function Qt(i,e){O.getAuth=i,O.refreshAuth=e}function Xt(){O.getAuth=null,O.refreshAuth=null}async function Yt(i,e){try{return await i()}catch(t){if(t instanceof g&&t.statusCode===401)return await e(),await i();throw t}}async function Zt(i,e={}){let t=e.count??5,r=e.intervalMs??200,n=e.settleDelayMs??1e3,s=e.timeoutMs??t*r+n+1e3;return e.signal?.aborted?-1:await new Promise(a=>{let l=[],c=new Set,p,u=!1,d=(y,x)=>{let E=setTimeout(()=>{c.delete(E),y()},x);return c.add(E),E},m=()=>{for(let y of c)clearTimeout(y);c.clear(),e.signal?.removeEventListener("abort",v),p&&(p.readyState===WebSocket.CONNECTING||p.readyState===WebSocket.OPEN)&&p.close()},b=y=>{u||(u=!0,m(),a(y))},v=()=>b(-1);e.signal?.addEventListener("abort",v,{once:!0});try{p=new WebSocket(i)}catch{b(-1);return}d(()=>b(-1),s),p.onopen=()=>{for(let y=0;y<t;y++)d(()=>{p?.readyState===WebSocket.OPEN&&p.send(String(performance.now()))},y*r);d(()=>{let y=l.length>0?Math.round([...l].sort((x,E)=>x-E)[Math.floor(l.length/2)]):-1;b(y)},t*r+n)},p.onmessage=y=>{l.push(performance.now()-Number(y.data))},p.onerror=()=>b(-1),p.onclose=()=>{!u&&l.length===0&&b(-1)}})}export{f as AbstractFeature,C as AbstractModrinthClient,I as AbstractSyncClient,q as AbstractUploadClient,M as AbstractWebSocketClient,Et as Archon,et as AuthFeature,tt as CircuitBreakerFeature,at as GenericModrinthClient,S as GenericSyncClient,Xe as InMemoryCircuitBreakerStorage,g as ModrinthApiError,L as ModrinthServerError,rt as NodeAuthFeature,lt as NuxtCircuitBreakerStorage,ct as NuxtModrinthClient,_t as PANEL_VERSION,nt as PanelVersionFeature,it as RetryFeature,$ as SseParser,ut as TauriModrinthClient,st as VerboseLoggingFeature,A as XHRUploadClient,Xt as clearNodeAuthState,Ye as getNodeWebSocketUrl,Ze as isModrinthErrorResponse,O as nodeAuthState,ot as parseSyncEventData,Zt as pingWebSocketUrl,Qt as setNodeAuthState,Yt as withJWTRetry};
10
10
  //# sourceMappingURL=index.js.map