UNPKG

@zennomi/mangadex-full-api

Version:

A MangaDex api based around the official API.

6 lines (5 loc) 32.9 kB
var oe=Object.defineProperty,ce=Object.defineProperties;var pe=Object.getOwnPropertyDescriptors;var _=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,le=Object.prototype.propertyIsEnumerable;var ee=(c,r,e)=>r in c?oe(c,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[r]=e,w=(c,r)=>{for(var e in r||(r={}))ue.call(r,e)&&ee(c,e,r[e]);if(_)for(var e of _(r))le.call(r,e)&&ee(c,e,r[e]);return c},R=(c,r)=>ce(c,pe(r));var s=(c,r,e)=>new Promise((t,a)=>{var i=o=>{try{n(e.next(o))}catch(l){a(l)}},p=o=>{try{n(e.throw(o))}catch(l){a(l)}},n=o=>o.done?t(o.value):Promise.resolve(o.value).then(i,p);n((e=e.apply(c,r)).next())});var Y=class{},g=Y;var B=class extends g{constructor(e){super();this.cached=!1;if(this.id=e.id,!(e.type in B.typeMap))throw`Unregistered relationship type: ${e.type}`;if(this.type=e.type,this.related=e.related,e.attributes)try{let t=B.typeMap[this.type],a={attributes:e.attributes,id:this.id,type:this.type,relationships:[]};this.cachedData=Reflect.construct(t,[a]),this.cached=!0}catch(t){}}resolve(){return s(this,null,function*(){return this.cached?this.cachedData:B.typeMap[this.type].get(this.id)})}static resolveAll(e){return s(this,null,function*(){if(e.length===0)return[];let t=B.typeMap[e[0].type];return t!==void 0&&t.getMultiple!==void 0?t.getMultiple(e.map(a=>a.id)):yield Promise.all(e.map(a=>a.resolve()))})}static convertType(e,t){return t.filter(a=>a.type===e).map(a=>new B(a))}static registerTypes(e,t){if(B.typeMapLocked)throw Error(`Cannot add types ${e} because the Relationship type map has been locked.`);e.forEach(a=>B.typeMap[a]=t)}static lockTypeMap(){B.typeMapLocked=!0}static getRegisteredTypes(){return Object.keys(B.typeMap)}},z=B;z.typeMap={},z.typeMapLocked=!1;var h=z;var V=class{constructor(r){for(let e in r)this[e]=r[e]}get localString(){if(V.globalLocale in this)return this[V.globalLocale];if("en"in this)return this.en;for(let r of Object.keys(this))if(typeof this[r]=="string")return this[r];return""}static setGlobalLocale(r){if(r.length<2||r.length>8)throw Error(`Locale "${r}" has an invalid length`);V.globalLocale=r}},O=V;O.globalLocale="en";var x=O;var A=class extends Error{constructor(r){if(typeof r!="string"){let e;"result"in r?e=r.errors:e=r,r=e.map((a,i,p)=>{let n="";return p.length>1&&(n+=`[${i} of ${p.length}] `),n+=`${a.title} (${a.status}, ${a.id}): ${a.detail}. `,n}).join(` `)}r.includes("36 characters")&&(r+=` It looks like MangaDex expected a UUID, but you provided a non-UUID string. If you are using Tags, please use Tag.getByName() instead of the literal name.`),super(r),Object.setPrototypeOf(this,A.prototype),this.name="APIResponseError"}};var T=class extends Error{constructor(r){super(r),Object.setPrototypeOf(this,T.prototype),this.name="AuthError"}};var I=class{};I.useDebugServerValue=!1;function he(c){I.useDebugServerValue=c}function me(){return I.useDebugServerValue}function H(c){I.activeClient=c}function te(){I.activeClient=void 0}function ae(){var c;return(c=I.activeClient)!=null?c:null}function u(t,a){return s(this,arguments,function*(c,r,e={}){let i=I.useDebugServerValue?"https://api.mangadex.dev":"https://api.mangadex.org/",p=re(i,c,r);if(I.activeClient&&!e.noAuth){let d=yield I.activeClient.getSessionToken();e.headers===void 0&&(e.headers={}),e.headers.authorization=`Bearer ${d}`}let n=yield fetch(p,e),o=n.headers.get("content-type");if(!(o!=null&&o.toLowerCase().includes("json"))){let d=`${n.statusText} (${n.status}) Response was an unexpected content type: ${o!=null?o:"Unspecified Type"}.`;try{let y=yield n.text();y.length>128&&(y=y.slice(0,128)),d+=` Start of Body: ${y}`}catch(y){}throw new A(d)}let l=yield n.json();if("result"in l&&l.result!=="ok")throw new A(l);if(n.status>=400)throw new A(`${n.statusText} (${n.status})`);return l})}function S(c,r,e){return s(this,null,function*(){return(yield u(c,r,e)).data})}function f(i){return s(this,arguments,function*(c,r={},e,t=100,a=10){var D,q;let n=Math.min((D=r.limit)!=null?D:a,1e4),o=(q=r.offset)!=null?q:0;if(o>=1e4||n<=0)return[];o>1e4-Math.min(t,n)&&(n=1e4-o);let l=yield u(c,R(w({},r),{limit:Math.min(n,t)}),e);if(n<=t||l.total<=l.data.length+o)return l.data;n=Math.min(n,l.total);let d=[];for(let W=o+t;W<n;W+=t){let ne=Math.min(n-W,t);d.push(S(c,R(w({},r),{limit:ne,offset:W}),e))}let y=yield Promise.all(d);return l.data.concat(...y)})}function E(p,n){return s(this,arguments,function*(c,r,e={},t="ids",a=100,i){let o=r.map(D=>D instanceof g?D.id:D),l=[];for(let D=0;D<o.length;D+=a)l.push(S(c,R(w({},e),{[t]:o.slice(D,D+a),limit:a}),i));let y=(yield Promise.all(l)).flat();return y.sort((D,q)=>o.indexOf(D.id)-o.indexOf(q.id)),y})}function L(i,p,n){return s(this,arguments,function*(c,r,e,t="POST",a={}){let o=a.headers!==void 0?a.headers:{};return o["Content-Type"]="application/json",u(c,e,{body:JSON.stringify(r),method:t,headers:o})})}function P(i,p,n){return s(this,arguments,function*(c,r,e,t="POST",a={}){return(yield L(c,r,e,t,a)).data})}function se(c,r,e){return s(this,null,function*(){let t=re("https://api.mangadex.network",c,e),a=yield fetch(t,{body:JSON.stringify(r),method:"POST",headers:{"Content-Type":"application/json"}});if(!a.ok)throw new A(`${a.status} ${a.statusText}`)})}function Q(i,p,n){return s(this,arguments,function*(c,r,e,t="POST",a={}){let o=new FormData,l=(d,y)=>{typeof y!="string"&&"data"in y&&"name"in y?o.append(d,y.data,y.name):o.append(d,y)};for(let[d,y]of Object.entries(r))y&&(Array.isArray(y)?y.forEach((D,q)=>l(d+q,D)):l(d,y));return yield u(c,e,R(w({},a),{method:t,body:o}))})}function re(c,r,e){let t=r?new URL(r,c):new URL(c);if(!e)return t;for(let[a,i]of Object.entries(e))if(Array.isArray(i))for(let p of i)p instanceof g&&(p=p.id),t.searchParams.append(`${a}[]`,p.toString());else if(typeof i=="object")if(i instanceof g)t.searchParams.append(a,i.id.toString());else{let p=Object.entries(i);for(let[n,o]of p)t.searchParams.append(`${a}[${n}]`,o.toString())}else i!==void 0&&t.searchParams.append(a,i.toString());return t}function J(c){return s(this,null,function*(){try{let r;return c!==void 0&&(r={headers:{authorization:`Bearer ${c}`},noAuth:!0}),(yield u("/auth/check",void 0,r)).isAuthenticated}catch(r){if(r instanceof A)return!1;throw r}})}function Z(c,r){return s(this,null,function*(){let e=new URLSearchParams;for(let[n,o]of Object.entries(r))e.append(n,o);let t=`https://auth.mangadex.${me()?"dev":"org"}`,a=new URL(c,t),i=yield fetch(a,{body:e,method:"POST"});if(i.status>=400)throw new T(`${i.statusText} (${i.status})`);return yield i.json()})}var U=class extends g{constructor(e){super();this.id=e.id,this.name=e.attributes.name,this.imageUrl=e.attributes.imageUrl,this.biography=new x(e.attributes.biography),this.twitter=e.attributes.twitter,this.pixiv=e.attributes.pixiv,this.melonBook=e.attributes.melonBook,this.fanBox=e.attributes.fanBox,this.booth=e.attributes.booth,this.nicoVideo=e.attributes.nicoVideo,this.skeb=e.attributes.skeb,this.fantia=e.attributes.fantia,this.tumblr=e.attributes.tumblr,this.youtube=e.attributes.youtube,this.weibo=e.attributes.weibo,this.naver=e.attributes.naver,this.namicomi=e.attributes.namicomi,this.website=e.attributes.website,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.updatedAt=new Date(e.attributes.updatedAt),this.manga=h.convertType("manga",e.relationships)}static get(e,t){return s(this,null,function*(){return new U(yield S(`/author/${e}`,{includes:t}))})}static search(e){return s(this,null,function*(){return(yield f("/author",e)).map(a=>new U(a))})}static getByQuery(e){return s(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}static getMultiple(e){return s(this,null,function*(){return(yield E("/author",e)).map(a=>new U(a))})}static create(e){return s(this,null,function*(){return new U(yield P("/author",e))})}static delete(e){return s(this,null,function*(){yield u(`/author/${e}`,void 0,{method:"DELETE"})})}delete(){return s(this,null,function*(){yield U.delete(this.id)})}update(e){return s(this,null,function*(){return new U(yield P(`/author/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}};var v=class extends g{constructor(e){super();this.id=e.id,this.volume=e.attributes.volume,this.fileName=e.attributes.fileName,this.description=e.attributes.description,this.locale=e.attributes.locale,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.updatedAt=new Date(e.attributes.updatedAt),this.manga=h.convertType("manga",e.relationships).pop(),this.url=this.manga?`https://mangadex.org/covers/${this.manga.id}/${this.fileName}`:null,this.uploader=h.convertType("user",e.relationships).pop()}static get(e,t){return s(this,null,function*(){return e instanceof g&&(e=e.id),new v(yield S(`/cover/${e}`,{includes:t}))})}static search(e){return s(this,null,function*(){return(yield f("/cover",e)).map(a=>new v(a))})}static getByQuery(e){return s(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}static getMultiple(e){return s(this,null,function*(){return(yield E("/cover",e)).map(a=>new v(a))})}static getMangaCovers(e,t){return s(this,null,function*(){if(Array.isArray(e)||(e=[typeof e=="string"?e:e.id]),e.length===0)return[];let a=e.map(i=>typeof i=="string"?i:i.id);return v.search({manga:a,includes:t})})}static delete(e){return s(this,null,function*(){yield u(`/cover/${e}`,void 0,{method:"DELETE"})})}delete(){return s(this,null,function*(){yield v.delete(this.id)})}update(e){return s(this,null,function*(){return new v(yield P(`/cover/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}static create(e,t){return s(this,null,function*(){typeof e!="string"&&(e=e.id);let a=yield Q(`/cover/${e}`,t);return new v(a.data)})}};var $=class extends g{constructor(e){super();this.id=e.id,this.name=new x(e.attributes.name),this.description=new x(e.attributes.description),this.group=e.attributes.group,this.version=e.attributes.version}get localName(){return this.name.localString}get localDescription(){return this.description.localString}static getAllTags(){return s(this,null,function*(){if(!$.allTagCache||$.allTagCache.length===0){let e=yield u("/manga/tag");$.allTagCache=e.data.map(t=>new $(t))}return $.allTagCache})}static getByName(e){return s(this,null,function*(){let t=yield this.getAllTags(),a=e.toLowerCase(),i=t.find(p=>Object.values(p.name).some(n=>n.toLowerCase()===a));if(!i)throw new Error(`No tag found with name ${e}`);return i})}static getByNames(e){return s(this,null,function*(){let t=yield this.getAllTags(),a=e.map(i=>i.toLowerCase());return t.filter(i=>Object.values(i.name).some(p=>a.includes(p.toLowerCase())))})}};var j=class{constructor(r){this.anilist=r!=null&&r.al?`https://anilist.co/manga/${r.al}`:void 0,this.animePlanet=r!=null&&r.ap?`https://www.anime-planet.com/manga/${r.ap}`:void 0,this.bookWalker=r!=null&&r.bw?`https://bookwalker.jp/${r.bw}`:void 0,this.mangaUpdates=r!=null&&r.mu?`https://www.mangaupdates.com/series.html?id=${r.mu}`:void 0,this.novelUpdates=r!=null&&r.nu?`https://www.novelupdates.com/series/${r.nu}`:void 0,this.myAnimeList=r!=null&&r.mal?`https://myanimelist.net/manga/${r.mal}`:void 0,(r==null?void 0:r.kt)!==void 0&&(isNaN(parseInt(r.kt))?this.kitsu=`https://kitsu.io/api/edge/manga?filter[slug]=${r.kt}`:this.kitsu=`https://kitsu.io/api/edge/manga/${r.kt}`),this.amazon=r==null?void 0:r.amz,this.eBookJapan=r==null?void 0:r.ebj,this.raw=r==null?void 0:r.raw,this.officialEnglishTranslation=r==null?void 0:r.engtl,this.cdJapan=r==null?void 0:r.cdj}},ie=j;var b=class extends g{constructor(e){super();this.id=e.id,this.title=e.attributes.title,this.volume=e.attributes.volume,this.chapter=e.attributes.chapter,this.pages=e.attributes.pages,this.translatedLanguage=e.attributes.translatedLanguage,this.uploader=h.convertType("user",e.relationships).pop(),this.externalUrl=e.attributes.externalUrl,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.publishAt=new Date(e.attributes.publishAt),this.updatedAt=new Date(e.attributes.updatedAt),this.readableAt=new Date(e.attributes.readableAt),this.isExternal=e.attributes.externalUrl!==null,this.manga=h.convertType("manga",e.relationships).pop(),this.groups=h.convertType("scanlation_group",e.relationships)}static get(e,t){return s(this,null,function*(){return new b(yield S(`/chapter/${e}`,{includes:t}))})}static getMultiple(e){return s(this,null,function*(){return(yield E("/chapter",e)).map(a=>new b(a))})}static search(e){return s(this,null,function*(){return(yield f("/chapter",e)).map(a=>new b(a))})}static getByQuery(e){return s(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}update(e){return s(this,null,function*(){return new b(yield P(`/chapter/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}static delete(e){return s(this,null,function*(){yield u(`/chapter/${e}`,void 0,{method:"DELETE"})})}delete(){return s(this,null,function*(){yield b.delete(this.id)})}getReadablePages(e=!1,t=!1){return s(this,null,function*(){var p,n;if(this.isExternal)throw new Error("Cannot get readable pages for an external chapter.");let a=yield u(`/at-home/server/${this.id}`,{forcePort443:t});return((n=e&&(p=a.chapter.dataSaver)!=null?p:a.chapter.data)!=null?n:[]).map(o=>`${a.baseUrl}/${e?"data-saver":"data"}/${a.chapter.hash}/${o}`)})}static reportPageURL(e){return s(this,null,function*(){yield se("/report",e)})}static getStatistics(e){return s(this,null,function*(){return(yield u("/statistics/chapter",{chapter:e})).statistics})}getStatistics(){return s(this,null,function*(){return(yield b.getStatistics([this.id]))[this.id]})}};var m=class extends g{constructor(e){super();this.id=e.id,this.altTitles=e.attributes.altTitles.map(t=>new x(t)),this.artists=h.convertType("artist",e.relationships),this.authors=h.convertType("author",e.relationships),this.availableTranslatedLanguages=e.attributes.availableTranslatedLanguages,this.chapterNumbersResetOnNewVolume=e.attributes.chapterNumbersResetOnNewVolume,this.contentRating=e.attributes.contentRating,this.createdAt=new Date(e.attributes.createdAt),this.description=new x(e.attributes.description),this.isLocked=e.attributes.isLocked,this.lastChapter=e.attributes.lastChapter,this.lastVolume=e.attributes.lastVolume,this.latestUploadedChapter=new h({id:e.attributes.latestUploadedChapter,type:"chapter"}),this.links=new ie(e.attributes.links),this.mainCover=h.convertType("cover_art",e.relationships).pop(),this.publicationDemographic=e.attributes.publicationDemographic,this.relatedManga=m.getRelatedManga(e.relationships),this.state=e.attributes.state,this.status=e.attributes.status,this.tags=e.attributes.tags.map(t=>new $(t)),this.title=new x(e.attributes.title),this.updatedAt=new Date(e.attributes.updatedAt),this.version=e.attributes.version,this.year=e.attributes.year,this.originalLanguage=e.attributes.originalLanguage}static getRelatedManga(e){let t={monochrome:[],main_story:[],adapted_from:[],based_on:[],prequel:[],side_story:[],doujinshi:[],same_franchise:[],shared_universe:[],sequel:[],spin_off:[],alternate_story:[],alternate_version:[],preserialization:[],colored:[],serialization:[]};for(let a of e)a.type==="manga"&&t[a.related].push(new h(a));return t}get localTitle(){return this.title.localString}get localAltTitles(){return this.altTitles.map(e=>e.localString)}get localDescription(){return this.description.localString}static get(e,t){return s(this,null,function*(){return new m(yield S(`/manga/${e}`,{includes:t}))})}static search(e){return s(this,null,function*(){return(yield f("/manga",e)).map(a=>new m(a))})}static getMultiple(e,t){return s(this,null,function*(){return(yield E("/manga",e,t)).map(i=>new m(i))})}static getTotalSearchResults(e){return s(this,null,function*(){return(yield u("/manga",R(w({},e),{limit:1,offset:0}))).total})}static getFeed(e,t){return s(this,null,function*(){return(yield f(`/manga/${e}/feed`,t)).map(i=>new b(i))})}getFeed(e){return s(this,null,function*(){return m.getFeed(this.id,e)})}static updateReadChapters(e,t,a=!1){return s(this,null,function*(){var p,n,o,l;if(!t.read&&!t.unread)return[];let i={chapterIdsRead:(n=(p=t.read)==null?void 0:p.map(d=>typeof d=="string"?d:d.id))!=null?n:[],chapterIdsUnread:(l=(o=t.unread)==null?void 0:o.map(d=>typeof d=="string"?d:d.id))!=null?l:[]};yield L(`/manga/${e}/read`,i,{updateHistory:a})})}updateReadChapters(e,t=!1){return s(this,null,function*(){return m.updateReadChapters(this.id,e,t)})}static getReadChapters(e){return s(this,null,function*(){let t={};for(let p=0;p<e.length;p+=100){let n=yield S("/manga/read",{ids:e.slice(p,p+100),grouped:!0});if(Array.isArray(n))if(e.length===1)n={[typeof e[0]=="string"?e[0]:e[0].id]:n};else throw new A("MangaDex did not respond with a grouped body.");for(let[o,l]of Object.entries(n))o in t?t[o].push(...l):t[o]=l}let a=yield b.getMultiple(Object.values(t).flat()),i={};for(let p in t)i[p]=a.filter(n=>t[p].includes(n.id));return i})}getReadChapters(){return s(this,null,function*(){let e=yield S(`/manga/${this.id}/read`);return yield b.getMultiple(e)})}static getRandom(e){return s(this,null,function*(){let t=yield S("/manga/random",e);return new m(t)})}static getByQuery(e){return s(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}getCovers(){return s(this,null,function*(){return v.getMangaCovers(this.id)})}static getFollowedManga(){return s(this,arguments,function*(e={limit:1/0,offset:0}){return(yield f("/user/follows/manga",e)).map(a=>new m(a))})}static getUserRatings(e){return s(this,null,function*(){let t=yield u("/rating",{manga:e}),a={};for(let i of e)typeof i!="string"&&(i=i.id),i in t.ratings?a[i]={rating:t.ratings[i].rating,createdAt:new Date(t.ratings[i].createdAt)}:a[i]=null;return a})}getUserRating(){return s(this,null,function*(){var t,a;return(a=(t=(yield m.getUserRatings([this.id]))[this.id])==null?void 0:t.rating)!=null?a:null})}static giveRating(e,t){return s(this,null,function*(){if(t>10||t<1)throw new Error("Rating must be in the range of 1-10 (inclusive).");yield L(`/rating/${e}`,{rating:t})})}giveRating(e){return s(this,null,function*(){yield m.giveRating(this.id,e)})}static removeRating(e){return s(this,null,function*(){yield u(`/rating/${e}`,void 0,{method:"DELETE"})})}removeRating(){return s(this,null,function*(){yield m.removeRating(this.id)})}static getFollowedFeed(e){return s(this,null,function*(){return(yield f("/user/follows/manga/feed",e)).map(a=>new b(a))})}static convertLegacyId(e,t){return s(this,null,function*(){let a=yield P("/legacy/mapping",{type:e,ids:t});return Object.fromEntries(a.map(i=>[i.attributes.legacyId,i.attributes.newId]))})}static getAllReadingStatus(e){return s(this,null,function*(){return(yield u("/manga/status",{status:e})).statuses})}static getReadingStatus(e){return s(this,null,function*(){return(yield u(`/manga/${e}/status`)).status})}getReadingStatus(){return s(this,null,function*(){return yield m.getReadingStatus(this.id)})}static setReadingStatus(e,t){return s(this,null,function*(){yield L(`/manga/${e}/status`,{status:t})})}setReadingStatus(e){return s(this,null,function*(){yield m.setReadingStatus(this.id,e)})}static getRelations(e,t=!1){return s(this,null,function*(){let i=(yield S(`/manga/${e}/relation`,{includes:t?["manga"]:void 0})).flatMap(p=>p.relationships.map(n=>R(w({},n),{related:p.attributes.relation})));return m.getRelatedManga(i)})}getRelations(e=!1){return s(this,null,function*(){return yield m.getRelations(this.id,e)})}static addRelation(e,t,a){return s(this,null,function*(){yield P(`/manga/${e}/relation`,{targetManga:t,relation:a})})}addRelation(e,t){return s(this,null,function*(){yield m.addRelation(this.id,e,t)})}static removeRelation(e,t){return s(this,null,function*(){yield u(`/manga/${e}/relation/${t}`,void 0,{method:"DELETE"})})}removeRelation(e){return s(this,null,function*(){yield m.removeRelation(this.id,e)})}static getStatistics(e){return s(this,null,function*(){return(yield u("/statistics/manga",{manga:e})).statistics})}getStatistics(){return s(this,null,function*(){return(yield m.getStatistics([this.id]))[this.id]})}static getDraft(e,t){return s(this,null,function*(){return new m(yield S(`/manga/draft/${e}`,{includes:t}))})}static searchDrafts(e){return s(this,null,function*(){return(yield f("/manga/draft",e)).map(a=>new m(a))})}static commitDraft(e,t){return s(this,null,function*(){let a=yield P(`/manga/draft/${e}/commit`,t);return new m(a)})}static create(e){return s(this,null,function*(){return new m(yield P("/manga",e))})}static delete(e){return s(this,null,function*(){yield u(`/manga/${e}`,void 0,{method:"DELETE"})})}delete(){return s(this,null,function*(){yield m.delete(this.id)})}update(e){return s(this,null,function*(){return new m(yield P(`/author/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}static getAggregate(e,t,a){return s(this,null,function*(){return(yield u(`/manga/${e}/aggregate`,{groups:t,translatedLanguage:a})).volumes})}getAggregate(e,t){return s(this,null,function*(){return m.getAggregate(this.id,e,t)})}static changeFollowship(e,t=!0){return s(this,null,function*(){yield u(`/manga/${e}/follow`,void 0,{method:t?"POST":"DELETE"})})}changeFollowship(e=!0){return s(this,null,function*(){yield m.changeFollowship(this.id,e)})}};var G=class extends g{constructor(e){super();this.id=e.id,this.username=e.attributes.username,this.roles=e.attributes.roles,this.version=e.attributes.version,this.groups=h.convertType("scanlation_group",e.relationships)}static get(e){return s(this,null,function*(){return new G(yield S(`/user/${e}`))})}static search(e){return s(this,null,function*(){return(yield f("/user",e)).map(a=>new G(a))})}static getMultiple(e){return s(this,null,function*(){return(yield E("/user",e)).map(a=>new G(a))})}static getByQuery(e){return s(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}static getLoggedInUser(){return s(this,null,function*(){return new G(yield S("/user/me"))})}static getFollowedUsers(){return s(this,arguments,function*(e={limit:1/0,offset:0}){return(yield f("/user/follows/user",e)).map(a=>new G(a))})}};var C=class extends g{constructor(e){var t;super();this.id=e.id,this.name=e.attributes.name,this.altNames=e.attributes.altNames.map(a=>new x(a)),this.website=e.attributes.website,this.ircServer=e.attributes.ircServer,this.ircChannel=e.attributes.ircChannel,this.discord=e.attributes.discord,this.contactEmail=e.attributes.contactEmail,this.description=e.attributes.description,this.twitter=e.attributes.twitter,this.mangaUpdates=e.attributes.mangaUpdates,this.focusedLanguage=e.attributes.focusedLanguage,this.locked=e.attributes.locked,this.official=e.attributes.official,this.inactive=e.attributes.inactive,this.publishDelay=e.attributes.publishDelay,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.updatedAt=new Date(e.attributes.updatedAt),this.leader=(t=h.convertType("leader",e.relationships).pop())!=null?t:null,this.members=h.convertType("member",e.relationships),this.exLicensed=e.attributes.exLicensed,this.verified=e.attributes.verified}static get(e){return s(this,null,function*(){return new C(yield S(`/group/${e}`))})}static search(e){return s(this,null,function*(){return(yield f("/group",e)).map(a=>new C(a))})}static getMultiple(e){return s(this,null,function*(){return(yield E("/group",e)).map(a=>new C(a))})}static getByQuery(e){return s(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}static create(e){return s(this,null,function*(){return new C(yield P("/group",e))})}static delete(e){return s(this,null,function*(){yield u(`/group/${e}`,void 0,{method:"DELETE"})})}delete(){return s(this,null,function*(){yield C.delete(this.id)})}update(e){return s(this,null,function*(){return new C(yield P(`/group/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}static changeFollowship(e,t=!0){return s(this,null,function*(){yield u(`/group/${e}/follow`,void 0,{method:t?"POST":"DELETE"})})}changeFollowship(e=!0){return s(this,null,function*(){yield C.changeFollowship(this.id,e)})}static getStatistics(e){return s(this,null,function*(){return(yield u("/statistics/group",{group:e})).statistics})}getStatistics(){return s(this,null,function*(){return(yield C.getStatistics([this.id]))[this.id]})}static getFollowedGroups(){return s(this,arguments,function*(e={limit:1/0,offset:0}){return(yield f("/user/follows/group",e)).map(a=>new C(a))})}};var F=class extends g{constructor(e){super();this.updateData(e)}updateData(e){"data"in e&&(e=e.data),this.id=e.id,this.isCommitted=e.attributes.isCommitted,this.isProcessed=e.attributes.isProcessed,this.isDeleted=e.attributes.isDeleted,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.updatedAt=new Date(e.attributes.updatedAt),this.uploader=h.convertType("user",e.relationships).pop(),this.manga=h.convertType("manga",e.relationships).pop(),this.groups=h.convertType("scanlation_group",e.relationships),this.pages=e.relationships.filter(t=>t.type==="upload_session_file").map(t=>{if(!t.attributes)throw new Error("MangaDex did not return session file attributes in a relationship. Did you forget a reference expansion (ie includes[])?");return new X({id:t.id,attributes:t.attributes,type:"upload_session_file"})}),this.pages.sort((t,a)=>t.num-a.num)}static begin(i){return s(this,arguments,function*(e,t=[],a=!1){return a&&(yield F.cancelCurrentSession()),new F(yield L("/upload/begin",{manga:typeof e=="string"?e:e.id,groups:t.map(p=>typeof p=="string"?p:p.id)},{includes:["upload_session_file"]}))})}static beginChapterEdit(e,t=!1){return s(this,null,function*(){return t&&(yield F.cancelCurrentSession()),new F(yield L(`/upload/begin/${e.id}`,{version:e.version},{includes:["upload_session_file"]}))})}static getCurrentSession(){return s(this,null,function*(){return new F(yield u("/upload",{includes:["upload_session_file"]}))})}static cancelCurrentSession(){return s(this,null,function*(){let e;try{e=yield F.getCurrentSession()}catch(t){}e&&(yield e.close())})}close(){return s(this,null,function*(){yield u(`/upload/${this.id}`,void 0,{method:"DELETE"}),this.isDeleted=!0})}commit(e,t){return s(this,null,function*(){t?t=t.map(a=>typeof a=="string"?a:a.id):t=this.pages.map(a=>a.id),this.updateData(yield L(`/upload/${this.id}/commit`,{chapterDraft:e,pageOrder:t},{includes:["upload_session_file"]}))})}uploadPages(e){return s(this,null,function*(){let t=Math.max(...this.pages.map(l=>l.num),0),a=e.map((l,d)=>({data:l,name:(d+t).toString()})),i=[];for(;a.length>0;)i.push(Q(`/upload/${this.id}`,{files:a.splice(0,10)}));let p=yield Promise.all(i),n=p.flatMap(l=>{var d;return(d=l.errors)!=null?d:[]});if(n.length>0)throw new A(n);let o=p.flatMap(l=>{var d;return(d=l.data)!=null?d:[]}).map(l=>new X(l));o.sort((l,d)=>l.num-d.num),this.pages.push(...o)})}deletePages(e){return s(this,null,function*(){let t=e.map(a=>typeof a=="string"?a:a.id);yield L(`/upload/${this.id}/batch`,t,void 0,"DELETE"),this.pages=this.pages.filter(a=>!t.includes(a.id))})}},X=class extends g{constructor(e){super();this.id=e.id,this.originalFileName=e.attributes.originalFileName,this.fileHash=e.attributes.fileHash,this.fileSize=e.attributes.fileSize,this.mimeType=e.attributes.mimeType,this.source=e.attributes.source,this.version=e.attributes.version,this.num=parseInt(this.originalFileName),isNaN(this.num)&&(this.num=parseInt(this.fileHash,16)),isNaN(this.num)&&(this.num=1e3)}};var k=class{constructor(r){this.data=r}getSessionToken(){return s(this,null,function*(){if(Date.now()>this.data.refreshExpiration)throw new T("Refresh token has expired. Please login again.");if(Date.now()>this.data.accessExpiration&&(yield this.refreshTokens(),!(yield J(this.data.accessToken))))throw new T("Failed to validate auth token. Please login again.");return this.data.accessToken})}refreshTokens(){return s(this,null,function*(){let r=yield Z("/realms/mangadex/protocol/openid-connect/token",{grant_type:"refresh_token",refresh_token:this.data.refreshToken,client_id:this.data.clientId,client_secret:this.data.clientSecret});this.data.accessToken=r.access_token,this.data.accessExpiration=K(r.expires_in),this.data.refreshToken=r.refresh_token,this.data.refreshExpiration=K(r.refresh_expires_in)})}static login(r,e=!0){return s(this,null,function*(){let t=yield Z("/realms/mangadex/protocol/openid-connect/token",{grant_type:"password",username:r.username,password:r.password,client_id:r.clientId,client_secret:r.clientSecret}),a=new k(R(w({},r),{accessToken:t.access_token,accessExpiration:K(t.expires_in),refreshToken:t.refresh_token,refreshExpiration:K(t.refresh_expires_in)}));return e&&H(a),a})}};function K(c){return c*1e3+Date.now()-5e3}var N=class{constructor(r){this.data=r}getSessionToken(){return s(this,null,function*(){if(Date.now()-this.data.timestamp>=894e3&&(yield this.refreshTokens(),!(yield this.checkSessionToken())))throw new T("Failed to validate auth token. Please login again.");return this.data.session})}setActive(){H(this)}static login(r,e){return s(this,null,function*(){let t=yield L("/auth/login",{username:r,password:e}),a=t.token.session,i=t.token.refresh;if(!a||!i)throw new T("MangaDex did not return auth tokens.");let p=new N({session:a,refresh:i,timestamp:Date.now()});return p.setActive(),p})}refreshTokens(){return s(this,null,function*(){let r=yield L("/auth/refresh",{token:this.data.refresh},void 0,"POST",{noAuth:!0});if(!r.token)throw new T(`Failed to refresh auth tokens, MangaDex did not return any. ${r.message}`);let e=r.token.session,t=r.token.refresh;if(!e||!t)throw new T(`MangaDex did not return auth tokens. ${r.message}`);this.data={session:e,refresh:t,timestamp:Date.now()}})}checkSessionToken(){return J(this.data.session)}};var M=class extends g{constructor(e){super();this.id=e.id,this.name=e.attributes.name,this.visibility=e.attributes.visibility,this.version=e.attributes.version,this.creator=h.convertType("user",e.relationships).pop(),this.manga=h.convertType("manga",e.relationships)}static get(e){return s(this,null,function*(){return new M(yield S(`/list/${e}`))})}static create(e){return s(this,null,function*(){return new M(yield P("/list",e))})}static delete(e){return s(this,null,function*(){yield u(`/list/${e}`,void 0,{method:"DELETE"})})}delete(){return s(this,null,function*(){yield M.delete(this.id)})}update(e){return s(this,null,function*(){var t;return new M(yield P(`/list/${this.id}`,R(w({},e),{name:(t=e.name)!=null?t:this.name,version:this.version+1}),void 0,"PUT"))})}static follow(e){return s(this,null,function*(){yield u(`/list/${e}/follow`,void 0,{method:"POST"})})}follow(){return s(this,null,function*(){yield M.follow(this.id)})}static unfollow(e){return s(this,null,function*(){yield u(`/list/${e}/follow`,void 0,{method:"DELETE"})})}unfollow(){return s(this,null,function*(){yield M.unfollow(this.id)})}static addManga(e,t){return s(this,null,function*(){typeof t!="string"&&(t=t.id),yield u(`/manga/${t}/list/${e}`,void 0,{method:"POST"})})}addManga(e){return s(this,null,function*(){yield M.addManga(this.id,e)})}static removeManga(e,t){return s(this,null,function*(){typeof t!="string"&&(t=t.id),yield u(`/manga/${t}/list/${e}`,void 0,{method:"DELETE"})})}removeManga(e){return s(this,null,function*(){yield M.removeManga(this.id,e)})}static getLoggedInUserLists(e=1/0,t=0){return s(this,null,function*(){return(yield f("/user/list",{limit:e,offset:t})).map(i=>new M(i))})}static getUserLists(e,t=1/0,a=0){return s(this,null,function*(){return typeof e!="string"&&(e=e.id),(yield f(`/user/${e}/list`,{limit:t,offset:a})).map(p=>new M(p))})}static getFeed(e,t){return s(this,null,function*(){return(yield f(`/list/${e}/feed`,t)).map(i=>new b(i))})}getFeed(e){return s(this,null,function*(){return yield M.getFeed(this.id,e)})}static getFollowedLists(e=1/0,t=0){return s(this,null,function*(){return(yield f("/user/follows/list",{limit:e,offset:t})).map(i=>new M(i))})}changeVisibility(e){return s(this,null,function*(){return yield this.update({visibility:e})})}rename(e){return s(this,null,function*(){return yield this.update({name:e})})}updateMangaList(e){return s(this,null,function*(){return e=e.map(t=>typeof t=="string"?t:t.id),yield this.update({manga:e})})}};h.getRegisteredTypes().length===0&&(h.registerTypes(["manga"],m),h.registerTypes(["author","artist"],U),h.registerTypes(["cover_art"],v),h.registerTypes(["chapter"],b),h.registerTypes(["user","member","leader"],G),h.registerTypes(["scanlation_group"],C),h.lockTypeMap());var Qt=x.setGlobalLocale,Jt=h.resolveAll,Xt=m.convertLegacyId,Yt=N.login,jt=k.login,ea=te,ta=ae;export{U as Author,b as Chapter,v as Cover,C as Group,N as LegacyAuthClient,M as List,m as Manga,k as PersonalAuthClient,$ as Tag,F as UploadSession,G as User,Xt as convertLegacyId,ta as getCurrentAuthClient,Yt as login,jt as loginPersonal,ea as logout,Jt as resolveArray,Qt as setGlobalLocale,he as useDebugServer}; //# sourceMappingURL=index.mjs.map