@serifpersia/dango 4.0.1 → 4.0.2
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/README.md +1 -1
- package/client/dist/assets/{AnimeCard-DpZ4X9XD.js → AnimeCard-B-3qrNhu.js} +1 -1
- package/client/dist/assets/AnimeInfo-DXoNbSao.js +1 -0
- package/client/dist/assets/{AnimeInfoPage-CsDJS_8b.js → AnimeInfoPage-CRWoCwXo.js} +2 -2
- package/client/dist/assets/{Asmr-BdCT1sg3.js → Asmr-z6PNn8Ld.js} +1 -1
- package/client/dist/assets/{AsmrPopup-CNqixGCf.js → AsmrPopup-Cc-aIYXd.js} +1 -1
- package/client/dist/assets/{AsmrResetProgressModal-BOXFH3f2.js → AsmrResetProgressModal-D4Mp_-lx.js} +1 -1
- package/client/dist/assets/Home-9ZTaG1WX.js +1 -0
- package/client/dist/assets/Insights-Bf92STPA.js +1 -0
- package/client/dist/assets/{LibraryListPage-CIILJZTu.js → LibraryListPage-CNjzasIi.js} +1 -1
- package/client/dist/assets/{ListeningList-oMw31vdT.js → ListeningList-1mBIfxxH.js} +1 -1
- package/client/dist/assets/{Manga-CFSwxy0V.js → Manga-B3_TdzgY.js} +1 -1
- package/client/dist/assets/MangaInfoPage-DnDwJDWC.js +1 -0
- package/client/dist/assets/{MangaReadPage-Bk_RFHao.js → MangaReadPage-Cq4NYq31.js} +1 -1
- package/client/dist/assets/{MangaResetProgressModal-CVPwJSlW.js → MangaResetProgressModal-DaZmK9CX.js} +1 -1
- package/client/dist/assets/{Mature-BqODUa8k.js → Mature-CbQWqjUS.js} +1 -1
- package/client/dist/assets/{MatureConsentModal-BoSwjOI5.js → MatureConsentModal-CEoZ_OA0.js} +1 -1
- package/client/dist/assets/MediaCard-B-TmXdgl.js +1 -0
- package/client/dist/assets/{OptionListMenu-COsyoLhE.js → OptionListMenu-ArbsAjlv.js} +1 -1
- package/client/dist/assets/{Player-Ctxb19Xq.js → Player-4wh-a_ee.js} +2 -2
- package/client/dist/assets/{PlayerProvider-BpHzod7D.js → PlayerProvider-CbamWD19.js} +1 -1
- package/client/dist/assets/{PlayerSettings-BN8IC5it.js → PlayerSettings-DehU56D4.js} +1 -1
- package/client/dist/assets/{QueueOptionsButton-BubxC3vl.js → QueueOptionsButton-DqoDQST5.js} +1 -1
- package/client/dist/assets/QueueRail-ClrcV9LL.js +1 -0
- package/client/dist/assets/{ReadingList-CXQy4sxe.js → ReadingList-Cy1BKzJs.js} +1 -1
- package/client/dist/assets/{ResetProgressModal-tI6IHvmP.js → ResetProgressModal-BdcBPlC1.js} +1 -1
- package/client/dist/assets/{Search-B9v2KFw9.js → Search-5PvZ8pAC.js} +1 -1
- package/client/dist/assets/Settings-O0oOrEUd.js +21 -0
- package/client/dist/assets/{SkeletonGrid-U0v5ZOMU.js → SkeletonGrid-DqN0laN_.js} +1 -1
- package/client/dist/assets/{Trackers-BApb11Vz.js → Trackers-DxBWYwss.js} +2 -2
- package/client/dist/assets/{Tv-B23iWxt-.js → Tv-Ox6p6iEx.js} +3 -3
- package/client/dist/assets/TvInfo-DjPQ7BZn.js +1 -0
- package/client/dist/assets/{TvPopup-B_BBkSA6.js → TvPopup-CCTQiS84.js} +1 -1
- package/client/dist/assets/{TvSearch-B6DALvV9.js → TvSearch-Baig87wj.js} +1 -1
- package/client/dist/assets/{TvWatchlist-DRms0v9m.js → TvWatchlist-D-yxvaKC.js} +1 -1
- package/client/dist/assets/{VirtualKeyboard-BLXSHA6_.js → VirtualKeyboard-Bf7wvuX3.js} +1 -1
- package/client/dist/assets/{WatchAlong-DqiBYW8W.js → WatchAlong-D9NsqbWz.js} +1 -1
- package/client/dist/assets/{WatchAlongPanel-CDbbTIqv.js → WatchAlongPanel-DRsYyjM7.js} +1 -1
- package/client/dist/assets/{Watchlist-B8NP7imi.js → Watchlist-oYAx_dFL.js} +1 -1
- package/client/dist/assets/{index-BHWOY-pi.js → index-CPhXtUuw.js} +4 -4
- package/client/dist/assets/{libraryInvalidation-D8h84CFM.js → libraryInvalidation-hcASRQHn.js} +1 -1
- package/client/dist/assets/{playbackCompletion-Cq6Pbug7.js → playbackCompletion-D1Gm0GbH.js} +1 -1
- package/client/dist/assets/{useAnimeInfoData-DhoidxrL.js → useAnimeInfoData-BsFz9uiF.js} +1 -1
- package/client/dist/assets/{useMangaLibrary-Bogr8MQ7.js → useMangaLibrary-DbvnlYV9.js} +1 -1
- package/client/dist/assets/{useMangaPopup-BV_Jk_2y.js → useMangaPopup-2lqmdmS5.js} +1 -1
- package/client/dist/assets/{useProviders-CbFHcVVq.js → useProviders-BgAgACS8.js} +1 -1
- package/client/dist/assets/{useTv-DBYyKAM6.js → useTv-OX_q_uaI.js} +1 -1
- package/client/dist/assets/{useTvLibrary-D2tKj7cP.js → useTvLibrary-DaLHYFID.js} +1 -1
- package/client/dist/assets/useWatchAlongPlayer-B7Yj2s3s.js +10 -0
- package/client/dist/index.html +1 -1
- package/package.json +2 -2
- package/server/dist/server.js +1 -1
- package/server/package.json +1 -1
- package/client/dist/assets/AnimeInfo-CnBDIp7R.js +0 -1
- package/client/dist/assets/Home-D-SVz5cA.js +0 -1
- package/client/dist/assets/Insights-DybhDzpO.js +0 -1
- package/client/dist/assets/MangaInfoPage-DhbrQs6K.js +0 -1
- package/client/dist/assets/MediaCard-BbqpD03k.js +0 -1
- package/client/dist/assets/QueueRail-CUsYeL0A.js +0 -1
- package/client/dist/assets/Settings-C0Zb4_G5.js +0 -21
- package/client/dist/assets/TvInfo-DEWBzt0W.js +0 -1
- package/client/dist/assets/useWatchAlongPlayer-BmHRwl6J.js +0 -10
package/server/dist/server.js
CHANGED
|
@@ -466,7 +466,7 @@ ${u}
|
|
|
466
466
|
}
|
|
467
467
|
}
|
|
468
468
|
`,B=t?.toLowerCase().replace(/[^a-z0-9]/g,""),k=t?.trim()?pB(t).filter(be=>be.toLowerCase().replace(/[^a-z0-9]/g,"")===B):[""],x=new Map,U=null,W=!1;for(let[be,De]of k.entries()){if(U=await ur(S,{...C,...De?{search:De}:{}}),!U?.data)break;for(let K of U.data.Page.media??[])K.id&&x.set(K.id,K);if(be>0&&(W=!0),(U.data.Page.media?.length??0)>=n)break}if(!U?.data&&x.size===0){if(_i()){let De=await Of(async()=>{let j=Wr(),Z=await wd(j,{query:t,page:r,perPage:n,format:i&&i!=="ALL"&&i!=="ADULT"?i:void 0,status:s,season:o,seasonYear:a,genre:u,genre_in:c,genre_not_in:d,averageScore_greater:g,episodes_greater:p,isAdult:i==="ADULT"?!0:m,sort:I});if(Z.length>0)try{let Ie=await wd(j,{query:t,page:r,perPage:n,format:i&&i!=="ALL"&&i!=="ADULT"?i:void 0,status:s,season:o,seasonYear:a,genre:u,genre_in:c,averageScore_greater:g,episodes_greater:p,sort:I,isAdult:!0},!1);if(Ie.length>0){let Bt=new Set(Ie.map(er=>er.id));Z=Z.filter(er=>!Bt.has(er.id))}}catch{}return Z},()=>Qa({query:t,page:r,perPage:n,format:i&&i!=="ALL"&&i!=="ADULT"?i:void 0,status:s,season:o,seasonYear:a,genre:u,genre_in:c,genre_not_in:d,averageScore_greater:g,episodes_greater:p,isAdult:i==="ADULT"?!0:m,sort:I}));try{await pD(Wr(),De)}catch{}let K=hae(De);if(K.length===0&&t?.trim())try{let Z=(await TB(Wr(),t,r)).entries.map(Ie=>bd(Ie));try{await pD(Wr(),Z)}catch{}K=Z.map(Ie=>Er(Ie))}catch{}return K}return[]}let X=[...x.values()];if(!X||X.length===0)return[];W&&X.sort((be,De)=>{let K=j=>Math.max(0,...[j.title?.romaji,j.title?.english,j.title?.native].filter(Z=>!!Z).map(Z=>vc([{title:Z}],[t??""])?.score??0));return K(De)-K(be)});let ae=new Set,pe=[];for(let be of X)!be.id||ae.has(be.id)||(ae.add(be.id),pe.push(Er(be)));return pe.slice(0,n)}function Y8(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.browse=="function"&&typeof t.getEpisodes=="function"&&typeof t.getStreamUrls=="function"&&typeof t.getImages=="function"&&typeof t.getChapters=="function"}var yae=/^[a-z0-9][a-z0-9-]*$/i,gKe=/^[0-9a-f]{64}$/i,bae=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Qae(e,t){let r=e.split(".").map(Number),n=t.split(".").map(Number);for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]>n[i];return!0}function RB(e){if(!e||typeof e!="object")throw new Error("registry: not an object");let t=e;if(!Number.isSafeInteger(t.version)||t.version<0)throw new Error("registry.version must be a non-negative integer");if(!Array.isArray(t.providers))throw new Error("registry.providers must be an array");let r=t.providers.map((i,s)=>pKe(i,s)),n=new Set;for(let i of r){let s=i.id.toLowerCase();if(n.has(s))throw new Error(`registry: duplicate provider id "${i.id}"`);n.add(s)}return{version:t.version,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:void 0,providers:r}}function pKe(e,t){if(!e||typeof e!="object")throw new Error(`registry.providers[${t}]: not an object`);let r=e,n=r.id,i=r.entry,s=r.label,o=r.version;if(typeof n!="string"||!yae.test(n.trim()))throw new Error(`registry.providers[${t}].id must match ${yae}`);if(typeof s!="string"||!s.trim())throw new Error(`registry.providers[${t}].label must be a non-empty string`);if(typeof o!="string"||!bae.test(o.trim()))throw new Error(`registry.providers[${t}].version must be major.minor.patch`);if(r.minDango!==void 0&&(typeof r.minDango!="string"||!bae.test(r.minDango)))throw new Error(`registry.providers[${t}].minDango must be major.minor.patch`);let a=r.embedBase;if(a!==void 0&&(typeof a!="string"||!/^https:\/\/[^/]+/i.test(a.trim())))throw new Error(`registry.providers[${t}].embedBase must be an https URL`);if((typeof i!="string"||!i.trim())&&a===void 0)throw new Error(`registry.providers[${t}].entry must be a non-empty string`);if(r.sha256!==void 0&&(typeof r.sha256!="string"||!gKe.test(r.sha256.trim())))throw new Error(`registry.providers[${t}].sha256 must be 64 hex chars`);if(r.mature!==void 0&&typeof r.mature!="boolean")throw new Error(`registry.providers[${t}].mature must be boolean`);if(r.kind!==void 0&&r.kind!=="anime"&&r.kind!=="asmr"&&r.kind!=="manga"&&r.kind!=="tv")throw new Error(`registry.providers[${t}].kind must be anime|asmr|manga|tv`);if(r.sub!==void 0&&r.sub!=="soft"&&r.sub!=="hard"&&r.sub!=="mixed")throw new Error(`registry.providers[${t}].sub must be soft|hard|mixed`);if(r.tier!==void 0&&r.tier!=="direct"&&r.tier!=="embed"&&r.tier!=="cookie")throw new Error(`registry.providers[${t}].tier must be direct|embed|cookie`);let A;if(r.modes!==void 0){if(!Array.isArray(r.modes))throw new Error(`registry.providers[${t}].modes must be an array`);A=[];for(let u of r.modes){if(u!=="sub"&&u!=="dub")throw new Error(`registry.providers[${t}].modes must contain only sub|dub`);A.includes(u)||A.push(u)}}return{id:n.trim(),label:s.trim(),version:o.trim(),entry:typeof i=="string"?i.trim():void 0,embedBase:typeof a=="string"?a.trim().replace(/\/+$/,""):void 0,sha256:typeof r.sha256=="string"?r.sha256.trim().toLowerCase():void 0,minDango:typeof r.minDango=="string"?r.minDango:void 0,mature:typeof r.mature=="boolean"?r.mature:!1,kind:a!==void 0?"tv":r.kind==="asmr"||r.kind==="manga"||r.kind==="tv"?r.kind:"anime",sub:r.sub,tier:r.tier,modes:A,browse:mKe(r.browse,t),proxy:EKe(r.proxy,t),auth:r.auth==="cookie"?"cookie":void 0,enabledByDefault:r.enabledByDefault!==!1}}function EKe(e,t){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`registry.providers[${t}].proxy must be an object`);let r=e,n={};for(let i of["hosts","suffixes","mirrors"])if(r[i]!==void 0){if(!Array.isArray(r[i])||!r[i].every(s=>typeof s=="string"&&s))throw new Error(`registry.providers[${t}].proxy.${i} must be a non-empty string array`);n[i]=r[i].map(s=>s.trim().toLowerCase())}for(let i of["referer","origin"])if(r[i]!==void 0){if(typeof r[i]!="string"||!/^https:\/\//i.test(r[i].trim()))throw new Error(`registry.providers[${t}].proxy.${i} must be an https URL`);n[i]=r[i].trim()}for(let i of["originFromReferer","scrape","cfCookie","embedPatch"])if(r[i]!==void 0){if(typeof r[i]!="boolean")throw new Error(`registry.providers[${t}].proxy.${i} must be boolean`);n[i]=r[i]}return n}function mKe(e,t){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`registry.providers[${t}].browse must be an object`);let r=e,n={};for(let i of["genre","order","studio","sort"])if(r[i]!==void 0){if(typeof r[i]!="boolean")throw new Error(`registry.providers[${t}].browse.${i} must be boolean`);n[i]=r[i]}if(r.pageSize!==void 0){if(typeof r.pageSize!="number"||!Number.isInteger(r.pageSize)||r.pageSize<1)throw new Error(`registry.providers[${t}].browse.pageSize must be a positive integer`);n.pageSize=r.pageSize}return n}var QD=15e3,wae=JSON.parse(Pi.readFileSync(As.join(Pn.PACKAGE_ROOT,"package.json"),"utf8")).version;async function CD(e,t){let r=`${e}.${bD.randomUUID()}.tmp`;try{await Pi.promises.writeFile(r,t),await Pi.promises.rename(r,e)}finally{await Pi.promises.rm(r,{force:!0})}}var vB="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";function kB(e,t,r){let n,i=new Promise((s,o)=>{n=setTimeout(()=>o(new Error(`${r} timed out after ${t}ms`)),t)});return Promise.race([e,i]).finally(()=>clearTimeout(n))}function LB(e){return/^https?:\/\//i.test(e)}function W8(e){return e.startsWith("file://")?CKe(e):e}function bKe(e){return LB(e)||e.startsWith("file://")?!1:e.includes("/")||e.includes("\\")||e.endsWith(".json")}async function QKe(e){if(LB(e)){let r=await kB(fetch(e,{headers:{"User-Agent":vB,Accept:"application/json"}}),QD,"registry fetch");if(!r.ok)throw new Error(`registry HTTP ${r.status}: ${e}`);return Dl(Buffer.from(await r.arrayBuffer()))}let t=As.resolve(W8(e));return await Pi.promises.readFile(t)}async function wKe(e){if(LB(e)){let r=await kB(fetch(e,{headers:{"User-Agent":vB,Accept:"text/javascript,*/*"}}),QD,"provider fetch");if(!r.ok)throw new Error(`provider HTTP ${r.status}: ${e}`);return Dl(Buffer.from(await r.arrayBuffer()))}let t=As.resolve(W8(e));return await Pi.promises.readFile(t)}function SKe(e,t){let r=(e??"").trim();if(LB(r)||r.startsWith("file://"))return r;if(LB(t))return new URL(r,t).href;let n=As.dirname(As.resolve(W8(t)));return As.resolve(n,r)}function BD(e){return bD.createHash("sha256").update(e).digest("hex")}function TKe(e,t,r){let n;try{n=Buffer.from(e,"base64url")}catch{return null}if(!n.length||n.length%16!==0)return null;try{let i=Buffer.alloc(32);Buffer.from(t).copy(i);let s=bD.createDecipheriv("aes-256-cbc",i,Buffer.from(r)),o=Buffer.concat([s.update(n),s.final()]);return JSON.parse(o.toString("utf8"))}catch{return null}}function Sae(e,t){let r=["-sSL","-A",vB,...Object.entries(t??{}).flatMap(([o,a])=>["-H",`${o}: ${a}`]),"--max-time","15","-w",`
|
|
469
|
-
__HTTP_STATUS__%{http_code}`,"--",e],n;try{n=IKe("curl",r,{encoding:"utf-8",maxBuffer:10*1024*1024})}catch{return null}let i=n.match(/__HTTP_STATUS__(\d+)\s*$/);return{status:i?parseInt(i[1],10):0,body:i&&i.index!==void 0?n.slice(0,i.index):n}}function DKe(e){let t=async(r,n,i=QD)=>kB(fetch(r,{...n,headers:{"User-Agent":vB,...n?.headers}}),i,`fetch ${r}`);return{cache:{get:r=>e.get(r),set:(r,n,i)=>{e.set(r,n,i)}},logger:{info:(r,n)=>{O.info(r,n)},warn:(r,n)=>{O.warn(r,n)},error:(r,n)=>{O.error(r,n)},debug:(r,n)=>{O.debug(r,n)}},fetchText:async(r,n)=>{try{let i=await t(r,n);return i.ok?await i.text():null}catch{return null}},fetchJson:async(r,n)=>{let i=await t(r,n);if(!i.ok)throw new Error(`HTTP ${i.status}: ${r}`);return Yt(i)},proxyUrl:(r,n)=>`/api/proxy?url=${encodeURIComponent(r)}&referer=${encodeURIComponent(n)}`,userAgent:vB,titleMatch:{buildQueryVariants:pB,pickBestMatch:vc},resolveBestShowId:async(r,n,i)=>{let s=[r,n].filter(o=>typeof o=="string"&&o.trim().length>0);if(s.length===0)return null;for(let o of pB(r,n)){let a;try{a=await i(o)}catch(u){if(u.message==="AUTH_REQUIRED")throw u;continue}if(!a||a.length===0)continue;let A=vc(a.filter(u=>u&&typeof u.id=="string"&&u.id.length>0),s);if(A)return A.item.id}return null},anilist:{request:(r,n)=>ur(r,n),parseMalId:_s,searchByTitle:Os},kitsu:{metaByAnilistId:BB},tmdb:{base:To,image:Sd,get:async r=>{try{let n=await Fc(),i=r.includes("?")?"&":"?",s=await t(`${To}${r}${i}api_key=${n}`);return s.ok?Yt(s):null}catch{return null}}},request:{get:r=>eD.getStore()?.get(r)},cookies:{sanitizeCfClearance:_p,buildCfClearanceCookie:pu},crypto:{aes256CbcDecryptJson:TKe,hmacSha256Base64Url:(r,n)=>bD.createHmac("sha256",r).update(n).digest("base64url")},scraping:{fetch:async(r,n)=>{let i=typeof r=="string"?{url:r,...n??{}}:r,{url:s,...o}=i,a=await yKe({url:s,method:"GET",responseType:"text",throwHttpErrors:!1,...o});return{statusCode:a.statusCode,body:String(a.body??""),headers:a.headers}}},curl:{getJson:async(r,n)=>{try{let i=Sae(r,n);return!i||i.status!==200?null:JSON.parse(i.body)}catch{return null}},getText:async(r,n)=>{let i=Sae(r,n);return!i||i.status!==200?null:i.body}},cheerio:{load:r=>S2(r)}}}function q8(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.name=="string"?t:null}function xae(e,t){return t.every(r=>typeof e[r]=="function")}function vae(e){let t=q8(e);return!!t&&xae(t,["search","getEpisodes","getStreamUrls"])}function kae(e){let t=q8(e);return!!t&&xae(t,["search","getDetail","getChapters","getPages"])}function Lae(e){let t=q8(e);return!!t&&(typeof t.getSources=="function"||typeof t.getEmbedUrl=="function")}function NKe(e,t){return e==="manga"?kae(t):e==="tv"?Lae(t):e==="asmr"?Y8(t):vae(t)}function Tae(e,t,r,n){return t.kind==="manga"?kae(n)?(e.mangaProviders[r]=n,!0):!1:t.kind==="tv"?Lae(n)?(e.tvProviders[r]=n,!0):!1:t.kind==="asmr"?Y8(n)?(e.asmrProviders[r]=n,!0):!1:vae(n)?(e.providers[r]=n,!0):!1}function RKe(e,t){let r=t.trim().replace(/\/+$/,"");return{name:e,getEmbedUrl:async n=>{let i=Number(n.tmdbId);return i?n.type==="movie"?`${r}/movie/${i}`:`${r}/tv/${i}/${n.season||1}/${n.episode||1}`:null}}}async function V8(e,t,r,n,i){if(e.minDango&&!Qae(wae,e.minDango))return{provider:null,error:`requires dango ${e.minDango}, running ${wae}`};if(e.embedBase)return{provider:RKe(e.id,e.embedBase)};let s=SKe(e.entry,t);await Pi.promises.mkdir(r,{recursive:!0});let o=xB(e),a=As.join(r,o),A=`${a}:${e.kind??"anime"}`,u=null;try{let h=await Pi.promises.readFile(a);(e.sha256&&BD(h)===e.sha256||!e.sha256&&i)&&(u=h)}catch{}if(u){let h=yD.get(A);if(h)return O.debug({provider:e.id,version:e.version},"remote provider reused cached instance"),{provider:h.provider,facets:h.facets}}else{try{u=await wKe(s)}catch(h){return{provider:null,error:`download failed: ${h.message}`}}if(e.sha256){if(BD(u)!==e.sha256)return{provider:null,error:`sha256 mismatch for ${e.id}`}}else if(!i)return{provider:null,error:`missing sha256 for ${e.id}`};await CD(a,u)}let c=`${e.version}-${e.sha256??"nosha"}`,l=await vKe(a,c,n,e);return l.provider&&!l.error&&yD.set(A,{provider:l.provider,facets:l.facets}),l}var yD=new Map;function xB(e){return`${e.id}-${e.version}-${e.sha256??"nosha"}.mjs`}function xKe(e){let t,r;for(let[n,i]of Object.entries(e)){if(n==="default"||!Array.isArray(i)||i.length===0||!i.every(a=>typeof a=="string"&&a.length>0))continue;let s=i.filter(a=>a.length<=64).slice(0,500);if(s.length===0)continue;let o=n.toUpperCase();o.includes("GENRE")||o.includes("TAG")?t??=s:(o.includes("ORDER")||o.includes("SORT"))&&(r??=s)}if(!(!t&&!r))return{...t?{genres:t}:{},...r?{orders:r}:{}}}async function vKe(e,t,r,n){let i=n.id,s;try{let A=`${BKe(e).href}?v=${encodeURIComponent(t)}`;s=await kB(import(A),QD,`import ${i}`)}catch(A){return{provider:null,error:`import failed: ${A.message}`}}let o=s.default;if(typeof o!="function")return{provider:null,error:"missing default factory export"};let a;try{a=await kB(Promise.resolve(o(r)),1e4,`factory ${i}`)}catch(A){return{provider:null,error:`factory failed: ${A.message}`}}return NKe(n.kind,a)?{provider:a,facets:xKe(s)}:{provider:null,error:"invalid provider shape"}}async function kKe(e,t,r){if(e.embedBase)return V8(e,"",t,r,!1);if(!e.sha256)return{provider:null,error:"no verified fallback"};let n=As.join(t,xB(e)),i;try{i=await Pi.promises.readFile(n)}catch{return{provider:null,error:"no cached fallback file"}}return BD(i)!==e.sha256?{provider:null,error:"cached fallback failed verification"}:V8(e,"",t,r,!1)}var Dae;function Mae(e){return Dae??=LKe(e).finally(()=>{Dae=void 0})}async function LKe(e){let t=(e.registryUrl??Ae.PROVIDER_REPO_URL??"").trim(),r={registryLoaded:!1,providers:{},mangaProviders:{},tvProviders:{},asmrProviders:{},catalog:[],proxyRules:[]};if(!t)return r;let n=As.join(Pn.ROOT,"remote-providers"),i=As.join(n,"registry.json"),s=As.join(n,"active.json"),o=null;try{o=RB(JSON.parse(await Pi.promises.readFile(s,"utf8")))}catch{try{o=RB(JSON.parse(await Pi.promises.readFile(i,"utf8")));for(let f of o.providers){if(f.embedBase||!f.sha256)continue;let g=As.join(n,`${f.id}-${f.version}.mjs`);try{let p=await Pi.promises.readFile(g);BD(p)===f.sha256&&await CD(As.join(n,xB(f)),p)}catch{}}}catch{}}let a=new Map((o?.providers??[]).map(f=>[f.id.toLowerCase(),f])),A;try{let f=await QKe(t);A=RB(JSON.parse(f.toString("utf8")))}catch(f){O.error({err:f,registryUrl:t},"remote providers: manifest fetch failed, trying disk cache");try{A=RB(JSON.parse(await Pi.promises.readFile(i,"utf8")))}catch{return r}}r.registryLoaded=!0;let u=[],c=new Set((e.enabledProviders??[]).map(f=>f.toLowerCase())),l=c.size>0,h=DKe(e.cache),d=e.allowUnsigned??(process.env.DANGO_ALLOW_UNSIGNED_PROVIDERS==="1"||bKe(t));for(let f of A.providers){let g=f.id.toLowerCase();if(f.enabledByDefault===!1&&(!l||!c.has(g))){r.catalog.push(qp(f,!1,"disabled by default"));continue}if(l&&!c.has(g)){r.catalog.push(qp(f,!1,"not in enabledProviders"));continue}let{provider:p,facets:m,error:I}=await V8(f,t,n,h,d);if(p&&!I){if(!Tae(r,f,g,p)){r.catalog.push(qp(f,!1,"invalid provider shape for kind")),O.warn({provider:f.id},"remote provider kind mismatch, skipped");continue}r.catalog.push(Rae(m,Nae(f,p,qp(f,!0)))),u.push(f),f.proxy&&r.proxyRules.push(f.proxy),O.info({provider:f.id,version:f.version},"remote provider loaded")}else{let C=a.get(g);if(C){let y=await kKe(C,n,h);if(y.provider&&!y.error&&(Tae(r,C,g,y.provider)||(y.error="cached fallback failed validation")),y.provider&&!y.error){r.catalog.push({...Rae(y.facets,Nae(C,y.provider,qp(C,!0))),error:`serving cached ${C.version}: ${I}`}),u.push(C),C.proxy&&r.proxyRules.push(C.proxy),O.warn({provider:f.id,error:I,fallback:C.version},"remote provider update failed, serving cached version");continue}}r.catalog.push(qp(f,!1,I)),C&&u.push(C),f.proxy&&r.proxyRules.push(f.proxy),O.warn({provider:f.id,error:I},"remote provider skipped")}}await Pi.promises.mkdir(n,{recursive:!0}),await CD(s,JSON.stringify({...A,providers:u})),await CD(i,JSON.stringify(A));try{let f=new Set([...A.providers,...u].map(m=>xB(m))),g=new Set([...A.providers,...u].map(m=>{let I=m.embedBase?"tv":m.kind??"anime";return`${As.join(n,xB(m))}:${I}`}));for(let m of yD.keys())g.has(m)||yD.delete(m);let p=await Pi.promises.readdir(n);for(let m of p)m.toLowerCase().endsWith(".mjs")&&(f.has(m)||(await Pi.promises.unlink(As.join(n,m)),O.info({file:m},"remote providers: removed superseded module")))}catch(f){O.warn({err:f},"remote providers: superseded module cleanup failed")}return r}function Nae(e,t,r){if(e.kind!=="tv"||!t||typeof t!="object")return r;let n=t.servers;return Array.isArray(n)&&n.every(i=>typeof i=="string")&&n.length>0?{...r,servers:[...n]}:r}function Rae(e,t){let r=(e?.genres??[]).length>0?e?.genres:void 0,n=(e?.orders??[]).length>0?e?.orders:void 0;return!r&&!n?t:{...t,facets:{...r?{genres:r}:{},...n?{orders:n}:{}}}}function qp(e,t,r){return{id:e.id.toLowerCase(),label:e.label,version:e.version,mature:e.mature,kind:e.kind??"anime",sub:e.sub,tier:e.tier,modes:e.modes??(e.kind==="tv"?[]:["sub","dub"]),browse:e.browse,enabledByDefault:e.enabledByDefault!==!1,loaded:t,remote:!0,error:r}}var hm=rr(rBe(),1);In();var vht=rr(S4(),1),kht=rr(jB(),1),Lht=rr(Yf(),1),Mht=rr($D(),1),Fht=rr(XD(),1),Uht=rr(rN(),1),nBe=rr($B(),1),_ht=rr(D4(),1);var Qg=nBe.default;In();var iBe=rr(UQ(),1),js=O.child({module:"DiscordGateway"}),M5=class{gateway=null;heartbeat=null;token=null;reconnectTimeout=null;lastActivity=null;isEnabled=!1;RECONNECT_DELAY=15e3;externalAssetCache=new Map;logoAssetId=null;logoAssetChecked=!1;setEnabled(t){this.isEnabled=t,t?(this.loadToken(),this.connect()):this.disconnect()}get serviceEnabled(){return this.isEnabled&&!!this.token&&this.token.length>30}hasToken(){return!!this.token&&this.token.length>30}loadToken(){this.token=process.env.DISCORD_GATEWAY_TOKEN||null,this.logoAssetId=null,this.logoAssetChecked=!1}reloadToken(){iBe.default.config({path:Ae.ENV_PATH,override:!0}),this.loadToken(),this.serviceEnabled&&(this.disconnect(),this.connect())}async getExternalAsset(t){if(!Ae.DISCORD_CLIENT_ID||!this.token)return null;let r=this.externalAssetCache.get(t);if(r)return r;try{let n=await fetch(`https://discord.com/api/v9/applications/${Ae.DISCORD_CLIENT_ID}/external-assets`,{method:"POST",headers:{Authorization:this.token,"Content-Type":"application/json"},body:JSON.stringify({urls:[t]})}),i=await n.text();if(!n.ok)return js.warn(`external-assets proxy failed ${n.status}: ${i.slice(0,200)}`),null;let s=JSON.parse(i);if(!s[0]?.external_asset_path)return null;let o=`mp:${s[0].external_asset_path}`;return this.externalAssetCache.set(t,o),o}catch(n){return js.warn({err:n},"external-assets proxy error"),null}}async getLogoAssetId(){if(!Ae.DISCORD_CLIENT_ID||!this.token)return null;if(this.logoAssetChecked)return this.logoAssetId;try{let t=await fetch(`https://discord.com/api/v9/oauth2/applications/${Ae.DISCORD_CLIENT_ID}/assets`,{headers:{Authorization:this.token}}),r=await t.text();if(!t.ok)return js.warn(`application assets fetch failed ${t.status}: ${r.slice(0,200)}`),this.logoAssetChecked=!0,null;let n=JSON.parse(r);return this.logoAssetId=n.find(i=>i.name==="logo")?.id??null,this.logoAssetChecked=!0,this.logoAssetId}catch(t){return js.warn({err:t},"application assets fetch error"),this.logoAssetChecked=!0,null}}resolveImageUrl(t){let r=i=>!i.startsWith("https://")||i.includes("localhost")||i.includes("127.0.0.1")?!1:i.includes("s4.anilist.co")||i.includes("anilistcdn")?!0:!["youtube-anime.com","animepahe","animeya.cc","gogocdn.net","weeabo0.xyz","japaneseasmr.com"].some(o=>i.includes(o)),n=t.thumbnail;if(n&&n.includes("/api/image-proxy")){let i=n.match(/url=([^&]+)/);if(i)try{n=decodeURIComponent(i[1])}catch(s){}}if(n&&t.providerName!=="AnimePahe"&&r(n))return n;if(t.thumbnails){let i=t.thumbnails.find(s=>s&&(s.includes("s4.anilist.co")||s.includes("anilistcdn")));if(i)return i}return n&&r(n)?n:null}async updatePresence(t){if(this.lastActivity=t,!this.isEnabled||!this.gateway||this.gateway.readyState!==Qg.OPEN)return;let r="dango",n=t.title,i=t.stateLine?t.stateLine:`Episode ${t.episode}${t.totalEpisodes?`/${t.totalEpisodes}`:""}`,s=t.providerName==="ASMR"||t.providerName==="Radio"||t.providerName==="Music"?2:3,o=this.resolveImageUrl(t),a;if(Ae.DISCORD_CLIENT_ID){let l=(o?await this.getExternalAsset(o):null)??await this.getLogoAssetId();l&&(a={large_image:l,large_text:t.title.slice(0,128)})}let A={since:null,activities:[{name:r,type:s,state:t.isPlaying?i:`${i} (Paused)`,details:n,...Ae.DISCORD_CLIENT_ID?{application_id:Ae.DISCORD_CLIENT_ID}:{},...a?{assets:a}:{},buttons:["Learn More"],metadata:{button_urls:["https://github.com/serifpersia/dango"]},status_display_type:2}],status:"online",afk:!1},u=Date.now();t.isPlaying&&(t.currentTime&&t.currentTime>0&&(A.since=u-Math.round(t.currentTime*1e3)),t.duration&&t.duration>t.currentTime&&(A.activities[0].timestamps={start:u-Math.round(t.currentTime*1e3),end:u+Math.round((t.duration-t.currentTime)*1e3)}));try{this.gateway.send(JSON.stringify({op:3,d:A}))}catch(c){js.error({err:c},"Failed to send gateway presence update")}}async setIdleStatus(t){if(!this.isEnabled||!this.gateway||this.gateway.readyState!==Qg.OPEN)return;let n={home:{details:"Home",state:"Browsing anime"},search:{details:"Search",state:"Exploring titles..."},watchlist:{details:"Watchlist",state:"Reviewing the watchlist"},anime:{details:"Anime Info",state:"Reading show details"},insights:{details:"Insights",state:"Reviewing stats"},settings:{details:"Settings",state:"Tweaking preferences"},trackers:{details:"Trackers",state:"Syncing watchlists"},map:{details:"Map",state:"Exploring the global user map"},asmr:{details:"ASMR",state:"Browsing ASMR works"},radio:{details:"Radio",state:"Browsing radio stations"},music:{details:"Music",state:"Browsing music"},tv:{details:"TV",state:"Browsing movies & shows"},manga:{details:"Manga",state:"Browsing manga"}}[t]??{details:"dango",state:"Idle"},i=await this.getLogoAssetId();try{this.gateway.send(JSON.stringify({op:3,d:{since:null,activities:[{name:"dango",type:t==="asmr"||t==="radio"||t==="music"?2:3,state:n.state,details:n.details,...Ae.DISCORD_CLIENT_ID?{application_id:Ae.DISCORD_CLIENT_ID}:{},...i?{assets:{large_image:i,large_text:"dango"}}:{},buttons:["Learn More"],metadata:{button_urls:["https://github.com/serifpersia/dango"]},status_display_type:2}],status:"online",afk:!1}}))}catch(s){js.error({err:s},"Failed to send gateway idle status")}}clearPresence(){if(this.isEnabled){if(this.gateway&&this.gateway.readyState===Qg.OPEN)try{this.gateway.send(JSON.stringify({op:3,d:{since:null,activities:[],status:"online",afk:!1}}))}catch{}this.lastActivity=null}}shutdown(){this.isEnabled=!1,this.token=null,this.disconnect()}disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.gateway){try{this.gateway.readyState===Qg.OPEN&&this.gateway.send(JSON.stringify({op:3,d:{since:null,activities:[],status:"online",afk:!1}})),this.gateway.close()}catch{}this.gateway=null}this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=null)}connect(){if(!this.isEnabled||!this.token||this.gateway)return;let t="wss://gateway.discord.gg/?encoding=json&v=10";js.debug("Connecting Discord gateway"),this.gateway=new Qg(t);let r=41250;this.gateway.on("message",n=>{try{let i=JSON.parse(n.toString());if(i.op===10){r=i.d.heartbeat_interval,this.heartbeat=setInterval(()=>{try{this.gateway&&this.gateway.readyState===Qg.OPEN&&this.gateway.send(JSON.stringify({op:1,d:null}))}catch{}},r);let s={op:2,d:{token:this.token,capabilities:1021,client_state:{guild_hashes:{},highest_last_message_id:"0",private_channels_version:"0",read_state_version:0,user_guild_settings_version:-1,user_settings_version:-1},compress:!1,presence:{since:null,activities:[],status:"online",afk:!1},properties:{os:"Windows",os_version:"10.0.19044",os_arch:"x64",browser:"Discord Client",client_version:"0.0.20",client_build_number:152131,client_event_source:null,release_channel:"stable",system_locale:"en-US"}}};this.gateway&&this.gateway.send(JSON.stringify(s))}else i.op===11||(i.op===0?i.t==="READY"&&(js.info(`Gateway READY as ${i.d.user?.username||"unknown"}`),this.logoAssetChecked=!1,this.lastActivity&&this.updatePresence(this.lastActivity).catch(s=>js.warn({err:s},"failed to restore presence after READY"))):i.op===7?(js.warn("Gateway reconnect requested by Discord"),this.handleDisconnect()):i.op===9&&(js.warn("Gateway invalid session, reconnecting..."),this.handleDisconnect()))}catch(i){js.debug({err:i},"Gateway message parse error")}}),this.gateway.on("close",(n,i)=>{js.warn(`Gateway closed ${n} ${i.toString().slice(0,100)}`),this.handleDisconnect()}),this.gateway.on("error",n=>{js.error(n,"Gateway WebSocket error"),this.handleDisconnect()})}handleDisconnect(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=null),this.gateway=null,this.isEnabled&&this.token&&(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.connect()},this.RECONNECT_DELAY))}},$r=new M5;var Ci=O.child({module:"DiscordRPC"}),F5=class{client=null;isEnabled=!1;hideMature=!0;reconnectTimeout=null;lastActivity=null;currentSessionId=null;hasPagePresence=!1;hasEverConnected=!1;permanentlyDisabled=!1;heartbeats=new Map;heartbeatTimer=null;retryCount=0;MAX_RETRIES=5;INITIAL_RECONNECT_DELAY=15e3;MAX_RECONNECT_DELAY=3e5;HEARTBEAT_TIMEOUT=4e4;HEARTBEAT_CHECK_INTERVAL=1e4;async setEnabled(t){if(this.isEnabled!==t)if(this.isEnabled=t,t){if(this.permanentlyDisabled){Ci.debug("Discord Rich Presence is unavailable on this device/session. Not retrying."),this.isEnabled=!1;return}this.retryCount=0,$r.setEnabled(!0),$r.serviceEnabled||this.connect()}else await this.disconnect(),$r.setEnabled(!1)}get isServiceEnabled(){return this.isEnabled&&(this.client!==null||$r.serviceEnabled)}setHideMature(t){this.hideMature=t}heartbeat(t){this.heartbeats.set(t,Date.now()),!this.heartbeatTimer&&this.isEnabled&&(this.heartbeatTimer=setInterval(()=>{this.checkHeartbeats()},this.HEARTBEAT_CHECK_INTERVAL))}removeHeartbeat(t){this.heartbeats.delete(t),this.checkHeartbeats()}isLocked(t){if(!t||!this.currentSessionId||t===this.currentSessionId)return!1;let r=this.heartbeats.get(this.currentSessionId);return r!==void 0&&Date.now()-r<=this.HEARTBEAT_TIMEOUT}async checkHeartbeats(){if(!this.isEnabled){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);return}let t=Date.now();for(let[r,n]of this.heartbeats)t-n>this.HEARTBEAT_TIMEOUT&&this.heartbeats.delete(r);this.currentSessionId&&!this.heartbeats.has(this.currentSessionId)&&(this.lastActivity=null,this.currentSessionId=null,this.hasPagePresence=!1),this.heartbeats.size===0&&(this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),(this.hasPagePresence||this.lastActivity||this.currentSessionId)&&(this.lastActivity=null,this.currentSessionId=null,this.hasPagePresence=!1,await this.setIdleStatus("idle")))}async connect(){if(!this.isEnabled||this.client||this.permanentlyDisabled)return;if($r.serviceEnabled){Ci.debug("Using Discord Gateway for presence (token configured). Skipping local RPC.");return}let t=!!process.env.TERMUX_VERSION,r=process.platform==="android";if(t||r){Ci.debug("Discord Rich Presence is not supported on Android/Termux. Skipping connection."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}let n=Ae.DISCORD_CLIENT_ID;if(!n){Ci.debug("DISCORD_CLIENT_ID is not configured. Discord Rich Presence is disabled."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}try{this.client=new hm.Client({clientId:n}),this.client.on("ready",()=>{Ci.info("Connected to Discord client successfully"),this.hasEverConnected=!0,this.retryCount=0,this.lastActivity?this.updatePresence(this.lastActivity):this.setIdleStatus("idle")}),this.client.on("disconnected",()=>{Ci.warn("Disconnected from Discord client, scheduling reconnect..."),this.cleanup(),this.scheduleReconnect()}),this.client.on("ERROR",o=>{let a=o instanceof Error?o.message:String(o);if(a.includes("ENOENT")||a.includes("ECONNREFUSED")){if(this.cleanup(),!this.hasEverConnected){Ci.debug("Discord client not detected. Rich Presence disabled for this session."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}Ci.debug("Discord client not running or connection refused."),this.scheduleReconnect()}else Ci.error({err:o},"Discord RPC client error"),this.cleanup(),this.scheduleReconnect()});let i=this.client.login(),s=new Promise((o,a)=>setTimeout(()=>a(new Error("Login timeout")),5e3));await Promise.race([i,s]),this.hasEverConnected=!0}catch{if(this.cleanup(),!this.hasEverConnected){Ci.debug("Discord client not available at startup. Rich Presence disabled for the rest of this session."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}this.scheduleReconnect()}}scheduleReconnect(){if(!this.isEnabled||this.reconnectTimeout||this.permanentlyDisabled)return;let t=Math.min(this.INITIAL_RECONNECT_DELAY*Math.pow(1.5,this.retryCount),this.MAX_RECONNECT_DELAY);this.retryCount++,this.retryCount>this.MAX_RETRIES?Ci.debug(`Discord RPC login failed ${this.retryCount} times. Retrying in ${Math.round(t/1e3)}s...`):Ci.info(`Discord RPC login failed. Retrying in ${Math.round(t/1e3)}s...`),this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.connect()},t)}cleanup(){if(this.client){try{this.client.removeAllListeners(),this.client.destroy()}catch{}this.client=null}}async disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.client?.user)try{await this.client.user.clearActivity()}catch{}this.cleanup(),this.lastActivity=null,this.currentSessionId=null,this.heartbeats.clear(),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),$r.disconnect()}async updatePresence(t){if(this.isLocked(t.sessionId)||(this.lastActivity=t,t.sessionId&&(this.currentSessionId=t.sessionId),!this.isEnabled))return;if(this.hideMature&&t.isAdult){if($r.serviceEnabled)$r.clearPresence();else if(this.client?.user)try{await this.client.user.clearActivity()}catch{}return}if($r.serviceEnabled){$r.updatePresence(t);return}if(!this.client||!this.client.user)return;let r=i=>!i.startsWith("https://")||i.includes("localhost")||i.includes("127.0.0.1")?!1:i.includes("s4.anilist.co")||i.includes("anilistcdn")?!0:!["youtube-anime.com","animepahe","animeya.cc","gogocdn.net","weeabo0.xyz","japaneseasmr.com"].some(o=>i.includes(o)),n="logo";if(t.thumbnail&&t.providerName!=="AnimePahe"){let i=t.thumbnail;if(i.includes("/api/image-proxy")){let s=i.match(/url=([^&]+)/);s&&(i=decodeURIComponent(s[1]))}if(r(i))n=i;else if(t.thumbnails){let s=t.thumbnails.find(o=>o&&(o.includes("s4.anilist.co")||o.includes("anilistcdn")));s&&(n=s)}}try{if(!t.isPlaying){await this.client.user.clearActivity(),await this.client.user.setActivity({details:t.title,state:t.stateLine?`${t.stateLine} (Paused)`:`Episode ${t.episode}${t.totalEpisodes?`/${t.totalEpisodes}`:""} (Paused)`,largeImageKey:n,largeImageText:t.title,type:t.providerName==="ASMR"||t.providerName==="Radio"||t.providerName==="Music"?2:3,statusDisplayType:hm.StatusDisplayType.DETAILS,buttons:[{label:"Learn More",url:"https://github.com/serifpersia/dango"}]}),this.hasPagePresence=!1;return}let i=Math.round(Date.now()/1e3),s={details:t.title,state:t.stateLine?t.stateLine:`Episode ${t.episode}${t.totalEpisodes?`/${t.totalEpisodes}`:""}`,largeImageKey:n,largeImageText:t.title,type:t.providerName==="ASMR"||t.providerName==="Radio"||t.providerName==="Music"?2:3,statusDisplayType:hm.StatusDisplayType.DETAILS,buttons:[{label:"Learn More",url:"https://github.com/serifpersia/dango"}]};t.currentTime&&t.currentTime>0&&(s.startTimestamp=Math.round(i-t.currentTime)),t.duration&&t.duration>t.currentTime&&(s.endTimestamp=Math.round(i+(t.duration-t.currentTime))),await this.client.user.setActivity(s),this.hasPagePresence=!1}catch(i){Ci.error({err:i},"Failed to set Discord activity")}}async setIdleStatus(t,r){if(this.isLocked(r)||(r&&!this.currentSessionId&&(this.currentSessionId=r),!this.isEnabled))return;if($r.serviceEnabled){$r.setIdleStatus(t);return}if(!this.client||!this.client.user){Ci.warn("Discord client not connected, skipping idle status update");return}let n={home:{details:"Home",state:"Browsing anime"},search:{details:"Search",state:"Exploring titles..."},watchlist:{details:"Watchlist",state:"Reviewing the watchlist"},anime:{details:"Anime Info",state:"Reading show details"},insights:{details:"Insights",state:"Reviewing stats"},settings:{details:"Settings",state:"Tweaking preferences"},mal:{details:"MAL Sync",state:"Syncing with MyAnimeList"},map:{details:"Map",state:"Exploring the global user map"},asmr:{details:"ASMR",state:"Browsing ASMR works"},radio:{details:"Radio",state:"Browsing radio stations"},music:{details:"Music",state:"Browsing music"},tv:{details:"TV",state:"Browsing movies & shows"},manga:{details:"Manga",state:"Browsing manga"}},i=n[t]??{details:"dango",state:"Idle"};try{if(!this.client||!this.client.user){Ci.warn("Discord client not connected, skipping idle status update");return}await this.client.user.setActivity({details:i.details,state:i.state,largeImageKey:"logo",largeImageText:"dango",type:t==="asmr"||t==="radio"||t==="music"?2:3,statusDisplayType:hm.StatusDisplayType.DETAILS,buttons:[{label:"Learn More",url:"https://github.com/serifpersia/dango"}]}),this.hasPagePresence=t in n}catch(s){s.message==="Closed by Discord"?Ci.warn("Discord connection ended, skipping idle status update"):Ci.error({err:s},"Failed to set Discord idle status")}}async clearPresence(t){if(!(t&&this.currentSessionId&&t!==this.currentSessionId)){if(this.lastActivity=null,this.currentSessionId=null,$r.serviceEnabled){$r.clearPresence();return}await this.setIdleStatus("idle")}}},rb=new F5;var U5=(e,t,r)=>(n,i)=>{let s=-1;return o(0);async function o(a){if(a<=s)throw new Error("next() called multiple times");s=a;let A,u=!1,c;if(e[a]?(c=e[a][0][0],n.req.routeIndex=a):c=a===e.length&&i||void 0,c)try{A=await c(n,()=>o(a+1))}catch(l){if(l instanceof Error&&t)n.error=l,A=await t(l,n),u=!0;else throw l}else n.finalized===!1&&r&&(A=await r(n));return A&&(n.finalized===!1||u)&&(n.res=A),n}};var Bi="ALL",sBe="all",oBe=["get","post","put","delete","options","patch","query"],Qx="Can not add a route since the matcher is already built.",wx=class extends Error{};var aBe="__COMPOSED_HANDLER";var Oht=e=>e.text("404 Not Found",404),ABe=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},uBe=class cBe{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...oBe,sBe].forEach(s=>{this[s]=(o,...a)=>{let A=s.toUpperCase();return typeof o=="string"?this.#e=o:this.#i(A,this.#e,o),a.forEach(u=>{this.#i(A,this.#e,u)}),this}}),this.on=(s,o,...a)=>{for(let A of[o].flat()){this.#e=A;for(let u of[s].flat()){let c=u.toUpperCase();for(let l of a)this.#i(c,this.#e,l)}}return this},this.use=(s,...o)=>(typeof s=="string"?this.#e=s:(this.#e="*",o.unshift(s)),o.forEach(a=>{this.#i(Bi,this.#e,a)}),this);let{strict:n,...i}=t;Object.assign(this,i),this.getPath=n??!0?t.getPath??Ak:x9}#t(){let t=new cBe({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Oht;errorHandler=ABe;route(t,r){let n=this.basePath(t);return r.routes.map(i=>{let s;r.errorHandler===ABe?s=i.handler:(s=async(o,a)=>(await U5([],r.errorHandler)(o,()=>i.handler(o,a))).res,s[aBe]=i.handler),n.#i(i.method,i.path,s,i.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=Il(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let i,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?i=A=>A:i=n.replaceRequest));let o=s?A=>{let u=s(A);return Array.isArray(u)?u:[u]}:A=>{let u;try{u=A.executionCtx}catch{}return[A.env,u]};i||=(()=>{let A=Il(this._basePath,t),u=A==="/"?0:A.length;return c=>{let l=new URL(c.url);return l.pathname=this.getPath(c).slice(u)||"/",new Request(l,c)}})();let a=async(A,u)=>{let c=await r(i(A.req.raw),...o(A));if(c)return c;await u()};return this.#i(Bi,Il(t,"*"),a),this}#i(t,r,n,i){r=Il(this._basePath,r);let s={basePath:i!==void 0?Il(this._basePath,i):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#s(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,i){if(i==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),o=this.router.match(i,s),a=new ck(t,{path:s,matchResult:o,env:n,executionCtx:r,notFoundHandler:this.#r});if(o[0].length===1){let u;try{u=o[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(c){return this.#s(c,a)}return u instanceof Promise?u.then(c=>c||(a.finalized?a.res:this.#r(a))).catch(c=>this.#s(c,a)):u??this.#r(a)}let A=U5(o[0],this.errorHandler,this.#r);return(async()=>{try{let u=await A(a);if(!u.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#s(u,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,i)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Il("/",t)}`,r),n,i));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var ii=()=>Object.create(null);var Sx=[];function _5(e,t){let r=this.buildAllMatchers(),n=((i,s)=>{let o=r[i]||r[Bi],a=o[2][s];if(a)return a;let A=s.match(o[0]);if(!A)return[[],Sx];let u=A.indexOf("",1);return[o[1][u],A]});return this.match=n,n(e,t)}var fm="[^/]+",zd=".*",nl="(?:|/.*)",Xd=Symbol(),lBe=new Set(".\\+*[^]$()");function Pht(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===zd||e===nl?t===nl?-1:1:t===zd||t===nl?-1:e===fm?1:t===fm?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var dBe=class O5{#e;#t;#r=ii();insert(t,r,n,i,s){let o=this;for(let a=0,A=t.length;a<A;a++){let u=t[a],c=u.length===1?u==="*"?a===A-1?["","",zd]:["","",fm]:null:u==="/*"?["","",nl]:u.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let h=c[1],d=c[2]||fm;if(h&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))||d.length===1&&lBe.has(d)))throw Xd;if(l=o.#r[d],!l){if(d!==zd&&d!==nl){for(let f in o.#r)if((d.length>1||f.length>1)&&f!==zd&&f!==nl)throw Xd}l=o.#r[d]=new O5}h!==""&&(l.#t??=i.varIndex++,n.push([h,l.#t]))}else if(l=o.#r[u],!l){for(let h in o.#r)if(h.length>1&&h!==zd&&h!==nl)throw Xd;l=o.#r[u]=new O5}o=l}if(o.#e!==void 0)throw Xd;o.#e=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(Pht).map(n=>{let i=this.#r[n],s=i.buildRegExpStr();return s===""?"":(typeof i.#t=="number"?`(${n})@${i.#t}`:lBe.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var P5=class{#e={varIndex:0};#t=new dBe;#r=0;paths=ii();insert(e,t){if(t){this.#t.insert(e.split(""),0,[],this.#e,!0);return}let r=[],n=[],i=e;for(let o=0;;){let a=!1;if(i=i.replace(/\{[^}]+\}/g,A=>{let u=`@\\${o}`;return n[o]=[u,A],o++,a=!0,u}),!a)break}let s=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=n.length-1;o>=0;o--){let[a]=n[o];for(let A=s.length-1;A>=0;A--)if(s[A].indexOf(a)!==-1){s[A]=s[A].replace(a,n[o][1]);break}}this.#t.insert(s,this.#r,r,this.#e,!1),this.paths[e]=[this.#r++,r]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,s,o)=>s!==void 0?(r[++t]=Number(s),"$()"):(o!==void 0&&(n[Number(o)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var hBe=ii();function fBe(e){return hBe[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?nl:t==="*"?zd:`/:${fm}`)}$`)}function Tx(e,t){for(let r of Object.keys(e).sort((n,i)=>i.length-n.length))if(fBe(r).test(t))return[...e[r]]}var Dx=class{name="RegExpRouter";#e;#t;#r;constructor(){this.#e={[Bi]:ii()},this.#t={[Bi]:ii()},this.#r={[Bi]:new P5}}#i(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===Xd?new wx(t):r}}add(e,t,r){let n=this.#e,i=this.#t;if(!n)throw new Error(Qx);if(!n[e]){this.#r[e]=new P5;for(let a of[n,i]){a[e]=ii();for(let A in a[Bi])a[e][A]=[...a[Bi][A]],this.#i(e,A)}}t==="/*"&&(t="*");let s=e===Bi?Object.keys(n):[e];if(/\*$/.test(t)){let a=fBe(t);for(let A of s)n[A][t]||(this.#i(A,t),n[A][t]=Tx(n[A],t)||Tx(n[Bi],t)||[]);for(let A of[n,i])for(let u of s)for(let c in A[u])a.test(c)&&A[u][c].push([r,t]);return}let o=aQ(t)||[t];for(let a of o)for(let A of s)i[A][a]||(this.#i(A,a),i[A][a]=Tx(n[A],a)||Tx(n[Bi],a)||[]),i[A][a].push([r,a])}match=_5;buildAllMatchers(){let e=ii();for(let t of Object.keys(this.#t))e[t]=this.#s(t);return this.#e=this.#t=this.#r=void 0,hBe=ii(),e}#s(e){let t=this.#e[e],r=this.#t[e],n=this.#r[e],i=ii(),s=[],[o,a,A]=n.buildRegExp();for(let u of[t,r])for(let c in u){let l=u[c],h=n.paths[c];if(!h){i[c]=[l.map(([d])=>[d,ii()]),Sx];continue}s[h[0]]=l.map(([d,f])=>[d,n.paths[f][1].reduceRight((g,[p],m)=>(g[p]=A[h[1][m][1]],g),ii())])}return[o,a.map(u=>s[u]),i]}};var H5=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,r){if(!this.#t)throw new Error(Qx);this.#t.push([e,t,r])}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,i=r.length,s=0,o;for(;s<i;s++){let a=r[s];try{for(let A=0,u=n.length;A<u;A++)a.add(...n[A]);o=a.match(e,t)}catch(A){if(A instanceof wx)continue;throw A}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(s===i)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var G5=ii(),Hht=0,gBe=class pBe{#e=[];#t=ii();#r=[];#i;#s=G5;insert(t,r,n){let i=this,s=D9(r),o=new Set,a=0;for(let A of s){let u=s[++a],c=N9(A,u)||(u===void 0&&A&&A.indexOf("*")===A.length-1?A:null),l=Array.isArray(c),h=l?c[0]:c||A,d=i.#t[h]||=new pBe;c&&!d.#i&&(d.#i=c,i.#r.push(d)),i=d,l&&o.add(c[1])}i.#e.push({[t]:{handler:n,possibleKeys:[...o],score:++Hht}})}#n(t,r,n,i,s){for(let o=0,a=r.#e.length;o<a;o++){let A=r.#e[o],u=A[n]||A[Bi];if(u){u.params=ii(),t.push(u);for(let c=0,l=u.possibleKeys.length;c<l;c++){let h=u.possibleKeys[c];u.params[h]=s?.[h]&&!c?s[h]:i[h]??s?.[h]}}}}search(t,r){let n=[];this.#s=G5;let s=[this],o=ak(r),a=[],A=o.length,u=null;for(let c=0;c<A;c++){let l=o[c],h=c===A-1,d=[];for(let g=0,p=s.length;g<p;g++){let m=s[g],I=m.#t[l];I&&(I.#s=m.#s,h?(I.#t["*"]&&this.#n(n,I.#t["*"],t,m.#s),this.#n(n,I,t,m.#s)):d.push(I));for(let C of m.#r){let y=C.#i,Q=m.#s===G5?{}:{...m.#s};if(typeof y=="string"){(y==="*"||l.startsWith(y.slice(0,-1)))&&(this.#n(n,C,t,m.#s),y==="*"&&(C.#s=Q,d.push(C)));continue}let[,D,N]=y;if(!(!l&&N===!0)){if(N!==!0){if(!u){u=[];let k=r[0]==="/"?1:0;for(let x=0;x<A;x++)u[x]=k,k+=o[x].length+1}let S=r.slice(u[c]),B=N.exec(S);if(B){Q[D]=B[0],this.#n(n,C,t,m.#s,Q),B[0].length===S.length&&C.#t["*"]&&this.#n(n,C.#t["*"],t,m.#s,Q);for(let k in C.#t){C.#s=Q;let x=B[0].match(/\//g)?.length??0;(a[x]||=[]).push(C);break}continue}}(N===!0||N.test(l))&&(Q[D]=l,h?(this.#n(n,C,t,Q,m.#s),C.#t["*"]&&this.#n(n,C.#t["*"],t,Q,m.#s)):(C.#s=Q,d.push(C)))}}}let f=a.shift();s=f?d.concat(f):d}return n[1]&&n.sort((c,l)=>c.score-l.score),[n.map(({handler:c,params:l})=>[c,l])]}};var Y5=class{name="TrieRouter";#e=new gBe;add(e,t,r){for(let n of aQ(t)||[t])this.#e.insert(e,n,r)}match(e,t){return this.#e.search(e,t)}};var V5=class extends uBe{constructor(e={}){super(e),this.router=e.router??new H5({routers:[new Dx,new Y5]})}};var mBe=e=>e===32||e===9||e===10||e===13,Nx=(e,t)=>{for(;t<e.length&&mBe(e.charCodeAt(t));)t++;return t},nb=(e,t)=>{for(;t>0&&mBe(e.charCodeAt(t-1));)t--;return t},EBe=(e,t)=>{for(;t<e.length;){let r=e.charCodeAt(t);if(r===59)return[t+1,!0];if(r===44)return[t+1,!1];t++}return[t,!1]},Ght=(e,t)=>{let r=t,n=!1;for(;r<e.length;){let i=e.charCodeAt(r);if(n&&i===92)r++;else if(i===34)n=!n;else if(!n&&i===44)return r+1;r++}return r},Yht=(e,t)=>{t=Nx(e,t);let r=t,n,i,s=!1;for(;r<e.length;){let A=e.charCodeAt(r);if(A===61){n=e.slice(t,nb(e,r)),r++;break}if(A===59)return[r+1,void 0,void 0,!0];if(A===44)return[r+1,void 0,void 0,!1];r++}if(n===void 0)return[r,void 0,void 0,!1];if(r=Nx(e,r),e.charCodeAt(r)===61){let A=EBe(e,r+1);return[A[0],n,void 0,A[1]]}let o=!1,a=r;for(;r<e.length;){let A=e.charCodeAt(r);if(o&&A===92)r++;else if(A===34){if(o){let u=Nx(e,r+1),c=e.charCodeAt(u);if(u<e.length&&!(c===59||c===44)){let l=EBe(e,u);return[l[0],n,void 0,l[1]]}if(i=e.slice(a+1,r),i.includes("\\")&&(i=i.replace(/\\(.)/g,"$1")),c===44)return[u+1,n,i,!1];c===59&&(s=!0,u++),r=u;break}o=!0}else if(!o&&(A===59||A===44)){i=e.slice(a,nb(e,r)),A===59&&(s=!0),r++;break}r++}return[r,n,i??e.slice(a,nb(e,r)),s]},Vht=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Nx(e,t);let n=t;for(;n<e.length;){let a=e.charCodeAt(n);if(a===59||a===44){if(r.type=e.slice(t,nb(e,n)),n++,a===44)return[n,r.type?r:void 0];if(!r.type)return[Ght(e,n),void 0];break}n++}if(!r.type)return r.type=e.slice(t,nb(e,e.length)),[e.length,r.type?r:void 0];let i,s,o;for(;n<e.length&&([n,i,s,o]=Yht(e,n),i&&s&&(r.params[i]=s),!!o););return[n,r]},IBe=e=>{if(!e)return[];let t=[],r=0,n,i=!1,s;for(;r<e.length;)[r,n]=Vht(e,r),n&&(n.q=Wht(n.params.q??n.params.Q),t.push(n),s&&s.q<n.q&&(i=!0),s=n);return i&&t.sort((o,a)=>a.q-o.q),t},Wht=e=>{if(e===void 0||e==="")return 1;if(e==="NaN")return 0;let t=Number(e);return Number.isNaN(t)?1:t<0?0:t>1?1:t};var CBe=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml|msgpack))(?:[;\s]|$)/i;var qht=["gzip","deflate"],Jht=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,jht=(e,t)=>{if(e===void 0)return;let r=IBe(e),n=r.find(s=>s.type==="*")?.q,i;for(let s of t){let o=r.find(A=>A.type.toLowerCase()===s),a=o?o.q:n??0;if(a===1)return s;a>0&&(!i||a>i.q)&&(i={encoding:s,q:a})}return i?.encoding},$ht=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,BBe=e=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:qht,n=e?.contentTypeFilter??CBe,i=typeof n=="function"?s=>{let o=s.headers.get("Content-Type");return o&&n(o)}:s=>{let o=s.headers.get("Content-Type");return o&&n.test(o)};return async function(o,a){await a();let A=o.res.headers.get("Content-Length");if(o.res.status===206||o.res.headers.has("Content-Encoding")||o.res.headers.has("Transfer-Encoding")||o.req.method==="HEAD"||A&&Number(A)<t||!i(o.res)||!Kht(o.res))return;let u=o.res.headers.get("Vary");u!=="*"&&!(u&&$ht.test(u))&&o.header("Vary",u?`${u}, Accept-Encoding`:"Accept-Encoding");let c=o.req.header("Accept-Encoding"),l=jht(c,r);if(!l||!o.res.body)return;let h=new CompressionStream(l);o.res=new Response(o.res.body.pipeThrough(h),o.res),o.res.headers.delete("Content-Length"),o.res.headers.set("Content-Encoding",l);let d=o.res.headers.get("ETag");d&&!d.startsWith("W/")&&o.res.headers.set("ETag",`W/${d}`)}},Kht=e=>{let t=e.headers.get("Cache-Control");return!t||!Jht.test(t)};import Swe from"path";import Vm from"fs";var yBe=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",Xht=yBe+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",zht="["+yBe+"]["+Xht+"]*",Zht=new RegExp("^"+zht+"$");function bBe(e,t){let r=[],n=t.exec(e);for(;n;){let i=[];i.startIndex=t.lastIndex-n[0].length;let s=n.length;for(let o=0;o<s;o++)i.push(n[o]);r.push(i),n=t.exec(e)}return r}var W5=function(e){let t=Zht.exec(e);return!(t===null||typeof t>"u")};function QBe(e){return typeof e<"u"}var ib=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],Rx=["__proto__","constructor","prototype"];var eft={allowBooleanAttributes:!1,unpairedTags:[]};function DBe(e,t){t=Object.assign({},eft,t);let r=[],n=!1,i=!1;e[0]==="\uFEFF"&&(e=e.substr(1));for(let s=0;s<e.length;s++)if(e[s]==="<"&&e[s+1]==="?"){if(s+=2,s=wBe(e,s),s.err)return s}else if(e[s]==="<"){let o=s;if(s++,e[s]==="!"){s=SBe(e,s);continue}else{let a=!1;e[s]==="/"&&(a=!0,s++);let A="";for(;s<e.length&&e[s]!==">"&&e[s]!==" "&&e[s]!==" "&&e[s]!==`
|
|
469
|
+
__HTTP_STATUS__%{http_code}`,"--",e],n;try{n=IKe("curl",r,{encoding:"utf-8",maxBuffer:10*1024*1024})}catch{return null}let i=n.match(/__HTTP_STATUS__(\d+)\s*$/);return{status:i?parseInt(i[1],10):0,body:i&&i.index!==void 0?n.slice(0,i.index):n}}function DKe(e){let t=async(r,n,i=QD)=>kB(fetch(r,{...n,headers:{"User-Agent":vB,...n?.headers}}),i,`fetch ${r}`);return{cache:{get:r=>e.get(r),set:(r,n,i)=>{e.set(r,n,i)}},logger:{info:(r,n)=>{O.info(r,n)},warn:(r,n)=>{O.warn(r,n)},error:(r,n)=>{O.error(r,n)},debug:(r,n)=>{O.debug(r,n)}},fetchText:async(r,n)=>{try{let i=await t(r,n);return i.ok?await i.text():null}catch{return null}},fetchJson:async(r,n)=>{let i=await t(r,n);if(!i.ok)throw new Error(`HTTP ${i.status}: ${r}`);return Yt(i)},proxyUrl:(r,n)=>`/api/proxy?url=${encodeURIComponent(r)}&referer=${encodeURIComponent(n)}`,userAgent:vB,titleMatch:{buildQueryVariants:pB,pickBestMatch:vc},resolveBestShowId:async(r,n,i)=>{let s=[r,n].filter(o=>typeof o=="string"&&o.trim().length>0);if(s.length===0)return null;for(let o of pB(r,n)){let a;try{a=await i(o)}catch(u){if(u.message==="AUTH_REQUIRED")throw u;continue}if(!a||a.length===0)continue;let A=vc(a.filter(u=>u&&typeof u.id=="string"&&u.id.length>0),s);if(A)return A.item.id}return null},anilist:{request:(r,n)=>ur(r,n),parseMalId:_s,searchByTitle:Os},kitsu:{metaByAnilistId:BB},tmdb:{base:To,image:Sd,get:async r=>{try{let n=await Fc(),i=r.includes("?")?"&":"?",s=await t(`${To}${r}${i}api_key=${n}`);return s.ok?Yt(s):null}catch{return null}}},request:{get:r=>eD.getStore()?.get(r)},cookies:{sanitizeCfClearance:_p,buildCfClearanceCookie:pu},crypto:{aes256CbcDecryptJson:TKe,hmacSha256Base64Url:(r,n)=>bD.createHmac("sha256",r).update(n).digest("base64url")},scraping:{fetch:async(r,n)=>{let i=typeof r=="string"?{url:r,...n??{}}:r,{url:s,...o}=i,a=await yKe({url:s,method:"GET",responseType:"text",throwHttpErrors:!1,...o});return{statusCode:a.statusCode,body:String(a.body??""),headers:a.headers}}},curl:{getJson:async(r,n)=>{try{let i=Sae(r,n);return!i||i.status!==200?null:JSON.parse(i.body)}catch{return null}},getText:async(r,n)=>{let i=Sae(r,n);return!i||i.status!==200?null:i.body}},cheerio:{load:r=>S2(r)}}}function q8(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.name=="string"?t:null}function xae(e,t){return t.every(r=>typeof e[r]=="function")}function vae(e){let t=q8(e);return!!t&&xae(t,["search","getEpisodes","getStreamUrls"])}function kae(e){let t=q8(e);return!!t&&xae(t,["search","getDetail","getChapters","getPages"])}function Lae(e){let t=q8(e);return!!t&&(typeof t.getSources=="function"||typeof t.getEmbedUrl=="function")}function NKe(e,t){return e==="manga"?kae(t):e==="tv"?Lae(t):e==="asmr"?Y8(t):vae(t)}function Tae(e,t,r,n){return t.kind==="manga"?kae(n)?(e.mangaProviders[r]=n,!0):!1:t.kind==="tv"?Lae(n)?(e.tvProviders[r]=n,!0):!1:t.kind==="asmr"?Y8(n)?(e.asmrProviders[r]=n,!0):!1:vae(n)?(e.providers[r]=n,!0):!1}function RKe(e,t){let r=t.trim().replace(/\/+$/,"");return{name:e,getEmbedUrl:async n=>{let i=Number(n.tmdbId);return i?n.type==="movie"?`${r}/movie/${i}`:`${r}/tv/${i}/${n.season||1}/${n.episode||1}`:null}}}async function V8(e,t,r,n,i){if(e.minDango&&!Qae(wae,e.minDango))return{provider:null,error:`requires dango ${e.minDango}, running ${wae}`};if(e.embedBase)return{provider:RKe(e.id,e.embedBase)};let s=SKe(e.entry,t);await Pi.promises.mkdir(r,{recursive:!0});let o=xB(e),a=As.join(r,o),A=`${a}:${e.kind??"anime"}`,u=null;try{let h=await Pi.promises.readFile(a);(e.sha256&&BD(h)===e.sha256||!e.sha256&&i)&&(u=h)}catch{}if(u){let h=yD.get(A);if(h)return O.debug({provider:e.id,version:e.version},"remote provider reused cached instance"),{provider:h.provider,facets:h.facets}}else{try{u=await wKe(s)}catch(h){return{provider:null,error:`download failed: ${h.message}`}}if(e.sha256){if(BD(u)!==e.sha256)return{provider:null,error:`sha256 mismatch for ${e.id}`}}else if(!i)return{provider:null,error:`missing sha256 for ${e.id}`};await CD(a,u)}let c=`${e.version}-${e.sha256??"nosha"}`,l=await vKe(a,c,n,e);return l.provider&&!l.error&&yD.set(A,{provider:l.provider,facets:l.facets}),l}var yD=new Map;function xB(e){return`${e.id}-${e.version}-${e.sha256??"nosha"}.mjs`}function xKe(e){let t,r;for(let[n,i]of Object.entries(e)){if(n==="default"||!Array.isArray(i)||i.length===0||!i.every(a=>typeof a=="string"&&a.length>0))continue;let s=i.filter(a=>a.length<=64).slice(0,500);if(s.length===0)continue;let o=n.toUpperCase();o.includes("GENRE")||o.includes("TAG")?t??=s:(o.includes("ORDER")||o.includes("SORT"))&&(r??=s)}if(!(!t&&!r))return{...t?{genres:t}:{},...r?{orders:r}:{}}}async function vKe(e,t,r,n){let i=n.id,s;try{let A=`${BKe(e).href}?v=${encodeURIComponent(t)}`;s=await kB(import(A),QD,`import ${i}`)}catch(A){return{provider:null,error:`import failed: ${A.message}`}}let o=s.default;if(typeof o!="function")return{provider:null,error:"missing default factory export"};let a;try{a=await kB(Promise.resolve(o(r)),1e4,`factory ${i}`)}catch(A){return{provider:null,error:`factory failed: ${A.message}`}}return NKe(n.kind,a)?{provider:a,facets:xKe(s)}:{provider:null,error:"invalid provider shape"}}async function kKe(e,t,r){if(e.embedBase)return V8(e,"",t,r,!1);if(!e.sha256)return{provider:null,error:"no verified fallback"};let n=As.join(t,xB(e)),i;try{i=await Pi.promises.readFile(n)}catch{return{provider:null,error:"no cached fallback file"}}return BD(i)!==e.sha256?{provider:null,error:"cached fallback failed verification"}:V8(e,"",t,r,!1)}var Dae;function Mae(e){return Dae??=LKe(e).finally(()=>{Dae=void 0})}async function LKe(e){let t=(e.registryUrl??Ae.PROVIDER_REPO_URL??"").trim(),r={registryLoaded:!1,providers:{},mangaProviders:{},tvProviders:{},asmrProviders:{},catalog:[],proxyRules:[]};if(!t)return r;let n=As.join(Pn.ROOT,"remote-providers"),i=As.join(n,"registry.json"),s=As.join(n,"active.json"),o=null;try{o=RB(JSON.parse(await Pi.promises.readFile(s,"utf8")))}catch{try{o=RB(JSON.parse(await Pi.promises.readFile(i,"utf8")));for(let f of o.providers){if(f.embedBase||!f.sha256)continue;let g=As.join(n,`${f.id}-${f.version}.mjs`);try{let p=await Pi.promises.readFile(g);BD(p)===f.sha256&&await CD(As.join(n,xB(f)),p)}catch{}}}catch{}}let a=new Map((o?.providers??[]).map(f=>[f.id.toLowerCase(),f])),A;try{let f=await QKe(t);A=RB(JSON.parse(f.toString("utf8")))}catch(f){O.error({err:f,registryUrl:t},"remote providers: manifest fetch failed, trying disk cache");try{A=RB(JSON.parse(await Pi.promises.readFile(i,"utf8")))}catch{return r}}r.registryLoaded=!0;let u=[],c=new Set((e.enabledProviders??[]).map(f=>f.toLowerCase())),l=c.size>0,h=DKe(e.cache),d=e.allowUnsigned??(process.env.DANGO_ALLOW_UNSIGNED_PROVIDERS==="1"||bKe(t));for(let f of A.providers){let g=f.id.toLowerCase();if(f.enabledByDefault===!1&&(!l||!c.has(g))){r.catalog.push(qp(f,!1,"disabled by default"));continue}if(l&&!c.has(g)){r.catalog.push(qp(f,!1,"not in enabledProviders"));continue}let{provider:p,facets:m,error:I}=await V8(f,t,n,h,d);if(p&&!I){if(!Tae(r,f,g,p)){r.catalog.push(qp(f,!1,"invalid provider shape for kind")),O.warn({provider:f.id},"remote provider kind mismatch, skipped");continue}r.catalog.push(Rae(m,Nae(f,p,qp(f,!0)))),u.push(f),f.proxy&&r.proxyRules.push(f.proxy),O.info({provider:f.id,version:f.version},"remote provider loaded")}else{let C=a.get(g);if(C){let y=await kKe(C,n,h);if(y.provider&&!y.error&&(Tae(r,C,g,y.provider)||(y.error="cached fallback failed validation")),y.provider&&!y.error){r.catalog.push({...Rae(y.facets,Nae(C,y.provider,qp(C,!0))),error:`serving cached ${C.version}: ${I}`}),u.push(C),C.proxy&&r.proxyRules.push(C.proxy),O.warn({provider:f.id,error:I,fallback:C.version},"remote provider update failed, serving cached version");continue}}r.catalog.push(qp(f,!1,I)),C&&u.push(C),f.proxy&&r.proxyRules.push(f.proxy),O.warn({provider:f.id,error:I},"remote provider skipped")}}await Pi.promises.mkdir(n,{recursive:!0}),await CD(s,JSON.stringify({...A,providers:u})),await CD(i,JSON.stringify(A));try{let f=new Set([...A.providers,...u].map(m=>xB(m))),g=new Set([...A.providers,...u].map(m=>{let I=m.embedBase?"tv":m.kind??"anime";return`${As.join(n,xB(m))}:${I}`}));for(let m of yD.keys())g.has(m)||yD.delete(m);let p=await Pi.promises.readdir(n);for(let m of p)m.toLowerCase().endsWith(".mjs")&&(f.has(m)||(await Pi.promises.unlink(As.join(n,m)),O.info({file:m},"remote providers: removed superseded module")))}catch(f){O.warn({err:f},"remote providers: superseded module cleanup failed")}return r}function Nae(e,t,r){if(e.kind!=="tv"||!t||typeof t!="object")return r;let n=t.servers;return Array.isArray(n)&&n.every(i=>typeof i=="string")&&n.length>0?{...r,servers:[...n]}:r}function Rae(e,t){let r=(e?.genres??[]).length>0?e?.genres:void 0,n=(e?.orders??[]).length>0?e?.orders:void 0;return!r&&!n?t:{...t,facets:{...r?{genres:r}:{},...n?{orders:n}:{}}}}function qp(e,t,r){return{id:e.id.toLowerCase(),label:e.label,version:e.version,mature:e.mature,kind:e.kind??"anime",sub:e.sub,tier:e.tier,modes:e.modes??(e.kind==="tv"?[]:["sub","dub"]),browse:e.browse,enabledByDefault:e.enabledByDefault!==!1,loaded:t,remote:!0,error:r}}var hm=rr(rBe(),1);In();var vht=rr(S4(),1),kht=rr(jB(),1),Lht=rr(Yf(),1),Mht=rr($D(),1),Fht=rr(XD(),1),Uht=rr(rN(),1),nBe=rr($B(),1),_ht=rr(D4(),1);var Qg=nBe.default;In();var iBe=rr(UQ(),1),js=O.child({module:"DiscordGateway"}),M5=class{gateway=null;heartbeat=null;token=null;reconnectTimeout=null;lastActivity=null;isEnabled=!1;RECONNECT_DELAY=15e3;externalAssetCache=new Map;logoAssetId=null;logoAssetChecked=!1;setEnabled(t){this.isEnabled=t,t?(this.loadToken(),this.connect()):this.disconnect()}get serviceEnabled(){return this.isEnabled&&!!this.token&&this.token.length>30}hasToken(){return!!this.token&&this.token.length>30}loadToken(){this.token=process.env.DISCORD_GATEWAY_TOKEN||null,this.logoAssetId=null,this.logoAssetChecked=!1}reloadToken(){iBe.default.config({path:Ae.ENV_PATH,override:!0}),this.loadToken(),this.serviceEnabled&&(this.disconnect(),this.connect())}async getExternalAsset(t){if(!Ae.DISCORD_CLIENT_ID||!this.token)return null;let r=this.externalAssetCache.get(t);if(r)return r;try{let n=await fetch(`https://discord.com/api/v9/applications/${Ae.DISCORD_CLIENT_ID}/external-assets`,{method:"POST",headers:{Authorization:this.token,"Content-Type":"application/json"},body:JSON.stringify({urls:[t]})}),i=await n.text();if(!n.ok)return js.warn(`external-assets proxy failed ${n.status}: ${i.slice(0,200)}`),null;let s=JSON.parse(i);if(!s[0]?.external_asset_path)return null;let o=`mp:${s[0].external_asset_path}`;return this.externalAssetCache.set(t,o),o}catch(n){return js.warn({err:n},"external-assets proxy error"),null}}async getLogoAssetId(){if(!Ae.DISCORD_CLIENT_ID||!this.token)return null;if(this.logoAssetChecked)return this.logoAssetId;try{let t=await fetch(`https://discord.com/api/v9/oauth2/applications/${Ae.DISCORD_CLIENT_ID}/assets`,{headers:{Authorization:this.token}}),r=await t.text();if(!t.ok)return js.warn(`application assets fetch failed ${t.status}: ${r.slice(0,200)}`),this.logoAssetChecked=!0,null;let n=JSON.parse(r);return this.logoAssetId=n.find(i=>i.name==="logo")?.id??null,this.logoAssetChecked=!0,this.logoAssetId}catch(t){return js.warn({err:t},"application assets fetch error"),this.logoAssetChecked=!0,null}}resolveImageUrl(t){let r=i=>!i.startsWith("https://")||i.includes("localhost")||i.includes("127.0.0.1")?!1:i.includes("s4.anilist.co")||i.includes("anilistcdn")?!0:!["youtube-anime.com","animepahe","animeya.cc","gogocdn.net","weeabo0.xyz","japaneseasmr.com"].some(o=>i.includes(o)),n=t.thumbnail;if(n&&n.includes("/api/image-proxy")){let i=n.match(/url=([^&]+)/);if(i)try{n=decodeURIComponent(i[1])}catch(s){}}if(n&&t.providerName!=="AnimePahe"&&r(n))return n;if(t.thumbnails){let i=t.thumbnails.find(s=>s&&(s.includes("s4.anilist.co")||s.includes("anilistcdn")));if(i)return i}return n&&r(n)?n:null}async updatePresence(t){if(this.lastActivity=t,!this.isEnabled||!this.gateway||this.gateway.readyState!==Qg.OPEN)return;let r="dango",n=t.title,i=t.stateLine?t.stateLine:`Episode ${t.episode}${t.totalEpisodes?`/${t.totalEpisodes}`:""}`,s=t.providerName==="ASMR"?2:3,o=this.resolveImageUrl(t),a;if(Ae.DISCORD_CLIENT_ID){let l=(o?await this.getExternalAsset(o):null)??await this.getLogoAssetId();l&&(a={large_image:l,large_text:t.title.slice(0,128)})}let A={since:null,activities:[{name:r,type:s,state:t.isPlaying?i:`${i} (Paused)`,details:n,...Ae.DISCORD_CLIENT_ID?{application_id:Ae.DISCORD_CLIENT_ID}:{},...a?{assets:a}:{},buttons:["Learn More"],metadata:{button_urls:["https://github.com/serifpersia/dango"]},status_display_type:2}],status:"online",afk:!1},u=Date.now();t.isPlaying&&(t.currentTime&&t.currentTime>0&&(A.since=u-Math.round(t.currentTime*1e3)),t.duration&&t.duration>t.currentTime&&(A.activities[0].timestamps={start:u-Math.round(t.currentTime*1e3),end:u+Math.round((t.duration-t.currentTime)*1e3)}));try{this.gateway.send(JSON.stringify({op:3,d:A}))}catch(c){js.error({err:c},"Failed to send gateway presence update")}}async setIdleStatus(t){if(!this.isEnabled||!this.gateway||this.gateway.readyState!==Qg.OPEN)return;let n={home:{details:"Home",state:"Browsing anime"},"home-anime":{details:"Home",state:"Browsing anime"},"home-manga":{details:"Home",state:"Browsing manga"},"home-tv":{details:"Home",state:"Browsing movies & shows"},"home-asmr":{details:"Home",state:"Browsing ASMR works"},search:{details:"Search",state:"Exploring titles..."},"search-anime":{details:"Anime Search",state:"Browsing titles"},"search-manga":{details:"Manga Search",state:"Browsing titles"},"search-tv":{details:"TV Search",state:"Browsing titles"},"search-asmr":{details:"ASMR Search",state:"Browsing titles"},watchlist:{details:"Watchlist",state:"Reviewing the watchlist"},anime:{details:"Anime Info",state:"Reading show details"},insights:{details:"Insights",state:"Reviewing stats"},settings:{details:"Settings",state:"Tweaking preferences"},trackers:{details:"Trackers",state:"Syncing watchlists"},map:{details:"Map",state:"Exploring the global user map"},asmr:{details:"ASMR Info",state:"Reading details"},tv:{details:"TV Info",state:"Reading show details"},manga:{details:"Manga Info",state:"Reading manga details"}}[t]??{details:"dango",state:"Idle"},i=t==="asmr"||t==="home-asmr"||t==="search-asmr",s=await this.getLogoAssetId();try{this.gateway.send(JSON.stringify({op:3,d:{since:null,activities:[{name:"dango",type:i?2:3,state:n.state,details:n.details,...Ae.DISCORD_CLIENT_ID?{application_id:Ae.DISCORD_CLIENT_ID}:{},...s?{assets:{large_image:s,...i?{}:{large_text:"dango"}}}:{},buttons:["Learn More"],metadata:{button_urls:["https://github.com/serifpersia/dango"]},status_display_type:2}],status:"online",afk:!1}}))}catch(o){js.error({err:o},"Failed to send gateway idle status")}}clearPresence(){if(this.isEnabled){if(this.gateway&&this.gateway.readyState===Qg.OPEN)try{this.gateway.send(JSON.stringify({op:3,d:{since:null,activities:[],status:"online",afk:!1}}))}catch{}this.lastActivity=null}}shutdown(){this.isEnabled=!1,this.token=null,this.disconnect()}disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.gateway){try{this.gateway.readyState===Qg.OPEN&&this.gateway.send(JSON.stringify({op:3,d:{since:null,activities:[],status:"online",afk:!1}})),this.gateway.close()}catch{}this.gateway=null}this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=null)}connect(){if(!this.isEnabled||!this.token||this.gateway)return;let t="wss://gateway.discord.gg/?encoding=json&v=10";js.debug("Connecting Discord gateway"),this.gateway=new Qg(t);let r=41250;this.gateway.on("message",n=>{try{let i=JSON.parse(n.toString());if(i.op===10){r=i.d.heartbeat_interval,this.heartbeat=setInterval(()=>{try{this.gateway&&this.gateway.readyState===Qg.OPEN&&this.gateway.send(JSON.stringify({op:1,d:null}))}catch{}},r);let s={op:2,d:{token:this.token,capabilities:1021,client_state:{guild_hashes:{},highest_last_message_id:"0",private_channels_version:"0",read_state_version:0,user_guild_settings_version:-1,user_settings_version:-1},compress:!1,presence:{since:null,activities:[],status:"online",afk:!1},properties:{os:"Windows",os_version:"10.0.19044",os_arch:"x64",browser:"Discord Client",client_version:"0.0.20",client_build_number:152131,client_event_source:null,release_channel:"stable",system_locale:"en-US"}}};this.gateway&&this.gateway.send(JSON.stringify(s))}else i.op===11||(i.op===0?i.t==="READY"&&(js.info(`Gateway READY as ${i.d.user?.username||"unknown"}`),this.logoAssetChecked=!1,this.lastActivity&&this.updatePresence(this.lastActivity).catch(s=>js.warn({err:s},"failed to restore presence after READY"))):i.op===7?(js.warn("Gateway reconnect requested by Discord"),this.handleDisconnect()):i.op===9&&(js.warn("Gateway invalid session, reconnecting..."),this.handleDisconnect()))}catch(i){js.debug({err:i},"Gateway message parse error")}}),this.gateway.on("close",(n,i)=>{js.warn(`Gateway closed ${n} ${i.toString().slice(0,100)}`),this.handleDisconnect()}),this.gateway.on("error",n=>{js.error(n,"Gateway WebSocket error"),this.handleDisconnect()})}handleDisconnect(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=null),this.gateway=null,this.isEnabled&&this.token&&(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.connect()},this.RECONNECT_DELAY))}},$r=new M5;var Ci=O.child({module:"DiscordRPC"}),F5=class{client=null;isEnabled=!1;hideMature=!0;reconnectTimeout=null;lastActivity=null;currentSessionId=null;hasPagePresence=!1;hasEverConnected=!1;permanentlyDisabled=!1;heartbeats=new Map;heartbeatTimer=null;retryCount=0;MAX_RETRIES=5;INITIAL_RECONNECT_DELAY=15e3;MAX_RECONNECT_DELAY=3e5;HEARTBEAT_TIMEOUT=4e4;HEARTBEAT_CHECK_INTERVAL=1e4;async setEnabled(t){if(this.isEnabled!==t)if(this.isEnabled=t,t){if(this.permanentlyDisabled){Ci.debug("Discord Rich Presence is unavailable on this device/session. Not retrying."),this.isEnabled=!1;return}this.retryCount=0,$r.setEnabled(!0),$r.serviceEnabled||this.connect()}else await this.disconnect(),$r.setEnabled(!1)}get isServiceEnabled(){return this.isEnabled&&(this.client!==null||$r.serviceEnabled)}setHideMature(t){this.hideMature=t}heartbeat(t){this.heartbeats.set(t,Date.now()),!this.heartbeatTimer&&this.isEnabled&&(this.heartbeatTimer=setInterval(()=>{this.checkHeartbeats()},this.HEARTBEAT_CHECK_INTERVAL))}removeHeartbeat(t){this.heartbeats.delete(t),this.checkHeartbeats()}isLocked(t){if(!t||!this.currentSessionId||t===this.currentSessionId)return!1;let r=this.heartbeats.get(this.currentSessionId);return r!==void 0&&Date.now()-r<=this.HEARTBEAT_TIMEOUT}async checkHeartbeats(){if(!this.isEnabled){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);return}let t=Date.now();for(let[r,n]of this.heartbeats)t-n>this.HEARTBEAT_TIMEOUT&&this.heartbeats.delete(r);this.currentSessionId&&!this.heartbeats.has(this.currentSessionId)&&(this.lastActivity=null,this.currentSessionId=null,this.hasPagePresence=!1),this.heartbeats.size===0&&(this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),(this.hasPagePresence||this.lastActivity||this.currentSessionId)&&(this.lastActivity=null,this.currentSessionId=null,this.hasPagePresence=!1,await this.setIdleStatus("idle")))}async connect(){if(!this.isEnabled||this.client||this.permanentlyDisabled)return;if($r.serviceEnabled){Ci.debug("Using Discord Gateway for presence (token configured). Skipping local RPC.");return}let t=!!process.env.TERMUX_VERSION,r=process.platform==="android";if(t||r){Ci.debug("Discord Rich Presence is not supported on Android/Termux. Skipping connection."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}let n=Ae.DISCORD_CLIENT_ID;if(!n){Ci.debug("DISCORD_CLIENT_ID is not configured. Discord Rich Presence is disabled."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}try{this.client=new hm.Client({clientId:n}),this.client.on("ready",()=>{Ci.info("Connected to Discord client successfully"),this.hasEverConnected=!0,this.retryCount=0,this.lastActivity?this.updatePresence(this.lastActivity):this.setIdleStatus("idle")}),this.client.on("disconnected",()=>{Ci.warn("Disconnected from Discord client, scheduling reconnect..."),this.cleanup(),this.scheduleReconnect()}),this.client.on("ERROR",o=>{let a=o instanceof Error?o.message:String(o);if(a.includes("ENOENT")||a.includes("ECONNREFUSED")){if(this.cleanup(),!this.hasEverConnected){Ci.debug("Discord client not detected. Rich Presence disabled for this session."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}Ci.debug("Discord client not running or connection refused."),this.scheduleReconnect()}else Ci.error({err:o},"Discord RPC client error"),this.cleanup(),this.scheduleReconnect()});let i=this.client.login(),s=new Promise((o,a)=>setTimeout(()=>a(new Error("Login timeout")),5e3));await Promise.race([i,s]),this.hasEverConnected=!0}catch{if(this.cleanup(),!this.hasEverConnected){Ci.debug("Discord client not available at startup. Rich Presence disabled for the rest of this session."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}this.scheduleReconnect()}}scheduleReconnect(){if(!this.isEnabled||this.reconnectTimeout||this.permanentlyDisabled)return;let t=Math.min(this.INITIAL_RECONNECT_DELAY*Math.pow(1.5,this.retryCount),this.MAX_RECONNECT_DELAY);this.retryCount++,this.retryCount>this.MAX_RETRIES?Ci.debug(`Discord RPC login failed ${this.retryCount} times. Retrying in ${Math.round(t/1e3)}s...`):Ci.info(`Discord RPC login failed. Retrying in ${Math.round(t/1e3)}s...`),this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.connect()},t)}cleanup(){if(this.client){try{this.client.removeAllListeners(),this.client.destroy()}catch{}this.client=null}}async disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.client?.user)try{await this.client.user.clearActivity()}catch{}this.cleanup(),this.lastActivity=null,this.currentSessionId=null,this.heartbeats.clear(),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),$r.disconnect()}async updatePresence(t){if(this.isLocked(t.sessionId)||(this.lastActivity=t,t.sessionId&&(this.currentSessionId=t.sessionId,this.heartbeat(t.sessionId)),!this.isEnabled))return;if(this.hideMature&&t.isAdult){if($r.serviceEnabled)$r.clearPresence();else if(this.client?.user)try{await this.client.user.clearActivity()}catch{}return}if($r.serviceEnabled){$r.updatePresence(t);return}if(!this.client||!this.client.user)return;let r=i=>!i.startsWith("https://")||i.includes("localhost")||i.includes("127.0.0.1")?!1:i.includes("s4.anilist.co")||i.includes("anilistcdn")?!0:!["youtube-anime.com","animepahe","animeya.cc","gogocdn.net","weeabo0.xyz","japaneseasmr.com"].some(o=>i.includes(o)),n="logo";if(t.thumbnail&&t.providerName!=="AnimePahe"){let i=t.thumbnail;if(i.includes("/api/image-proxy")){let s=i.match(/url=([^&]+)/);s&&(i=decodeURIComponent(s[1]))}if(r(i))n=i;else if(t.thumbnails){let s=t.thumbnails.find(o=>o&&(o.includes("s4.anilist.co")||o.includes("anilistcdn")));s&&(n=s)}}try{if(!t.isPlaying){await this.client.user.clearActivity(),await this.client.user.setActivity({details:t.title,state:t.stateLine?`${t.stateLine} (Paused)`:`Episode ${t.episode}${t.totalEpisodes?`/${t.totalEpisodes}`:""} (Paused)`,largeImageKey:n,largeImageText:t.title,type:t.providerName==="ASMR"?2:3,statusDisplayType:hm.StatusDisplayType.DETAILS,buttons:[{label:"Learn More",url:"https://github.com/serifpersia/dango"}]}),this.hasPagePresence=!1;return}let i=Math.round(Date.now()/1e3),s={details:t.title,state:t.stateLine?t.stateLine:`Episode ${t.episode}${t.totalEpisodes?`/${t.totalEpisodes}`:""}`,largeImageKey:n,largeImageText:t.title,type:t.providerName==="ASMR"?2:3,statusDisplayType:hm.StatusDisplayType.DETAILS,buttons:[{label:"Learn More",url:"https://github.com/serifpersia/dango"}]};t.currentTime&&t.currentTime>0&&(s.startTimestamp=Math.round(i-t.currentTime)),t.duration&&t.duration>t.currentTime&&(s.endTimestamp=Math.round(i+(t.duration-t.currentTime))),await this.client.user.setActivity(s),this.hasPagePresence=!1}catch(i){Ci.error({err:i},"Failed to set Discord activity")}}async setIdleStatus(t,r){if(this.isLocked(r)||!this.isEnabled)return;if($r.serviceEnabled){$r.setIdleStatus(t);return}if(!this.client||!this.client.user){Ci.warn("Discord client not connected, skipping idle status update");return}let n={home:{details:"Home",state:"Browsing anime"},"home-anime":{details:"Home",state:"Browsing anime"},"home-manga":{details:"Home",state:"Browsing manga"},"home-tv":{details:"Home",state:"Browsing movies & shows"},"home-asmr":{details:"Home",state:"Browsing ASMR works"},search:{details:"Search",state:"Exploring titles..."},"search-anime":{details:"Anime Search",state:"Browsing titles"},"search-manga":{details:"Manga Search",state:"Browsing titles"},"search-tv":{details:"TV Search",state:"Browsing titles"},"search-asmr":{details:"ASMR Search",state:"Browsing titles"},watchlist:{details:"Watchlist",state:"Reviewing the watchlist"},anime:{details:"Anime Info",state:"Reading show details"},insights:{details:"Insights",state:"Reviewing stats"},settings:{details:"Settings",state:"Tweaking preferences"},mal:{details:"MAL Sync",state:"Syncing with MyAnimeList"},map:{details:"Map",state:"Exploring the global user map"},asmr:{details:"ASMR Info",state:"Reading details"},tv:{details:"TV Info",state:"Reading show details"},manga:{details:"Manga Info",state:"Reading manga details"}},i=n[t]??{details:"dango",state:"Idle"},s=t==="asmr"||t==="home-asmr"||t==="search-asmr";try{if(!this.client||!this.client.user){Ci.warn("Discord client not connected, skipping idle status update");return}await this.client.user.setActivity({details:i.details,state:i.state,largeImageKey:"logo",largeImageText:s?void 0:"dango",type:s?2:3,statusDisplayType:hm.StatusDisplayType.DETAILS,buttons:[{label:"Learn More",url:"https://github.com/serifpersia/dango"}]}),this.hasPagePresence=t in n}catch(o){o.message==="Closed by Discord"?Ci.warn("Discord connection ended, skipping idle status update"):Ci.error({err:o},"Failed to set Discord idle status")}}async clearPresence(t){if(!(t&&this.currentSessionId&&t!==this.currentSessionId)){if(this.lastActivity=null,this.currentSessionId=null,$r.serviceEnabled){$r.clearPresence();return}await this.setIdleStatus("idle")}}},rb=new F5;var U5=(e,t,r)=>(n,i)=>{let s=-1;return o(0);async function o(a){if(a<=s)throw new Error("next() called multiple times");s=a;let A,u=!1,c;if(e[a]?(c=e[a][0][0],n.req.routeIndex=a):c=a===e.length&&i||void 0,c)try{A=await c(n,()=>o(a+1))}catch(l){if(l instanceof Error&&t)n.error=l,A=await t(l,n),u=!0;else throw l}else n.finalized===!1&&r&&(A=await r(n));return A&&(n.finalized===!1||u)&&(n.res=A),n}};var Bi="ALL",sBe="all",oBe=["get","post","put","delete","options","patch","query"],Qx="Can not add a route since the matcher is already built.",wx=class extends Error{};var aBe="__COMPOSED_HANDLER";var Oht=e=>e.text("404 Not Found",404),ABe=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},uBe=class cBe{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...oBe,sBe].forEach(s=>{this[s]=(o,...a)=>{let A=s.toUpperCase();return typeof o=="string"?this.#e=o:this.#i(A,this.#e,o),a.forEach(u=>{this.#i(A,this.#e,u)}),this}}),this.on=(s,o,...a)=>{for(let A of[o].flat()){this.#e=A;for(let u of[s].flat()){let c=u.toUpperCase();for(let l of a)this.#i(c,this.#e,l)}}return this},this.use=(s,...o)=>(typeof s=="string"?this.#e=s:(this.#e="*",o.unshift(s)),o.forEach(a=>{this.#i(Bi,this.#e,a)}),this);let{strict:n,...i}=t;Object.assign(this,i),this.getPath=n??!0?t.getPath??Ak:x9}#t(){let t=new cBe({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Oht;errorHandler=ABe;route(t,r){let n=this.basePath(t);return r.routes.map(i=>{let s;r.errorHandler===ABe?s=i.handler:(s=async(o,a)=>(await U5([],r.errorHandler)(o,()=>i.handler(o,a))).res,s[aBe]=i.handler),n.#i(i.method,i.path,s,i.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=Il(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let i,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?i=A=>A:i=n.replaceRequest));let o=s?A=>{let u=s(A);return Array.isArray(u)?u:[u]}:A=>{let u;try{u=A.executionCtx}catch{}return[A.env,u]};i||=(()=>{let A=Il(this._basePath,t),u=A==="/"?0:A.length;return c=>{let l=new URL(c.url);return l.pathname=this.getPath(c).slice(u)||"/",new Request(l,c)}})();let a=async(A,u)=>{let c=await r(i(A.req.raw),...o(A));if(c)return c;await u()};return this.#i(Bi,Il(t,"*"),a),this}#i(t,r,n,i){r=Il(this._basePath,r);let s={basePath:i!==void 0?Il(this._basePath,i):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#s(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,i){if(i==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),o=this.router.match(i,s),a=new ck(t,{path:s,matchResult:o,env:n,executionCtx:r,notFoundHandler:this.#r});if(o[0].length===1){let u;try{u=o[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(c){return this.#s(c,a)}return u instanceof Promise?u.then(c=>c||(a.finalized?a.res:this.#r(a))).catch(c=>this.#s(c,a)):u??this.#r(a)}let A=U5(o[0],this.errorHandler,this.#r);return(async()=>{try{let u=await A(a);if(!u.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#s(u,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,i)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Il("/",t)}`,r),n,i));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var ii=()=>Object.create(null);var Sx=[];function _5(e,t){let r=this.buildAllMatchers(),n=((i,s)=>{let o=r[i]||r[Bi],a=o[2][s];if(a)return a;let A=s.match(o[0]);if(!A)return[[],Sx];let u=A.indexOf("",1);return[o[1][u],A]});return this.match=n,n(e,t)}var fm="[^/]+",zd=".*",nl="(?:|/.*)",Xd=Symbol(),lBe=new Set(".\\+*[^]$()");function Pht(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===zd||e===nl?t===nl?-1:1:t===zd||t===nl?-1:e===fm?1:t===fm?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var dBe=class O5{#e;#t;#r=ii();insert(t,r,n,i,s){let o=this;for(let a=0,A=t.length;a<A;a++){let u=t[a],c=u.length===1?u==="*"?a===A-1?["","",zd]:["","",fm]:null:u==="/*"?["","",nl]:u.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let h=c[1],d=c[2]||fm;if(h&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))||d.length===1&&lBe.has(d)))throw Xd;if(l=o.#r[d],!l){if(d!==zd&&d!==nl){for(let f in o.#r)if((d.length>1||f.length>1)&&f!==zd&&f!==nl)throw Xd}l=o.#r[d]=new O5}h!==""&&(l.#t??=i.varIndex++,n.push([h,l.#t]))}else if(l=o.#r[u],!l){for(let h in o.#r)if(h.length>1&&h!==zd&&h!==nl)throw Xd;l=o.#r[u]=new O5}o=l}if(o.#e!==void 0)throw Xd;o.#e=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(Pht).map(n=>{let i=this.#r[n],s=i.buildRegExpStr();return s===""?"":(typeof i.#t=="number"?`(${n})@${i.#t}`:lBe.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var P5=class{#e={varIndex:0};#t=new dBe;#r=0;paths=ii();insert(e,t){if(t){this.#t.insert(e.split(""),0,[],this.#e,!0);return}let r=[],n=[],i=e;for(let o=0;;){let a=!1;if(i=i.replace(/\{[^}]+\}/g,A=>{let u=`@\\${o}`;return n[o]=[u,A],o++,a=!0,u}),!a)break}let s=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=n.length-1;o>=0;o--){let[a]=n[o];for(let A=s.length-1;A>=0;A--)if(s[A].indexOf(a)!==-1){s[A]=s[A].replace(a,n[o][1]);break}}this.#t.insert(s,this.#r,r,this.#e,!1),this.paths[e]=[this.#r++,r]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,s,o)=>s!==void 0?(r[++t]=Number(s),"$()"):(o!==void 0&&(n[Number(o)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var hBe=ii();function fBe(e){return hBe[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?nl:t==="*"?zd:`/:${fm}`)}$`)}function Tx(e,t){for(let r of Object.keys(e).sort((n,i)=>i.length-n.length))if(fBe(r).test(t))return[...e[r]]}var Dx=class{name="RegExpRouter";#e;#t;#r;constructor(){this.#e={[Bi]:ii()},this.#t={[Bi]:ii()},this.#r={[Bi]:new P5}}#i(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===Xd?new wx(t):r}}add(e,t,r){let n=this.#e,i=this.#t;if(!n)throw new Error(Qx);if(!n[e]){this.#r[e]=new P5;for(let a of[n,i]){a[e]=ii();for(let A in a[Bi])a[e][A]=[...a[Bi][A]],this.#i(e,A)}}t==="/*"&&(t="*");let s=e===Bi?Object.keys(n):[e];if(/\*$/.test(t)){let a=fBe(t);for(let A of s)n[A][t]||(this.#i(A,t),n[A][t]=Tx(n[A],t)||Tx(n[Bi],t)||[]);for(let A of[n,i])for(let u of s)for(let c in A[u])a.test(c)&&A[u][c].push([r,t]);return}let o=aQ(t)||[t];for(let a of o)for(let A of s)i[A][a]||(this.#i(A,a),i[A][a]=Tx(n[A],a)||Tx(n[Bi],a)||[]),i[A][a].push([r,a])}match=_5;buildAllMatchers(){let e=ii();for(let t of Object.keys(this.#t))e[t]=this.#s(t);return this.#e=this.#t=this.#r=void 0,hBe=ii(),e}#s(e){let t=this.#e[e],r=this.#t[e],n=this.#r[e],i=ii(),s=[],[o,a,A]=n.buildRegExp();for(let u of[t,r])for(let c in u){let l=u[c],h=n.paths[c];if(!h){i[c]=[l.map(([d])=>[d,ii()]),Sx];continue}s[h[0]]=l.map(([d,f])=>[d,n.paths[f][1].reduceRight((g,[p],m)=>(g[p]=A[h[1][m][1]],g),ii())])}return[o,a.map(u=>s[u]),i]}};var H5=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,r){if(!this.#t)throw new Error(Qx);this.#t.push([e,t,r])}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,i=r.length,s=0,o;for(;s<i;s++){let a=r[s];try{for(let A=0,u=n.length;A<u;A++)a.add(...n[A]);o=a.match(e,t)}catch(A){if(A instanceof wx)continue;throw A}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(s===i)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var G5=ii(),Hht=0,gBe=class pBe{#e=[];#t=ii();#r=[];#i;#s=G5;insert(t,r,n){let i=this,s=D9(r),o=new Set,a=0;for(let A of s){let u=s[++a],c=N9(A,u)||(u===void 0&&A&&A.indexOf("*")===A.length-1?A:null),l=Array.isArray(c),h=l?c[0]:c||A,d=i.#t[h]||=new pBe;c&&!d.#i&&(d.#i=c,i.#r.push(d)),i=d,l&&o.add(c[1])}i.#e.push({[t]:{handler:n,possibleKeys:[...o],score:++Hht}})}#n(t,r,n,i,s){for(let o=0,a=r.#e.length;o<a;o++){let A=r.#e[o],u=A[n]||A[Bi];if(u){u.params=ii(),t.push(u);for(let c=0,l=u.possibleKeys.length;c<l;c++){let h=u.possibleKeys[c];u.params[h]=s?.[h]&&!c?s[h]:i[h]??s?.[h]}}}}search(t,r){let n=[];this.#s=G5;let s=[this],o=ak(r),a=[],A=o.length,u=null;for(let c=0;c<A;c++){let l=o[c],h=c===A-1,d=[];for(let g=0,p=s.length;g<p;g++){let m=s[g],I=m.#t[l];I&&(I.#s=m.#s,h?(I.#t["*"]&&this.#n(n,I.#t["*"],t,m.#s),this.#n(n,I,t,m.#s)):d.push(I));for(let C of m.#r){let y=C.#i,Q=m.#s===G5?{}:{...m.#s};if(typeof y=="string"){(y==="*"||l.startsWith(y.slice(0,-1)))&&(this.#n(n,C,t,m.#s),y==="*"&&(C.#s=Q,d.push(C)));continue}let[,D,N]=y;if(!(!l&&N===!0)){if(N!==!0){if(!u){u=[];let k=r[0]==="/"?1:0;for(let x=0;x<A;x++)u[x]=k,k+=o[x].length+1}let S=r.slice(u[c]),B=N.exec(S);if(B){Q[D]=B[0],this.#n(n,C,t,m.#s,Q),B[0].length===S.length&&C.#t["*"]&&this.#n(n,C.#t["*"],t,m.#s,Q);for(let k in C.#t){C.#s=Q;let x=B[0].match(/\//g)?.length??0;(a[x]||=[]).push(C);break}continue}}(N===!0||N.test(l))&&(Q[D]=l,h?(this.#n(n,C,t,Q,m.#s),C.#t["*"]&&this.#n(n,C.#t["*"],t,Q,m.#s)):(C.#s=Q,d.push(C)))}}}let f=a.shift();s=f?d.concat(f):d}return n[1]&&n.sort((c,l)=>c.score-l.score),[n.map(({handler:c,params:l})=>[c,l])]}};var Y5=class{name="TrieRouter";#e=new gBe;add(e,t,r){for(let n of aQ(t)||[t])this.#e.insert(e,n,r)}match(e,t){return this.#e.search(e,t)}};var V5=class extends uBe{constructor(e={}){super(e),this.router=e.router??new H5({routers:[new Dx,new Y5]})}};var mBe=e=>e===32||e===9||e===10||e===13,Nx=(e,t)=>{for(;t<e.length&&mBe(e.charCodeAt(t));)t++;return t},nb=(e,t)=>{for(;t>0&&mBe(e.charCodeAt(t-1));)t--;return t},EBe=(e,t)=>{for(;t<e.length;){let r=e.charCodeAt(t);if(r===59)return[t+1,!0];if(r===44)return[t+1,!1];t++}return[t,!1]},Ght=(e,t)=>{let r=t,n=!1;for(;r<e.length;){let i=e.charCodeAt(r);if(n&&i===92)r++;else if(i===34)n=!n;else if(!n&&i===44)return r+1;r++}return r},Yht=(e,t)=>{t=Nx(e,t);let r=t,n,i,s=!1;for(;r<e.length;){let A=e.charCodeAt(r);if(A===61){n=e.slice(t,nb(e,r)),r++;break}if(A===59)return[r+1,void 0,void 0,!0];if(A===44)return[r+1,void 0,void 0,!1];r++}if(n===void 0)return[r,void 0,void 0,!1];if(r=Nx(e,r),e.charCodeAt(r)===61){let A=EBe(e,r+1);return[A[0],n,void 0,A[1]]}let o=!1,a=r;for(;r<e.length;){let A=e.charCodeAt(r);if(o&&A===92)r++;else if(A===34){if(o){let u=Nx(e,r+1),c=e.charCodeAt(u);if(u<e.length&&!(c===59||c===44)){let l=EBe(e,u);return[l[0],n,void 0,l[1]]}if(i=e.slice(a+1,r),i.includes("\\")&&(i=i.replace(/\\(.)/g,"$1")),c===44)return[u+1,n,i,!1];c===59&&(s=!0,u++),r=u;break}o=!0}else if(!o&&(A===59||A===44)){i=e.slice(a,nb(e,r)),A===59&&(s=!0),r++;break}r++}return[r,n,i??e.slice(a,nb(e,r)),s]},Vht=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Nx(e,t);let n=t;for(;n<e.length;){let a=e.charCodeAt(n);if(a===59||a===44){if(r.type=e.slice(t,nb(e,n)),n++,a===44)return[n,r.type?r:void 0];if(!r.type)return[Ght(e,n),void 0];break}n++}if(!r.type)return r.type=e.slice(t,nb(e,e.length)),[e.length,r.type?r:void 0];let i,s,o;for(;n<e.length&&([n,i,s,o]=Yht(e,n),i&&s&&(r.params[i]=s),!!o););return[n,r]},IBe=e=>{if(!e)return[];let t=[],r=0,n,i=!1,s;for(;r<e.length;)[r,n]=Vht(e,r),n&&(n.q=Wht(n.params.q??n.params.Q),t.push(n),s&&s.q<n.q&&(i=!0),s=n);return i&&t.sort((o,a)=>a.q-o.q),t},Wht=e=>{if(e===void 0||e==="")return 1;if(e==="NaN")return 0;let t=Number(e);return Number.isNaN(t)?1:t<0?0:t>1?1:t};var CBe=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml|msgpack))(?:[;\s]|$)/i;var qht=["gzip","deflate"],Jht=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,jht=(e,t)=>{if(e===void 0)return;let r=IBe(e),n=r.find(s=>s.type==="*")?.q,i;for(let s of t){let o=r.find(A=>A.type.toLowerCase()===s),a=o?o.q:n??0;if(a===1)return s;a>0&&(!i||a>i.q)&&(i={encoding:s,q:a})}return i?.encoding},$ht=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,BBe=e=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:qht,n=e?.contentTypeFilter??CBe,i=typeof n=="function"?s=>{let o=s.headers.get("Content-Type");return o&&n(o)}:s=>{let o=s.headers.get("Content-Type");return o&&n.test(o)};return async function(o,a){await a();let A=o.res.headers.get("Content-Length");if(o.res.status===206||o.res.headers.has("Content-Encoding")||o.res.headers.has("Transfer-Encoding")||o.req.method==="HEAD"||A&&Number(A)<t||!i(o.res)||!Kht(o.res))return;let u=o.res.headers.get("Vary");u!=="*"&&!(u&&$ht.test(u))&&o.header("Vary",u?`${u}, Accept-Encoding`:"Accept-Encoding");let c=o.req.header("Accept-Encoding"),l=jht(c,r);if(!l||!o.res.body)return;let h=new CompressionStream(l);o.res=new Response(o.res.body.pipeThrough(h),o.res),o.res.headers.delete("Content-Length"),o.res.headers.set("Content-Encoding",l);let d=o.res.headers.get("ETag");d&&!d.startsWith("W/")&&o.res.headers.set("ETag",`W/${d}`)}},Kht=e=>{let t=e.headers.get("Cache-Control");return!t||!Jht.test(t)};import Swe from"path";import Vm from"fs";var yBe=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",Xht=yBe+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",zht="["+yBe+"]["+Xht+"]*",Zht=new RegExp("^"+zht+"$");function bBe(e,t){let r=[],n=t.exec(e);for(;n;){let i=[];i.startIndex=t.lastIndex-n[0].length;let s=n.length;for(let o=0;o<s;o++)i.push(n[o]);r.push(i),n=t.exec(e)}return r}var W5=function(e){let t=Zht.exec(e);return!(t===null||typeof t>"u")};function QBe(e){return typeof e<"u"}var ib=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],Rx=["__proto__","constructor","prototype"];var eft={allowBooleanAttributes:!1,unpairedTags:[]};function DBe(e,t){t=Object.assign({},eft,t);let r=[],n=!1,i=!1;e[0]==="\uFEFF"&&(e=e.substr(1));for(let s=0;s<e.length;s++)if(e[s]==="<"&&e[s+1]==="?"){if(s+=2,s=wBe(e,s),s.err)return s}else if(e[s]==="<"){let o=s;if(s++,e[s]==="!"){s=SBe(e,s);continue}else{let a=!1;e[s]==="/"&&(a=!0,s++);let A="";for(;s<e.length&&e[s]!==">"&&e[s]!==" "&&e[s]!==" "&&e[s]!==`
|
|
470
470
|
`&&e[s]!=="\r";s++)A+=e[s];if(A=A.trim(),A[A.length-1]==="/"&&(A=A.substring(0,A.length-1),s--),!Aft(A)){let l;return A.trim().length===0?l="Invalid space after '<'.":l="Tag '"+A+"' is an invalid name.",gn("InvalidTag",l,ds(e,s))}let u=nft(e,s);if(u===!1)return gn("InvalidAttr","Attributes for '"+A+"' have open quote.",ds(e,s));let c=u.value;if(s=u.index,c[c.length-1]==="/"){let l=s-c.length;c=c.substring(0,c.length-1);let h=TBe(c,t);if(h===!0)n=!0;else return gn(h.err.code,h.err.msg,ds(e,l+h.err.line))}else if(a)if(u.tagClosed){if(c.trim().length>0)return gn("InvalidTag","Closing tag '"+A+"' can't have attributes or invalid starting.",ds(e,o));if(r.length===0)return gn("InvalidTag","Closing tag '"+A+"' has not been opened.",ds(e,o));{let l=r.pop();if(A!==l.tagName){let h=ds(e,l.tagStartPos);return gn("InvalidTag","Expected closing tag '"+l.tagName+"' (opened in line "+h.line+", col "+h.col+") instead of closing tag '"+A+"'.",ds(e,o))}r.length==0&&(i=!0)}}else return gn("InvalidTag","Closing tag '"+A+"' doesn't have proper closing.",ds(e,s));else{let l=TBe(c,t);if(l!==!0)return gn(l.err.code,l.err.msg,ds(e,s-c.length+l.err.line));if(i===!0)return gn("InvalidXml","Multiple possible root nodes found.",ds(e,s));t.unpairedTags.indexOf(A)!==-1||r.push({tagName:A,tagStartPos:o}),n=!0}for(s++;s<e.length;s++)if(e[s]==="<")if(e[s+1]==="!"){s++,s=SBe(e,s);continue}else if(e[s+1]==="?"){if(s=wBe(e,++s),s.err)return s}else break;else if(e[s]==="&"){let l=oft(e,s);if(l==-1)return gn("InvalidChar","char '&' is not expected.",ds(e,s));s=l}else if(i===!0&&!gm(e[s]))return gn("InvalidXml","Extra text at the end",ds(e,s));e[s]==="<"&&s--}}else{if(gm(e[s]))continue;return gn("InvalidChar","char '"+e[s]+"' is not expected.",ds(e,s))}if(n){if(r.length==1)return gn("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",ds(e,r[0].tagStartPos));if(r.length>0)return gn("InvalidXml","Invalid '"+JSON.stringify(r.map(s=>s.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return gn("InvalidXml","Start tag expected.",1);return!0}function gm(e){return e===" "||e===" "||e===`
|
|
471
471
|
`||e==="\r"}function wBe(e,t){let r=t;for(;t<e.length;t++)if(e[t]=="?"||e[t]==" "){let n=e.substr(r,t-r);if(t>5&&n==="xml")return gn("InvalidXml","XML declaration allowed only at the start of the document.",ds(e,t));if(e[t]=="?"&&e[t+1]==">"){t++;break}else continue}return t}function SBe(e,t){if(e.length>t+5&&e[t+1]==="-"&&e[t+2]==="-"){for(t+=3;t<e.length;t++)if(e[t]==="-"&&e[t+1]==="-"&&e[t+2]===">"){t+=2;break}}else if(e.length>t+8&&e[t+1]==="D"&&e[t+2]==="O"&&e[t+3]==="C"&&e[t+4]==="T"&&e[t+5]==="Y"&&e[t+6]==="P"&&e[t+7]==="E"){let r=1;for(t+=8;t<e.length;t++)if(e[t]==="<")r++;else if(e[t]===">"&&(r--,r===0))break}else if(e.length>t+9&&e[t+1]==="["&&e[t+2]==="C"&&e[t+3]==="D"&&e[t+4]==="A"&&e[t+5]==="T"&&e[t+6]==="A"&&e[t+7]==="["){for(t+=8;t<e.length;t++)if(e[t]==="]"&&e[t+1]==="]"&&e[t+2]===">"){t+=2;break}}return t}var tft='"',rft="'";function nft(e,t){let r="",n="",i=!1;for(;t<e.length;t++){if(e[t]===tft||e[t]===rft)n===""?n=e[t]:n!==e[t]||(n="");else if(e[t]===">"&&n===""){i=!0;break}r+=e[t]}return n!==""?!1:{value:r,index:t,tagClosed:i}}function ift(e){let t=[],r=e.length,n=0;for(;n<r;){let i=n;for(;n<r&&gm(e[n]);)n++;if(n>=r)break;if(e[n]==="="){n=i+1;continue}let s=e.slice(i,n),o=n;for(;n<r&&!gm(e[n])&&e[n]!=="=";)n++;let a=e.slice(o,n),A,u=n;for(;u<r&&gm(e[u]);)u++;u<r&&e[u]==="="&&(A=e.slice(n,u+1),n=u+1);let c,l,h=n;for(;h<r&&gm(e[h]);)h++;if(h<r&&(e[h]==='"'||e[h]==="'")){let f=h+1,g=e.indexOf(e[h],f);g!==-1&&(c=e[h],l=e.slice(f,g),n=g+1)}let d={startIndex:i};d[1]=s,d[2]=a,d[3]=A,d[4]=c!==void 0?!0:void 0,d[5]=c,d[6]=l,t.push(d)}return t}function TBe(e,t){let r=ift(e),n={};for(let i=0;i<r.length;i++){if(r[i][1].length===0)return gn("InvalidAttr","Attribute '"+r[i][2]+"' has no space in starting.",sb(r[i]));if(r[i][3]!==void 0&&r[i][4]===void 0)return gn("InvalidAttr","Attribute '"+r[i][2]+"' is without value.",sb(r[i]));if(r[i][3]===void 0&&!t.allowBooleanAttributes)return gn("InvalidAttr","boolean attribute '"+r[i][2]+"' is not allowed.",sb(r[i]));let s=r[i][2];if(!aft(s))return gn("InvalidAttr","Attribute '"+s+"' is an invalid name.",sb(r[i]));if(!Object.prototype.hasOwnProperty.call(n,s))n[s]=1;else return gn("InvalidAttr","Attribute '"+s+"' is repeated.",sb(r[i]))}return!0}function sft(e,t){let r=/\d/;for(e[t]==="x"&&(t++,r=/[\da-fA-F]/);t<e.length;t++){if(e[t]===";")return t;if(!e[t].match(r))break}return-1}function oft(e,t){if(t++,e[t]===";")return-1;if(e[t]==="#")return t++,sft(e,t);let r=0;for(;t<e.length;t++,r++)if(!(e[t].match(/\w/)&&r<20)){if(e[t]===";")break;return-1}return t}function gn(e,t,r){return{err:{code:e,msg:t,line:r.line||r,col:r.col}}}function aft(e){return W5(e)}function Aft(e){return W5(e)}function ds(e,t){let r=e.substring(0,t).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function sb(e){return e.startIndex+e[1].length}var q5={cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",euro:"\u20AC",dollar:"$",fnof:"\u0192",inr:"\u20B9",af:"\u060B",birr:"\u1265\u122D",peso:"\u20B1",rub:"\u20BD",won:"\u20A9",yuan:"\xA5",cedil:"\xB8"};var ob={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},J5={nbsp:"\xA0",copy:"\xA9",reg:"\xAE",trade:"\u2122",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",laquo:"\xAB",raquo:"\xBB",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",bull:"\u2022",para:"\xB6",sect:"\xA7",deg:"\xB0",frac12:"\xBD",frac14:"\xBC",frac34:"\xBE"};var pm=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),uft=new Set("!?\\\\/[]$%{}^&*()<>|+");function NBe(e){if(e[0]==="#")throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${e}"`);for(let t of e)if(uft.has(t))throw new Error(`[EntityReplacer] Invalid character '${t}' in entity name: "${e}"`);return e}function ab(...e){let t=Object.create(null);for(let r of e)if(r)for(let n of Object.keys(r)){let i=r[n];if(typeof i=="string")t[n]=i;else if(i&&typeof i=="object"&&i.val!==void 0){let s=i.val;typeof s=="string"&&(t[n]=s)}}return t}var wg="external",xx="base",j5="all";function cft(e){return!e||e===wg?new Set([wg]):e===j5?new Set([j5]):e===xx?new Set([xx]):Array.isArray(e)?new Set(e):new Set([wg])}var $s=Object.freeze({allow:0,leave:1,remove:2,throw:3}),lft=new Set([9,10,13]);function dft(e){if(!e)return{xmlVersion:1,onLevel:$s.allow,nullLevel:$s.remove};let t=e.xmlVersion===1.1?1.1:1,r=$s[e.onNCR]??$s.allow,n=$s[e.nullNCR]??$s.remove,i=Math.max(n,$s.remove);return{xmlVersion:t,onLevel:r,nullLevel:i}}var Em=class{constructor(t={}){this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck=typeof t.postCheck=="function"?t.postCheck:n=>n,this._limitTiers=cft(this._limit.applyLimitsTo??wg),this._numericAllowed=t.numericAllowed??!0,this._baseMap=ab(ob,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);let r=dft(t.ncr);this._ncrXmlVersion=r.xmlVersion,this._ncrOnLevel=r.onLevel,this._ncrNullLevel=r.nullLevel,this._onExternalEntity=typeof t.onExternalEntity=="function"?t.onExternalEntity:null,this._onInputEntity=typeof t.onInputEntity=="function"?t.onInputEntity:null}_applyRegistrationHook(t,r,n,i){if(!t)return!0;let s=t(r,n);if(s===pm.BLOCK)return!1;if(s===pm.THROW)throw new Error(`[EntityDecoder] Registration of ${i} entity "&${r};" was rejected by hook`);return!0}setExternalEntities(t){if(t)for(let i of Object.keys(t))NBe(i);if(!this._onExternalEntity){this._externalMap=ab(t);return}let r=ab(t),n=Object.create(null);for(let[i,s]of Object.entries(r))this._applyRegistrationHook(this._onExternalEntity,i,s,"external")&&(n[i]=s);this._externalMap=n}addExternalEntity(t,r){NBe(t),typeof r=="string"&&r.indexOf("&")===-1&&this._applyRegistrationHook(this._onExternalEntity,t,r,"external")&&(this._externalMap[t]=r)}addInputEntities(t){if(this._totalExpansions=0,this._expandedLength=0,!this._onInputEntity){this._inputMap=ab(t);return}let r=ab(t),n=Object.create(null);for(let[i,s]of Object.entries(r))this._applyRegistrationHook(this._onInputEntity,i,s,"input")&&(n[i]=s);this._inputMap=n}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=t===1.1?1.1:1}decode(t){if(typeof t!="string"||t.length===0||t.indexOf("&")===-1)return t;let r=t,n=[],i=t.length,s=0,o=0,a=this._maxTotalExpansions>0,A=this._maxExpandedLength>0,u=a||A;for(;o<i;){if(t.charCodeAt(o)!==38){o++;continue}let l=o+1;for(;l<i&&t.charCodeAt(l)!==59&&l-o<=32;)l++;if(l>=i||t.charCodeAt(l)!==59){o++;continue}let h=t.slice(o+1,l);if(h.length===0){o++;continue}let d,f;if(this._removeSet.has(h))d="",f===void 0&&(f=wg);else if(this._leaveSet.has(h)){o++;continue}else if(h.charCodeAt(0)===35){let g=this._resolveNCR(h);if(g===void 0){o++;continue}d=g,f=xx}else{let g=this._resolveName(h);d=g?.value,f=g?.tier}if(d===void 0){o++;continue}if(o>s&&n.push(t.slice(s,o)),n.push(d),s=l+1,o=s,u&&this._tierCounts(f)){if(a&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(A){let g=d.length-(h.length+2);if(g>0&&(this._expandedLength+=g,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}s<i&&n.push(t.slice(s));let c=n.length===0?t:n.join("");return this._postCheck(c,r)}_tierCounts(t){return this._limitTiers.has(j5)?!0:this._limitTiers.has(t)}_resolveName(t){if(t in this._inputMap)return{value:this._inputMap[t],tier:wg};if(t in this._externalMap)return{value:this._externalMap[t],tier:wg};if(t in this._baseMap)return{value:this._baseMap[t],tier:xx}}_classifyNCR(t){return t===0?this._ncrNullLevel:t>=55296&&t<=57343||this._ncrXmlVersion===1&&t>=1&&t<=31&&!lft.has(t)?$s.remove:-1}_applyNCRAction(t,r,n){switch(t){case $s.allow:return String.fromCodePoint(n);case $s.remove:return"";case $s.leave:return;case $s.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${r}; (U+${n.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(n)}}_resolveNCR(t){let r=t.charCodeAt(1),n;if(r===120||r===88?n=parseInt(t.slice(2),16):n=parseInt(t.slice(1),10),Number.isNaN(n)||n<0||n>1114111)return;let i=this._classifyNCR(n);if(!this._numericAllowed&&i<$s.remove)return;let s=i===-1?this._ncrOnLevel:Math.max(this._ncrOnLevel,i);return this._applyNCRAction(s,t,n)}};var RBe=e=>ib.includes(e)?"__"+e:e,hft={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0,unicode:!1},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,r){return e},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:RBe};function fft(e,t){if(typeof e!="string")return;let r=e.toLowerCase();if(ib.some(n=>r===n.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);if(Rx.some(n=>r===n.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`)}function xBe(e,t){return typeof e=="boolean"?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:typeof e=="object"&&e!==null?{enabled:e.enabled!==!1,maxEntitySize:Math.max(1,e.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,e.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,e.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,e.maxExpandedLength??1e5),maxEntityCount:Math.max(1,e.maxEntityCount??1e3),allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null,appliesTo:e.appliesTo??"all"}:xBe(!0)}var vBe=function(e){let t=Object.assign({},hft,e),r=[{value:t.attributeNamePrefix,name:"attributeNamePrefix"},{value:t.attributesGroupName,name:"attributesGroupName"},{value:t.textNodeName,name:"textNodeName"},{value:t.cdataPropName,name:"cdataPropName"},{value:t.commentPropName,name:"commentPropName"}];for(let{value:n,name:i}of r)n&&fft(n,i);return t.onDangerousProperty===null&&(t.onDangerousProperty=RBe),t.processEntities=xBe(t.processEntities,t.htmlEntities),t.unpairedTagsSet=new Set(t.unpairedTags),t.stopNodes&&Array.isArray(t.stopNodes)&&(t.stopNodes=t.stopNodes.map(n=>typeof n=="string"&&n.startsWith("*.")?".."+n.substring(2):n)),t};var Sg;typeof Symbol!="function"?Sg="@@xmlMetadata":Sg=Symbol("XML Node Metadata");var Ks=class{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,r){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:r})}addChild(t,r){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),this.addStartIndex(r)}addStartIndex(t){t!==void 0&&(this.child[this.child.length-1][Sg]={startIndex:t})}addEndIndex(t){let r=this.child[this.child.length-1];r!==void 0&&r[Sg]!==void 0&&r[Sg].endIndex===void 0&&(r[Sg].endIndex=t)}static getMetaDataSymbol(){return Sg}};var kBe=":A-Za-z_\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD",gft=kBe+"\\-\\.\\d\xB7\u0300-\u036F\u203F-\u2040",LBe=":A-Za-z_\xC0-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}",pft=LBe+"\\-\\.\\d\xB7\u0300-\u036F\u0487\u203F-\u2040",$5=(e,t,r="")=>{let n=e.replace(":",""),i=t.replace(":",""),s=`[${n}][${i}]*`;return{name:new RegExp(`^[${e}][${t}]*$`,r),ncName:new RegExp(`^${s}$`,r),qName:new RegExp(`^${s}(?::${s})?$`,r),nmToken:new RegExp(`^[${t}]+$`,r),nmTokens:new RegExp(`^[${t}]+(?:\\s+[${t}]+)*$`,r)}},Eft=$5(kBe,gft),mft=$5(LBe,pft,"u"),MBe=":A-Za-z_",Ift=MBe+"\\-\\.\\d",Cft=$5(MBe,Ift),Bft=(e="1.0",t=!1)=>t?Cft:e==="1.1"?mft:Eft;var K5=(e,{xmlVersion:t="1.0",asciiOnly:r=!1}={})=>Bft(t,r).qName.test(e);var ub=class{constructor(t,r){this.suppressValidationErr=!t,this.options=t,this.xmlVersion=r||1}setXmlVersion(t=1){this.xmlVersion=t}readDocType(t,r){let n=Object.create(null),i=0;if(t[r+3]==="O"&&t[r+4]==="C"&&t[r+5]==="T"&&t[r+6]==="Y"&&t[r+7]==="P"&&t[r+8]==="E"){r=r+9;let s=1,o=!1,a=!1,A=null,u="";for(;r<t.length;r++){if(A!==null){t[r]===A&&(A=null),u+=t[r];continue}if(!o&&!a&&(t[r]==='"'||t[r]==="'")){A=t[r],u+=t[r];continue}if(t[r]==="<"&&!a){if(o&&Tg(t,"!ENTITY",r)){r+=7;let c,l;if([c,l,r]=this.readEntityExp(t,r+1,this.suppressValidationErr),l.indexOf("&")===-1){if(this.options.enabled!==!1&&this.options.maxEntityCount!=null&&i>=this.options.maxEntityCount)throw new Error(`Entity count (${i+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);n[c]=l,i++}}else if(o&&Tg(t,"!ELEMENT",r)){r+=8;let{index:c}=this.readElementExp(t,r+1);r=c}else if(o&&Tg(t,"!ATTLIST",r))r+=8;else if(o&&Tg(t,"!NOTATION",r)){r+=9;let{index:c}=this.readNotationExp(t,r+1,this.suppressValidationErr);r=c}else if(Tg(t,"!--",r))a=!0;else throw new Error("Invalid DOCTYPE");s++,u=""}else if(t[r]===">"){if(a?t[r-1]==="-"&&t[r-2]==="-"&&(a=!1,s--):s--,s===0)break}else t[r]==="["?o=!0:u+=t[r]}if(A!==null||s!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:n,i:r}}readEntityExp(t,r){r=Xs(t,r);let n=r;for(;r<t.length&&!/\s/.test(t[r])&&t[r]!=='"'&&t[r]!=="'";)r++;let i=t.substring(n,r);if(Ab(i,{xmlVersion:this.xmlVersion}),r=Xs(t,r),!this.suppressValidationErr){if(t.substring(r,r+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(t[r]==="%")throw new Error("Parameter entities are not supported")}let s="";if([r,s]=this.readIdentifierVal(t,r,"entity"),this.options.enabled!==!1&&this.options.maxEntitySize!=null&&s.length>this.options.maxEntitySize)throw new Error(`Entity "${i}" size (${s.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return r--,[i,s,r]}readNotationExp(t,r){r=Xs(t,r);let n=r;for(;r<t.length&&!/\s/.test(t[r]);)r++;let i=t.substring(n,r);!this.suppressValidationErr&&Ab(i,{xmlVersion:this.xmlVersion}),r=Xs(t,r);let s=t.substring(r,r+6).toUpperCase();if(!this.suppressValidationErr&&s!=="SYSTEM"&&s!=="PUBLIC")throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);r+=s.length,r=Xs(t,r);let o=null,a=null;if(s==="PUBLIC")[r,o]=this.readIdentifierVal(t,r,"publicIdentifier"),r=Xs(t,r),(t[r]==='"'||t[r]==="'")&&([r,a]=this.readIdentifierVal(t,r,"systemIdentifier"));else if(s==="SYSTEM"&&([r,a]=this.readIdentifierVal(t,r,"systemIdentifier"),!this.suppressValidationErr&&!a))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:i,publicIdentifier:o,systemIdentifier:a,index:--r}}readIdentifierVal(t,r,n){let i="",s=t[r];if(s!=='"'&&s!=="'")throw new Error(`Expected quoted string, found "${s}"`);r++;let o=r;for(;r<t.length&&t[r]!==s;)r++;if(i=t.substring(o,r),t[r]!==s)throw new Error(`Unterminated ${n} value`);return r++,[r,i]}readElementExp(t,r){r=Xs(t,r);let n=r;for(;r<t.length&&!/\s/.test(t[r]);)r++;let i=t.substring(n,r);if(!this.suppressValidationErr&&!K5(i,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid element name: "${i}"`);r=Xs(t,r);let s="";if(t[r]==="E"&&Tg(t,"MPTY",r))r+=4;else if(t[r]==="A"&&Tg(t,"NY",r))r+=2;else if(t[r]==="("){r++;let o=r;for(;r<t.length&&t[r]!==")";)r++;if(s=t.substring(o,r),t[r]!==")")throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[r]}"`);return{elementName:i,contentModel:s.trim(),index:r}}readAttlistExp(t,r){r=Xs(t,r);let n=r;for(;r<t.length&&!/\s/.test(t[r]);)r++;let i=t.substring(n,r);for(Ab(i,{xmlVersion:this.xmlVersion}),r=Xs(t,r),n=r;r<t.length&&!/\s/.test(t[r]);)r++;let s=t.substring(n,r);if(!Ab(s,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid attribute name: "${s}"`);r=Xs(t,r);let o="";if(t.substring(r,r+8).toUpperCase()==="NOTATION"){if(o="NOTATION",r+=8,r=Xs(t,r),t[r]!=="(")throw new Error(`Expected '(', found "${t[r]}"`);r++;let A=[];for(;r<t.length&&t[r]!==")";){let u=r;for(;r<t.length&&t[r]!=="|"&&t[r]!==")";)r++;let c=t.substring(u,r);if(c=c.trim(),!Ab(c,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid notation name: "${c}"`);A.push(c),t[r]==="|"&&(r++,r=Xs(t,r))}if(t[r]!==")")throw new Error("Unterminated list of notations");r++,o+=" ("+A.join("|")+")"}else{let A=r;for(;r<t.length&&!/\s/.test(t[r]);)r++;o+=t.substring(A,r);let u=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!u.includes(o.toUpperCase()))throw new Error(`Invalid attribute type: "${o}"`)}r=Xs(t,r);let a="";return t.substring(r,r+8).toUpperCase()==="#REQUIRED"?(a="#REQUIRED",r+=8):t.substring(r,r+7).toUpperCase()==="#IMPLIED"?(a="#IMPLIED",r+=7):[r,a]=this.readIdentifierVal(t,r,"ATTLIST"),{elementName:i,attributeName:s,attributeType:o,defaultValue:a,index:r}}},Xs=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function Tg(e,t,r){for(let n=0;n<t.length;n++)if(t[n]!==e[r+n+1])return!1;return!0}function Ab(e,t){if(K5(e,{xmlVersion:t}))return e;throw new Error(`Invalid entity name ${e}`)}var yft=[48,1632,1776,2406,2534,2662,2790,2918,3046,3174,3302,3430,3558,3664,3792,3872,4160,4240,6112,6160,6470,6608,6784,6800,6992,7088,7232,7248,65296,120782,120792,120802,120812,120822,66720,68912,69734,69872,69942,70096,70384,70736,70864,71248,71360,71472,71904,72016,72688,72784,73040,73120,73552,92768,92864,93008,123200,123632,124144,125264,130032],vx=255,kx=new Map,FBe=65535,UBe=1632,mm=UBe,bft=FBe-UBe+1,Lx=new Uint8Array(bft).fill(vx);for(let e of yft)for(let t=0;t<10;t++){let r=e+t;r<=FBe?Lx[r-mm]=t:kx.set(r,t)}var _Be=48,OBe=57,PBe=45,Mx=new Set([8722,65293,65123]);function Qft(e){if(typeof e!="string")return e;let t=e.length;if(t===0)return e;let r=-1;for(let i=0;i<t;i++){let s=e.charCodeAt(i);if(!(s>=_Be&&s<=OBe||s===PBe)){if(s<mm){if(Mx.has(s)){r=i;break}continue}if(s>=55296&&s<=56319){if(i+1<t){let o=e.charCodeAt(i+1);if(o>=56320&&o<=57343){let a=65536+(s-55296<<10)+(o-56320);if(kx.has(a)){r=i;break}}}continue}if(Lx[s-mm]!==vx||Mx.has(s)){r=i;break}}}if(r===-1)return e;let n=[];r>0&&n.push(e.slice(0,r));for(let i=r;i<t;i++){let s=e.charCodeAt(i);if(s>=_Be&&s<=OBe||s===PBe){n.push(e[i]);continue}if(s<mm){n.push(Mx.has(s)?"-":e[i]);continue}if(s>=55296&&s<=56319){if(i+1<t){let a=e.charCodeAt(i+1);if(a>=56320&&a<=57343){let A=65536+(s-55296<<10)+(a-56320),u=kx.get(A);if(u!==void 0){n.push(String.fromCharCode(u+48)),i++;continue}}}n.push(e[i]);continue}if(Mx.has(s)){n.push("-");continue}let o=Lx[s-mm];n.push(o!==vx?String.fromCharCode(o+48):e[i])}return n.join("")}var HBe=Qft;var wft=/^[-+]?0x[a-fA-F0-9]+$/,Sft=/^0b[01]+$/,Tft=/^0o[0-7]+$/,Dft=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Nft={hex:!0,binary:!1,octal:!1,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original",unicode:!1};function z5(e,t={}){if(t=Object.assign({},Nft,t),!e||typeof e!="string")return e;let r=e.trim();if(r.length===0)return e;if(t.skipLike!==void 0&&t.skipLike.test(r))return e;if(r==="0"||t.unicode&&(r=HBe(r),r==="0"))return 0;if(t.hex&&wft.test(r))return X5(r,16);if(t.binary&&Sft.test(r))return X5(r,2);if(t.octal&&Tft.test(r))return X5(r,8);if(isFinite(r)){if(r.includes("e")||r.includes("E"))return xft(e,r,t);{let n=Dft.exec(r);if(n){let i=n[1]||"",s=n[2],o=vft(n[3]),a=i?e[s.length+1]===".":e[s.length]===".";if(!t.leadingZeros&&(s.length>1||s.length===1&&!a))return e;{let A=Number(r),u=String(A);if(A===0)return A;if(u.search(/[eE]/)!==-1)return t.eNotation?A:e;if(r.indexOf(".")!==-1)return u==="0"||u===o||u===`${i}${o}`?A:e;let c=s?o:r;return s?c===u||i+c===u?A:e:c===u||c===i+u?A:e}}else return e}}else return kft(e,Number(r),t)}var Rft=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function xft(e,t,r){if(!r.eNotation)return e;let n=t.match(Rft);if(n){let i=n[1]||"",s=n[3].indexOf("e")===-1?"E":"e",o=n[2],a=i?e[o.length+1]===s:e[o.length]===s;return o.length>1&&a?e:o.length===1&&(n[3].startsWith(`.${s}`)||n[3][0]===s)?Number(t):o.length>0?r.leadingZeros&&!a?(t=(n[1]||"")+n[3],Number(t)):e:Number(t)}else return e}function vft(e){if(e&&e.indexOf(".")!==-1){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===48;)t--;return e=e.slice(0,t),e==="."?e="0":e[0]==="."?e="0"+e:e[e.length-1]==="."&&(e=e.substring(0,e.length-1)),e}return e}function X5(e,t){let r=e.trim();if((t===2||t===8)&&(e=r.substring(2)),parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function kft(e,t,r){let n=t===1/0;switch(r.infinity.toLowerCase()){case"null":return null;case"infinity":return t;case"string":return n?"Infinity":"-Infinity";default:return e}}function Z5(e){return typeof e=="function"?e:Array.isArray(e)?t=>{for(let r of e)if(typeof r=="string"&&t===r||r instanceof RegExp&&r.test(t))return!0}:()=>!1}var Dg=class{constructor(t,r={},n){this.pattern=t,this.separator=r.separator||".",this.segments=this._parse(t),this.data=n,this._hasDeepWildcard=this.segments.some(i=>i.type==="deep-wildcard"),this._hasAttributeCondition=this.segments.some(i=>i.attrName!==void 0),this._hasPositionSelector=this.segments.some(i=>i.position!==void 0)}_parse(t){let r=[],n=0,i="";for(;n<t.length;)t[n]===this.separator?n+1<t.length&&t[n+1]===this.separator?(i.trim()&&(r.push(this._parseSegment(i.trim())),i=""),r.push({type:"deep-wildcard"}),n+=2):(i.trim()&&r.push(this._parseSegment(i.trim())),i="",n++):(i+=t[n],n++);return i.trim()&&r.push(this._parseSegment(i.trim())),r}_parseSegment(t){let r={type:"tag"},n=null,i=t,s=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(s&&(i=s[1]+s[3],s[2])){let c=s[2].slice(1,-1);c&&(n=c)}let o,a=i;if(i.includes("::")){let c=i.indexOf("::");if(o=i.substring(0,c).trim(),a=i.substring(c+2).trim(),!o)throw new Error(`Invalid namespace in pattern: ${t}`)}let A,u=null;if(a.includes(":")){let c=a.lastIndexOf(":"),l=a.substring(0,c).trim(),h=a.substring(c+1).trim();["first","last","odd","even"].includes(h)||/^nth\(\d+\)$/.test(h)?(A=l,u=h):A=a}else A=a;if(!A)throw new Error(`Invalid segment pattern: ${t}`);if(r.tag=A,o&&(r.namespace=o),n)if(n.includes("=")){let c=n.indexOf("=");r.attrName=n.substring(0,c).trim(),r.attrValue=n.substring(c+1).trim()}else r.attrName=n.trim();if(u){let c=u.match(/^nth\((\d+)\)$/);c?(r.position="nth",r.positionValue=parseInt(c[1],10)):r.position=u}return r}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}};var Im=class{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._deepByTerminalTag=new Map,this._patterns=new Set,this._sealed=!1}add(t){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(t.pattern))return this;if(this._patterns.add(t.pattern),t.hasDeepWildcard()){let s=t.segments[t.segments.length-1];if(s&&s.type!=="deep-wildcard"&&s.tag!=="*"){let o=s.tag;this._deepByTerminalTag.has(o)||this._deepByTerminalTag.set(o,[]),this._deepByTerminalTag.get(o).push(t)}else this._deepWildcards.push(t);return this}let r=t.length,i=t.segments[t.segments.length-1]?.tag;if(!i||i==="*")this._wildcardByDepth.has(r)||this._wildcardByDepth.set(r,[]),this._wildcardByDepth.get(r).push(t);else{let s=`${r}:${i}`;this._byDepthAndTag.has(s)||this._byDepthAndTag.set(s,[]),this._byDepthAndTag.get(s).push(t)}return this}addAll(t){for(let r of t)this.add(r);return this}has(t){return this._patterns.has(t.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(t){return this.findMatch(t)!==null}findMatch(t){let r=t.getDepth(),n=t.getCurrentTag(),i=`${r}:${n}`,s=this._byDepthAndTag.get(i);if(s){for(let A=0;A<s.length;A++)if(t.matches(s[A]))return s[A]}let o=this._wildcardByDepth.get(r);if(o){for(let A=0;A<o.length;A++)if(t.matches(o[A]))return o[A]}let a=this._deepByTerminalTag.get(n);if(a){for(let A=0;A<a.length;A++)if(t.matches(a[A]))return a[A]}for(let A=0;A<this._deepWildcards.length;A++)if(t.matches(this._deepWildcards[A]))return this._deepWildcards[A];return null}};var eG=class{constructor(t){this._matcher=t}get separator(){return this._matcher.separator}getCurrentTag(){let t=this._matcher.path;return t.length>0?t[t.length-1].tag:void 0}getCurrentNamespace(){let t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){let r=this._matcher.path;if(r.length!==0)return r[r.length-1].values?.[t]}hasAttr(t){let r=this._matcher.path;if(r.length===0)return!1;let n=r[r.length-1];return n.values!==void 0&&t in n.values}getAnyParentAttr(t){return this._matcher.getAnyParentAttr(t)}hasAnyParentAttr(t){return this._matcher.hasAnyParentAttr(t)}getPosition(){let t=this._matcher.path;return t.length===0?-1:t[t.length-1].position??0}getCounter(){let t=this._matcher.path;return t.length===0?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,r=!0){return this._matcher.toString(t,r)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}},Cm=class{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new eG(this),this._keptAttrs=[]}push(t,r=null,n=null,i=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);let s=this.path.length,o=this.siblingStacks[s];o||(o={counts:new Map,total:0},this.siblingStacks[s]=o);let a=n?`${n}:${t}`:t,A=o.counts.get(a)||0,u=o.total;o.counts.set(a,A+1),o.total++;let c={tag:t,position:u,counter:A};n!=null&&(c.namespace=n),r!=null&&(c.values=r),this.path.push(c);let l=this.path.length,h=i!==null?i.keep:null;if(h!=null&&h.length>0&&r)for(let d=0;d<h.length;d++){let f=h[d];r[f]!==void 0&&this._keptAttrs.push({depth:l,name:f,value:r[f]})}}pop(){if(this.path.length===0)return;this._pathStringCache=null;let t=this.path.pop();this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1);let r=this.path.length+1;for(;this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=r;)this._keptAttrs.pop();return t}updateCurrent(t){if(this.path.length>0){let r=this.path[this.path.length-1];t!=null&&(r.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(this.path.length!==0)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(this.path.length===0)return!1;let r=this.path[this.path.length-1];return r.values!==void 0&&t in r.values}getAnyParentAttr(t){let r=this._keptAttrs;for(let n=r.length-1;n>=0;n--)if(r[n].name===t)return r[n].value}hasAnyParentAttr(t){let r=this._keptAttrs;for(let n=r.length-1;n>=0;n--)if(r[n].name===t)return!0;return!1}getPosition(){return this.path.length===0?-1:this.path[this.path.length-1].position??0}getCounter(){return this.path.length===0?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,r=!0){let n=t||this.separator;if(n===this.separator&&r===!0){if(this._pathStringCache!==null)return this._pathStringCache;let s=this.path.map(o=>o.namespace?`${o.namespace}:${o.tag}`:o.tag).join(n);return this._pathStringCache=s,s}return this.path.map(s=>r&&s.namespace?`${s.namespace}:${s.tag}`:s.tag).join(n)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[],this._keptAttrs=[]}matches(t){let r=t.segments;return r.length===0?!1:t.hasDeepWildcard()?this._matchWithDeepWildcard(r):this._matchSimple(r)}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let r=0;r<t.length;r++)if(!this._matchSegment(t[r],this.path[r],r===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(t){let r=this.path.length-1,n=t.length-1;for(;n>=0&&r>=0;){let i=t[n];if(i.type==="deep-wildcard"){if(n--,n<0)return!0;let s=t[n],o=!1;for(let a=r;a>=0;a--)if(this._matchSegment(s,this.path[a],a===this.path.length-1)){r=a-1,n--,o=!0;break}if(!o)return!1}else{if(!this._matchSegment(i,this.path[r],r===this.path.length-1))return!1;r--,n--}}return n<0}_matchSegment(t,r,n){if(t.tag!=="*"&&t.tag!==r.tag||t.namespace!==void 0&&t.namespace!=="*"&&t.namespace!==r.namespace||t.attrName!==void 0&&(!n||!r.values||!(t.attrName in r.values)||t.attrValue!==void 0&&String(r.values[t.attrName])!==String(t.attrValue)))return!1;if(t.position!==void 0){if(!n)return!1;let i=r.counter??0;if(t.position==="first"&&i!==0)return!1;if(t.position==="odd"&&i%2!==1)return!1;if(t.position==="even"&&i%2!==0)return!1;if(t.position==="nth"&&i!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>t&&{counts:new Map(t.counts),total:t.total}),keptAttrs:this._keptAttrs.map(t=>({...t}))}}restore(t){this._pathStringCache=null,this.path=t.path.map(r=>({...r})),this.siblingStacks=t.siblingStacks.map(r=>r&&{counts:new Map(r.counts),total:r.total}),this._keptAttrs=(t.keptAttrs||[]).map(r=>({...r}))}readOnly(){return this._view}};var Lft=[{id:"html-script-open",description:"<script opening tag",pattern:/<script[\s>/]/i},{id:"html-script-close",description:"</script closing tag",pattern:/<\/script[\s>]/i},{id:"html-javascript-protocol",description:"javascript: URI scheme (with optional whitespace/encoding)",pattern:/j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i},{id:"html-vbscript-protocol",description:"vbscript: URI scheme",pattern:/vbscript[\t\n\r ]*:/i},{id:"html-data-html",description:"data:text/html URI \u2014 can execute scripts in browsers",pattern:/data[\t\n\r ]*:[\t\n\r ]*text\/html/i},{id:"html-data-xhtml",description:"data:application/xhtml+xml URI",pattern:/data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i},{id:"html-data-svg",description:"data:image/svg+xml URI \u2014 can execute scripts",pattern:/data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i},{id:"html-inline-event-handler",description:"Inline event handler attributes: onclick=, onerror=, onload=, etc.",pattern:/\bon\w{1,30}\s*=/i},{id:"html-entity-obfuscated-script",description:"HTML-entity-encoded <script (e.g. <script or <script)",pattern:/(?:�*3[Cc];?|�*60;?|<)\s*script/i},{id:"html-entity-obfuscated-javascript",description:'HTML-entity-encoded javascript: (partial \u2014 catches common j or j for "j")',pattern:/(?:�*6[Aa];?|�*106;?)\s*(?:�*61;?|a)[\s\S]{0,80}script\s*:/i},{id:"html-style-expression",description:"CSS expression() \u2014 IE-era code execution in style attributes",pattern:/style[\s\S]{0,20}expression\s*\(/i},{id:"html-object-embed",description:"<object or <embed tags that can load active content",pattern:/<(?:object|embed)[\s>/]/i},{id:"html-base-tag",description:"<base href= \u2014 can hijack all relative URLs on a page",pattern:/<base[\s>]/i},{id:"html-meta-refresh",description:'<meta http-equiv="refresh" \u2014 can redirect users',pattern:/<meta[\s\S]{0,40}http-equiv[\s\S]{0,20}refresh/i},{id:"html-srcdoc",description:"srcdoc= attribute on iframes \u2014 embeds HTML that can run scripts",pattern:/srcdoc\s*=/i},{id:"html-iframe",description:"<iframe tag",pattern:/<iframe[\s>/]/i},{id:"html-form",description:"<form tag \u2014 can be used for phishing / credential harvesting injection",pattern:/<form[\s>/]/i}],Bm=Lft;var Mft=[{id:"xml-cdata-injection",description:"CDATA section injection: <![CDATA[ breaks out of text node context",pattern:/<!\[CDATA\[/i},{id:"xml-cdata-close",description:"CDATA close sequence: ]]> can terminate an enclosing CDATA section",pattern:/\]\]>/},{id:"xml-processing-instruction",description:"XML processing instruction: <?xml-stylesheet or <?php etc.",pattern:/<\?(?:xml[\- ]|php|asp)/i},{id:"xml-doctype-injection",description:"DOCTYPE declaration embedded in content \u2014 can define entities",pattern:/<!DOCTYPE(?:[\s[]|$)/i},{id:"xml-entity-system",description:"SYSTEM keyword \u2014 used in external entity declarations (XXE)",pattern:/\bSYSTEM\s+["']/i},{id:"xml-entity-public",description:"PUBLIC keyword \u2014 used in external entity declarations (XXE)",pattern:/\bPUBLIC\s+["']/i},{id:"xml-entity-declaration",description:"<!ENTITY declaration \u2014 defines entities, potential XXE or entity expansion",pattern:/<!ENTITY[\s%]/i},{id:"xml-billion-laughs",description:"Entity reference chaining / billion laughs: repeated &eX; style references",pattern:/(?:&\w{1,20};){3,}/},{id:"xml-namespace-confusion",description:"xmlns: attribute injection \u2014 can redefine namespaces to confuse parsers",pattern:/\bxmlns(?::\w{1,40})?\s*=/i},{id:"xml-comment-injection",description:"<!-- comment injection \u2014 can hide content from some parsers",pattern:/<!--/},{id:"xml-comment-close",description:"--> closes an enclosing XML comment",pattern:/-->/},{id:"xml-pi-close",description:"?> closes an enclosing processing instruction",pattern:/\?>/}],ym=Mft;var Fft=[{id:"svg-script-element",description:"<script element inside SVG executes JavaScript",pattern:/<script[\s>/]/i},{id:"svg-xlink-href-javascript",description:"xlink:href with javascript: \u2014 classic SVG XSS via <a> or <use>",pattern:/xlink\s*:\s*href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-href-javascript",description:"href= with javascript: in SVG context (<a>, <animate>, etc.)",pattern:/href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-foreignobject",description:"<foreignObject embeds HTML inside SVG \u2014 can execute scripts",pattern:/<foreignObject[\s>/]/i},{id:"svg-use-external",description:"<use xlink:href or href pointing to external resource (non-fragment URL)",pattern:/<use[\s\S]{0,60}(?:xlink\s*:\s*)?href\s*=\s*(?:["'][^#]|[^"'#\s>])/i},{id:"svg-animate-href",description:'<animate attributeName="href" \u2014 can dynamically change href to javascript:',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*href["']/i},{id:"svg-animate-xlinkhref",description:'<animate attributeName="xlink:href"',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*xlink\s*:\s*href["']/i},{id:"svg-set-javascript",description:'<set to="javascript:..." \u2014 sets an attribute to a javascript: URI',pattern:/<set[\s\S]{0,80}to\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-event-handler",description:"SVG-specific event handler attributes: onload=, onerror=, onactivate=, etc.",pattern:/\bon(?:load|error|activate|begin|end|repeat|focus|blur|click|mouse\w{1,20}|key\w{1,20})\s*=/i},{id:"svg-handler-generic",description:"Generic on* handler catch-all for SVG attributes",pattern:/\bon\w{1,30}\s*=/i},{id:"svg-filter-feimage",description:"<feImage href= \u2014 filter primitive that can load external resources",pattern:/<feImage[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=/i},{id:"svg-image-external",description:"<image xlink:href with http/https or javascript protocol",pattern:/<image[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=\s*["']?\s*(?:https?|javascript)\s*:/i},{id:"svg-style-javascript",description:"style= attribute containing javascript: (e.g. background:url(javascript:...))",pattern:/style\s*=[\s\S]{0,60}javascript\s*:/i}],tG=Fft;var Uft=[{id:"sql-block-comment-open",description:"SQL block comment open: /* ... */ \u2014 unusual in legitimate user text",pattern:/\/\*/},{id:"sql-union-select",description:"UNION SELECT \u2014 most common SQL injection aggregation attack",pattern:/\bUNION\s{1,20}(?:ALL\s{1,20})?SELECT\b/i},{id:"sql-drop-table",description:"DROP TABLE \u2014 destructive DDL injection",pattern:/\bDROP\s{1,20}TABLE\b/i},{id:"sql-drop-database",description:"DROP DATABASE \u2014 destructive DDL injection",pattern:/\bDROP\s{1,20}DATABASE\b/i},{id:"sql-insert-into",description:"INSERT INTO \u2014 data injection",pattern:/\bINSERT\s{1,20}INTO\b/i},{id:"sql-delete-from",description:"DELETE FROM \u2014 data deletion injection",pattern:/\bDELETE\s{1,20}FROM\b/i},{id:"sql-update-set",description:"UPDATE ... SET \u2014 data modification injection",pattern:/\bUPDATE\b[\s\S]{1,60}\bSET\b/i},{id:"sql-exec-xp",description:"EXEC xp_ \u2014 MSSQL extended stored procedure execution",pattern:/\bEXEC(?:UTE)?\s{1,20}xp_/i},{id:"sql-tautology-string",description:`Classic string tautology: ' OR '1'='1 or " OR "1"="1"`,pattern:/'\s{0,10}OR\s{0,10}'[^']{0,20}'\s*=\s*'[^']{0,20}/i},{id:"sql-tautology-numeric",description:"Numeric tautology: OR 1=1",pattern:/\bOR\s{1,10}1\s*=\s*1\b/i},{id:"sql-always-true-zero",description:"Numeric tautology: OR 0=0",pattern:/\bOR\s{1,10}0\s*=\s*0\b/i},{id:"sql-sleep-benchmark",description:"Time-based blind injection: SLEEP() or BENCHMARK()",pattern:/\b(?:SLEEP|BENCHMARK)\s*\(/i},{id:"sql-waitfor-delay",description:"MSSQL time-based blind injection: WAITFOR DELAY",pattern:/\bWAITFOR\s{1,20}DELAY\b/i},{id:"sql-char-function",description:"CHAR() function \u2014 used to obfuscate injected strings",pattern:/\bCHAR\s*\(\s*\d{1,3}/i},{id:"sql-information-schema",description:"INFORMATION_SCHEMA \u2014 reconnaissance query for table/column enumeration",pattern:/\bINFORMATION_SCHEMA\b/i}],cb=Uft;var _ft=[{id:"shell-path-traversal-unix",description:"Unix path traversal: ../ \u2014 climbing the directory tree",pattern:/\.\.\//},{id:"shell-path-traversal-windows",description:"Windows path traversal: ..\\ \u2014 climbing the directory tree",pattern:/\.\.\\/},{id:"shell-path-traversal-encoded",description:"URL-encoded path traversal: %2e%2e or %2f variants",pattern:/%2e%2e|%2f\.\.|\.\.%2f/i},{id:"shell-null-byte",description:"Null byte injection: \\x00 or %00 \u2014 truncates strings in C-backed functions",pattern:/\x00|%00/},{id:"shell-semicolon",description:"Semicolon command separator: cmd1; cmd2",pattern:/;/},{id:"shell-pipe",description:"Pipe operator: cmd1 | cmd2",pattern:/\|/},{id:"shell-and-operator",description:"AND operator: cmd1 && cmd2",pattern:/&&/},{id:"shell-or-operator",description:"OR operator: cmd1 || cmd2",pattern:/\|\|/},{id:"shell-backtick",description:"Backtick command substitution: `cmd`",pattern:/`/},{id:"shell-dollar-paren",description:"Dollar-paren command substitution: $(cmd)",pattern:/\$\(/},{id:"shell-dollar-brace",description:"Dollar-brace variable expansion: ${var} \u2014 can be abused for injection",pattern:/\$\{/},{id:"shell-redirect-out",description:"Output redirection: cmd > file or cmd >> file",pattern:/>{1,2}/},{id:"shell-redirect-in",description:"Input redirection: cmd < file",pattern:/</},{id:"shell-newline-injection",description:"Newline injection: \\n or \\r \u2014 can inject new shell commands",pattern:/[\n\r]/},{id:"shell-glob-star",description:"Glob expansion: * or ? \u2014 can expand to unintended files",pattern:/[/\\][*?]/},{id:"shell-absolute-root",description:"Absolute root path injection: string starting with / or \\ (Windows UNC)",pattern:/^(?:\/|\\\\)/},{id:"shell-windows-drive",description:"Windows drive letter path injection: C:\\ or D:/",pattern:/^[a-zA-Z]:[/\\]/},{id:"shell-curl-wget",description:"curl/wget with URL or flags \u2014 can exfiltrate data or download payloads",pattern:/\b(?:curl|wget)\s+(?:https?:\/\/|ftp:\/\/|-)/i}],rG=_ft;var Oft=[{id:"redos-nested-quantifier-plus",description:"Nested + quantifier inside a group with outer quantifier: (a+)+, (.+b)*, etc.",pattern:/\([^)]*\+[^)]*\)[+*]/},{id:"redos-nested-quantifier-star",description:"Nested * quantifier: (a*)* or (a*)+ \u2014 catastrophic backtracking",pattern:/\([^)]*\*[^)]*\)[*+]/},{id:"redos-nested-groups",description:"Doubly nested quantified groups: ((a+)+) \u2014 guaranteed catastrophic",pattern:/\(\([^)]{0,40}\)[+*]\)[+*]/},{id:"redos-alternation-overlap",description:"Overlapping alternation under quantifier: (a|a)+ \u2014 ambiguous NFA paths",pattern:/\(([^|()]{1,20})\|(?:\1)(?:\|[^|()]{1,20}){0,5}\)[+*?]{1,2}/},{id:"redos-star-plus-concat",description:"(x*x)+ pattern \u2014 triggers super-linear backtracking",pattern:/\([^)]{0,10}\*[^)]{0,10}\)[+*]/},{id:"redos-dot-star-greedy",description:"(.*){n,} or (.+){n,} \u2014 repeated greedy dot quantifiers",pattern:/\(\.[*+]\)\{?\d/},{id:"redos-large-repetition",description:"Very large fixed or range repetition count {1000,} or {1000,n} \u2014 denial of service via backtracking",pattern:/\{\d{4,}(?:,\d*)?\}/},{id:"redos-catastrophic-alternation",description:"Long alternation with many similar branches \u2014 polynomial backtracking risk",pattern:/\([^)]{0,200}(?:\|[^|)]{0,50}){9,}\)/}],nG=Oft;var Po=`["'\\s]*:`,Pft=[{id:"nosql-where-operator",description:"$where \u2014 executes arbitrary JavaScript server-side in MongoDB",pattern:new RegExp(`\\$where${Po}`,"i")},{id:"nosql-ne-operator",description:'$ne \u2014 "not equal" operator used to bypass equality checks',pattern:new RegExp(`\\$ne${Po}`,"i")},{id:"nosql-gt-operator",description:'$gt \u2014 "greater than" used to bypass password/value checks',pattern:new RegExp(`\\$gte?${Po}`,"i")},{id:"nosql-lt-operator",description:'$lt / $lte \u2014 "less than" bypass variants',pattern:new RegExp(`\\$lte?${Po}`,"i")},{id:"nosql-regex-operator",description:"$regex \u2014 can be used to extract data character by character (blind injection)",pattern:new RegExp(`\\$regex${Po}`,"i")},{id:"nosql-or-operator",description:"$or \u2014 logical OR; used to create always-true conditions",pattern:new RegExp(`\\$or${Po}\\s*\\[`,"i")},{id:"nosql-and-operator",description:"$and \u2014 logical AND operator injection",pattern:new RegExp(`\\$and${Po}\\s*\\[`,"i")},{id:"nosql-nor-operator",description:"$nor \u2014 logical NOR operator injection",pattern:new RegExp(`\\$nor${Po}\\s*\\[`,"i")},{id:"nosql-exists-operator",description:"$exists \u2014 can enumerate fields to determine schema",pattern:new RegExp(`\\$exists${Po}`,"i")},{id:"nosql-in-operator",description:"$in \u2014 matches any value in a list; can enumerate values",pattern:new RegExp(`\\$in${Po}\\s*\\[`,"i")},{id:"nosql-expr-operator",description:"$expr \u2014 allows aggregation expressions in queries (MongoDB 3.6+)",pattern:new RegExp(`\\$expr${Po}`,"i")},{id:"nosql-function-operator",description:"$function \u2014 executes arbitrary JavaScript in MongoDB 4.4+",pattern:new RegExp(`\\$function${Po}`,"i")},{id:"nosql-accumulator-operator",description:"$accumulator \u2014 custom aggregation with arbitrary JS execution",pattern:new RegExp(`\\$accumulator${Po}`,"i")},{id:"nosql-proto-pollution",description:"__proto__ \u2014 prototype pollution via object key injection",pattern:/__proto__/},{id:"nosql-constructor-prototype",description:"constructor.prototype \u2014 alternative prototype pollution vector (dot notation or JSON key)",pattern:/constructor[\s"':.,{\[]*prototype/i},{id:"nosql-proto-bracket",description:'["__proto__"] \u2014 bracket-notation prototype pollution',pattern:/\[["']__proto__["']\]/}],iG=Pft;var Hft=[{id:"log-crlf-injection",description:"CRLF injection: literal \\r or \\n embeds fake log lines",pattern:/[\r\n]/},{id:"log-url-encoded-crlf",description:"URL-encoded CRLF: %0d, %0a, %0D, %0A \u2014 decoded by some log parsers",pattern:/%0[dDaA]/},{id:"log-unicode-newline",description:"Unicode newline variants: U+2028 (line separator), U+2029 (paragraph separator)",pattern:/[\u2028\u2029]/},{id:"log-log4shell-jndi",description:"Log4Shell: ${jndi:...} triggers remote code execution in Apache Log4j",pattern:/\$\{jndi\s*:/i},{id:"log-log4shell-obfuscated",description:"Obfuscated Log4Shell: ${::-j}... lookup-bypass prefix used to evade WAF detection",pattern:/\$\{::-/},{id:"log-log4j-lookup",description:"Log4j lookup syntax: ${env:...}, ${sys:...}, ${ctx:...} \u2014 data exfiltration",pattern:/\$\{(?:env|sys|ctx|main|map|sd|web|docker|k8s|spring)\s*:/i},{id:"log-ssti-double-brace",description:"SSTI double-brace: {{expression}} \u2014 Jinja2, Twig, Handlebars, etc.",pattern:/\{\{[\s\S]{0,80}\}\}/},{id:"log-ssti-hash-brace",description:"SSTI hash-brace: #{expression} \u2014 Thymeleaf, Velocity, Ruby ERB",pattern:/#\{[\s\S]{0,80}\}/},{id:"log-ssti-dollar-brace",description:"SSTI/EL injection: ${expression with operators or method calls} \u2014 JSP EL, Freemarker, SpEL",pattern:/\$\{[^}]*(?:\.|\(|\*|\+|\bclass\b|\bruntime\b|\bprocess\b|\bexec\b)[^}]{0,80}\}/i},{id:"log-ssti-percent-tag",description:"SSTI ERB/ASP tag: <%= expression %> \u2014 Ruby ERB, ASP",pattern:/<%=[\s\S]{0,80}%>/},{id:"log-null-byte",description:"Null byte: \\x00 or %00 \u2014 can truncate log entries in C-backed loggers",pattern:/\x00|%00/},{id:"log-ansi-escape",description:"ANSI escape sequence: ESC[ \u2014 can manipulate terminal output when logs are tailed",pattern:/\x1b\[/}],sG=Hft;var Gft=[{id:"sql-line-comment",description:"SQL line comment: -- followed by whitespace or end of string",pattern:/--(?:\s|$)/},{id:"sql-stacked-query",description:"Stacked queries: semicolon immediately followed by a SQL keyword",pattern:/;\s{0,10}(?:SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\b/i},{id:"sql-hex-encoding",description:"Hex-encoded string injection: 0x41414141 style (MySQL)",pattern:/\b0x[0-9a-f]{4,}/i}],Yft=[...cb,...Gft],oG=Yft;Bm.label="HTML";ym.label="XML";tG.label="SVG";cb.label="SQL";oG.label="SQL-STRICT";rG.label="SHELL";nG.label="REDOS";iG.label="NOSQL";sG.label="LOG";var q3t=Object.freeze({HTML:Bm,XML:ym,SVG:tG,SQL:cb,"SQL-STRICT":oG,SHELL:rG,REDOS:nG,NOSQL:iG,LOG:sG});function Vft(e){if(typeof e!="string")throw new TypeError(`is-unsafe: first argument must be a string, got ${typeof e}`)}function Wft(e){if(!(e instanceof RegExp)){if(Array.isArray(e)){if(e.length===0)throw new TypeError("is-unsafe: context must not be an empty array");if(Array.isArray(e[0])){for(let t of e)if(!Array.isArray(t)||t.length===0)throw new TypeError("is-unsafe: each context in the array must be a non-empty pattern array (PatternList)")}return}throw new TypeError(`is-unsafe: second argument must be a PatternList (e.g. HTML), an array of PatternLists (e.g. [HTML, XML]), or a RegExp. Got: ${typeof e}`)}}function qft(e){return e instanceof RegExp?{lists:null,regex:e}:Array.isArray(e[0])?{lists:e,regex:null}:{lists:[e],regex:null}}function Jft(e,t){let r=t.label??"CUSTOM";for(let n of t)if(n.pattern.test(e))return{context:r,id:n.id,description:n.description,pattern:n.pattern};return null}function GBe(e,t){Vft(e),Wft(t);let{lists:r,regex:n}=qft(t);if(n)return n.test(e);for(let i of r)if(Jft(e,i)!==null)return!0;return!1}function jft(e,t){if(!e)return{};let r=t.attributesGroupName?e[t.attributesGroupName]:e;if(!r)return{};let n={};for(let i in r)if(i.startsWith(t.attributeNamePrefix)){let s=i.substring(t.attributeNamePrefix.length);n[s]=r[i]}else n[i]=r[i];return n}function $ft(e){if(!e||typeof e!="string")return;let t=e.indexOf(":");if(t!==-1&&t>0){let r=e.substring(0,t);if(r!=="xmlns")return r}}var lb=class{constructor(t,r){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=egt,this.parseTextData=Kft,this.resolveNameSpace=Xft,this.buildAttributesMap=Zft,this.isItStopNode=igt,this.replaceEntitiesValue=rgt,this.readStopNodeData=agt,this.saveTextToParentTag=ngt,this.addChild=tgt,this.ignoreAttributesFn=Z5(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.doctypefound=!1;let n={...ob};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:(typeof this.options.htmlEntities=="object"?n=this.options.htmlEntities:this.options.htmlEntities===!0&&(n={...J5,...q5}),this.entityDecoder=new Em({namedEntities:{...n,...r},numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo},onInputEntity:(s,o)=>GBe(o,[Bm,ym])?pm.BLOCK:pm.ALLOW})),this.matcher=new Cm,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new Im;let i=this.options.stopNodes;if(i&&i.length>0){for(let s=0;s<i.length;s++){let o=i[s];typeof o=="string"?this.stopNodeExpressionsSet.add(new Dg(o)):o instanceof Dg&&this.stopNodeExpressionsSet.add(o)}this.stopNodeExpressionsSet.seal()}}};function Kft(e,t,r,n,i,s,o){let a=this.options;if(e!==void 0&&(a.trimValues&&!n&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e,t,r));let A=a.jPath?r.toString():r,u=a.tagValueProcessor(t,e,A,i,s);return u==null?e:typeof u!=typeof e||u!==e?u:a.trimValues||e.trim()===e?uG(e,a.parseTagValue,a.numberParseOptions):e}}function Xft(e){if(this.options.removeNSPrefix){let t=e.split(":"),r=e.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return"";t.length===2&&(e=r+t[1])}return e}var zft=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Zft(e,t,r,n=!1){let i=this.options;if(n===!0||i.ignoreAttributes!==!0&&typeof e=="string"){let s=bBe(e,zft),o=s.length,a={},A=new Array(o),u=!1,c={};for(let d=0;d<o;d++){let f=this.resolveNameSpace(s[d][1]),g=s[d][4];if(f.length&&g!==void 0){let p=g;i.trimValues&&(p=p.trim()),p=this.replaceEntitiesValue(p,r,this.readonlyMatcher),A[d]=p,c[f]=p,u=!0}}u&&typeof t=="object"&&t.updateCurrent&&t.updateCurrent(c);let l=i.jPath?t.toString():this.readonlyMatcher,h=!1;for(let d=0;d<o;d++){let f=this.resolveNameSpace(s[d][1]);if(this.ignoreAttributesFn(f,l))continue;let g=i.attributeNamePrefix+f;if(f.length)if(i.transformAttributeName&&(g=i.transformAttributeName(g)),g=YBe(g,i),s[d][4]!==void 0){let p=A[d],m=i.attributeValueProcessor(f,p,l);m==null?a[g]=p:typeof m!=typeof p||m!==p?a[g]=m:a[g]=uG(p,i.parseAttributeValue,i.numberParseOptions),h=!0}else i.allowBooleanAttributes&&(a[g]=!0,h=!0)}if(!h)return;if(i.attributesGroupName&&!i.preserveOrder){let d={};return d[i.attributesGroupName]=a,d}return a}}var egt=function(e){e=e.replace(/\r\n?/g,`
|
|
472
472
|
`);let t=new Ks("!xml"),r=t,n="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0,this.doctypefound=!1;let i=this.options,s=new ub(i.processEntities),o=e.length;for(let a=0;a<o;a++)if(e[a]==="<"){let u=e.charCodeAt(a+1);if(u===47){let c=bm(e,">",a,"Closing Tag is not closed."),l=e.substring(a+2,c).trim();if(i.removeNSPrefix){let d=l.indexOf(":");d!==-1&&(l=l.substr(d+1))}l=aG(i.transformTagName,l,"",i).tagName,r&&(n=this.saveTextToParentTag(n,r,this.readonlyMatcher));let h=this.matcher.getCurrentTag();if(l&&i.unpairedTagsSet.has(l))throw new Error(`Unpaired tag can not be used as closing tag: </${l}>`);h&&i.unpairedTagsSet.has(h)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,r=this.tagsNodeStack.pop()||t,i.captureMetaData&&r&&r.addEndIndex(c+1),n="",a=c}else if(u===63){let c=AG(e,a,!1,"?>");if(!c)throw new Error("Pi Tag is not closed.");n=this.saveTextToParentTag(n,r,this.readonlyMatcher);let l=this.buildAttributesMap(c.tagExp,this.matcher,c.tagName,!0);if(l){let h=l[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(h)||1),s.setXmlVersion(Number(h)||1)}if(!(i.ignoreDeclaration&&c.tagName==="?xml"||i.ignorePiTags)){let h=new Ks(c.tagName);h.add(i.textNodeName,""),c.tagName!==c.tagExp&&c.attrExpPresent&&i.ignoreAttributes!==!0&&(h[":@"]=l),this.addChild(r,h,this.readonlyMatcher,a),i.captureMetaData&&r.addEndIndex(c.closeIndex+2)}a=c.closeIndex+1}else if(u===33&&e.charCodeAt(a+2)===45&&e.charCodeAt(a+3)===45){let c=bm(e,"-->",a+4,"Comment is not closed.");if(i.commentPropName){let l=e.substring(a+4,c-2);n=this.saveTextToParentTag(n,r,this.readonlyMatcher),r.add(i.commentPropName,[{[i.textNodeName]:l}])}a=c}else if(u===33&&e.charCodeAt(a+2)===68){if(this.doctypefound)throw new Error("Multiple DOCTYPE declarations found.");this.doctypefound=!0;let c=s.readDocType(e,a);this.entityDecoder.addInputEntities(c.entities),a=c.i}else if(u===33&&e.charCodeAt(a+2)===91){let c=bm(e,"]]>",a,"CDATA is not closed.")-2,l=e.substring(a+9,c);n=this.saveTextToParentTag(n,r,this.readonlyMatcher);let h=this.parseTextData(l,r.tagname,this.readonlyMatcher,!0,!1,!0,!0);h==null&&(h=""),i.cdataPropName?r.add(i.cdataPropName,[{[i.textNodeName]:l}]):r.add(i.textNodeName,h),a=c+2}else{let c=AG(e,a,i.removeNSPrefix);if(!c){let D=e.substring(Math.max(0,a-50),Math.min(o,a+50));throw new Error(`readTagExp returned undefined at position ${a}. Context: "${D}"`)}let l=c.tagName,h=c.rawTagName,d=c.tagExp,f=c.attrExpPresent,g=c.closeIndex;if({tagName:l,tagExp:d}=aG(i.transformTagName,l,d,i),i.strictReservedNames&&(l===i.commentPropName||l===i.cdataPropName||l===i.textNodeName||l===i.attributesGroupName))throw new Error(`Invalid tag name: ${l}`);r&&n&&r.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,r,this.readonlyMatcher,!1));let p=r;p&&i.unpairedTagsSet.has(p.tagname)&&(r=this.tagsNodeStack.pop(),this.matcher.pop());let m=!1;d.length>0&&d.lastIndexOf("/")===d.length-1&&(m=!0,l[l.length-1]==="/"?(l=l.substr(0,l.length-1),d=l):d=d.substr(0,d.length-1),f=l!==d);let I=null,C={},y;y=$ft(h),l!==t.tagname&&this.matcher.push(l,{},y),l!==d&&f&&(I=this.buildAttributesMap(d,this.matcher,l),I&&(C=jft(I,i))),l!==t.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());let Q=a;if(this.isCurrentNodeStopNode){let D="";if(m)a=c.closeIndex;else if(i.unpairedTagsSet.has(l))a=c.closeIndex;else{let S=this.readStopNodeData(e,h,g+1);if(!S)throw new Error(`Unexpected end of ${h}`);a=S.i,D=S.tagContent}let N=new Ks(l);I&&(N[":@"]=I),N.add(i.textNodeName,D),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(r,N,this.readonlyMatcher,Q),i.captureMetaData&&r.addEndIndex(a+1)}else{if(m){({tagName:l,tagExp:d}=aG(i.transformTagName,l,d,i));let D=new Ks(l);I&&(D[":@"]=I),this.addChild(r,D,this.readonlyMatcher,Q),i.captureMetaData&&r.addEndIndex(g+1),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(i.unpairedTagsSet.has(l)){let D=new Ks(l);I&&(D[":@"]=I),this.addChild(r,D,this.readonlyMatcher,Q),i.captureMetaData&&r.addEndIndex(c.closeIndex+1),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=c.closeIndex;continue}else{let D=new Ks(l);if(this.tagsNodeStack.length>i.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(r),I&&(D[":@"]=I),this.addChild(r,D,this.readonlyMatcher,Q),r=D}n="",a=g}}}else n+=e[a];return t.child};function tgt(e,t,r,n){this.options.captureMetaData||(n=void 0);let i=this.options.jPath?r.toString():r,s=this.options.updateTag(t.tagname,i,t[":@"]);s===!1||(typeof s=="string"&&(t.tagname=s),e.addChild(t,n))}function rgt(e,t,r){let n=this.options.processEntities;if(!n||!n.enabled)return e;if(n.allowedTags){let i=this.options.jPath?r.toString():r;if(!(Array.isArray(n.allowedTags)?n.allowedTags.includes(t):n.allowedTags(t,i)))return e}if(n.tagFilter){let i=this.options.jPath?r.toString():r;if(!n.tagFilter(t,i))return e}return this.entityDecoder.decode(e)}function ngt(e,t,r,n){return e&&(n===void 0&&(n=t.child.length===0),e=this.parseTextData(e,t.tagname,r,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,n),e!==void 0&&e!==""&&t.add(this.options.textNodeName,e),e=""),e}function igt(){return this.stopNodeExpressionsSet.size===0?!1:this.matcher.matchesAny(this.stopNodeExpressionsSet)}function sgt(e,t,r=">"){let n=0,i=e.length,s=r.charCodeAt(0),o=r.length>1?r.charCodeAt(1):-1,a="",A=t;for(let u=t;u<i;u++){let c=e.charCodeAt(u);if(n)c===n&&(n=0);else if(c===34||c===39)n=c;else if(c===s)if(o!==-1){if(e.charCodeAt(u+1)===o)return a+=e.substring(A,u),{data:a,index:u}}else return a+=e.substring(A,u),{data:a,index:u};else c===9&&!n&&(a+=e.substring(A,u)+" ",A=u+1)}}function bm(e,t,r,n){let i=e.indexOf(t,r);if(i===-1)throw new Error(n);return i+t.length-1}function ogt(e,t,r,n){let i=e.indexOf(t,r);if(i===-1)throw new Error(n);return i}function AG(e,t,r,n=">"){let i=sgt(e,t+1,n);if(!i)return;let s=i.data,o=i.index,a=s.search(/\s/),A=s,u=!0;a!==-1&&(A=s.substring(0,a),s=s.substring(a+1).trimStart());let c=A;if(r){let l=A.indexOf(":");l!==-1&&(A=A.substr(l+1),u=A!==i.data.substr(l+1))}return{tagName:A,tagExp:s,closeIndex:o,attrExpPresent:u,rawTagName:c}}function agt(e,t,r){let n=r,i=1,s=e.length;for(;r<s;r++)if(e[r]==="<"){let o=e.charCodeAt(r+1);if(o===47){let a=ogt(e,">",r,`${t} is not closed`);if(e.substring(r+2,a).trim()===t&&(i--,i===0))return{tagContent:e.substring(n,r),i:a};r=a}else if(o===63)r=bm(e,"?>",r+1,"StopNode is not closed.");else if(o===33&&e.charCodeAt(r+2)===45&&e.charCodeAt(r+3)===45)r=bm(e,"-->",r+3,"StopNode is not closed.");else if(o===33&&e.charCodeAt(r+2)===91)r=bm(e,"]]>",r,"StopNode is not closed.")-2;else{let a=AG(e,r,!1);a&&((a&&a.tagName)===t&&a.tagExp[a.tagExp.length-1]!=="/"&&i++,r=a.closeIndex)}}}function uG(e,t,r){if(t&&typeof e=="string"){let n=e.trim();return n==="true"?!0:n==="false"?!1:z5(e,r)}else return QBe(e)?e:""}function aG(e,t,r,n){if(e){let i=e(t);r===t&&(r=i),t=i}return t=YBe(t,n),{tagName:t,tagExp:r}}function YBe(e,t){if(Rx.includes(e))throw new Error(`[SECURITY] Invalid name: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);return ib.includes(e)?t.onDangerousProperty(e):e}var cG=Ks.getMetaDataSymbol();function Agt(e,t){if(!e||typeof e!="object")return{};if(!t)return e;let r={};for(let n in e)if(n.startsWith(t)){let i=n.substring(t.length);r[i]=e[n]}else r[n]=e[n];return r}function lG(e,t,r,n){return VBe(e,t,r,n)}function VBe(e,t,r,n){let i,s={};for(let o=0;o<e.length;o++){let a=e[o],A=ugt(a);if(A!==void 0&&A!==t.textNodeName){let u=Agt(a[":@"]||{},t.attributeNamePrefix);r.push(A,u)}if(A===t.textNodeName)i===void 0?i=a[A]:i+=""+a[A];else{if(A===void 0)continue;if(a[A]){let u=VBe(a[A],t,r,n),c=lgt(u,t);if(Object.keys(u).length===0&&t.alwaysCreateTextNode&&(u[t.textNodeName]=""),a[":@"]?cgt(u,a[":@"],n,t):Object.keys(u).length===1&&u[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?u=u[t.textNodeName]:Object.keys(u).length===0&&(t.alwaysCreateTextNode?u[t.textNodeName]="":u=""),a[cG]!==void 0&&typeof u=="object"&&u!==null&&(u[cG]=a[cG]),s[A]!==void 0&&Object.prototype.hasOwnProperty.call(s,A))Array.isArray(s[A])||(s[A]=[s[A]]),s[A].push(u);else{let l=t.jPath?n.toString():n;t.isArray(A,l,c)?s[A]=[u]:s[A]=u}A!==void 0&&A!==t.textNodeName&&r.pop()}}}return typeof i=="string"?i.length>0&&(s[t.textNodeName]=i):i!==void 0&&(s[t.textNodeName]=i),s}function ugt(e){let t=Object.keys(e);for(let r=0;r<t.length;r++){let n=t[r];if(n!==":@")return n}}function cgt(e,t,r,n){if(t){let i=Object.keys(t),s=i.length;for(let o=0;o<s;o++){let a=i[o],A=a.startsWith(n.attributeNamePrefix)?a.substring(n.attributeNamePrefix.length):a,u=n.jPath?r.toString()+"."+A:r;n.isArray(a,u,!0,!0)?e[a]=[t[a]]:e[a]=t[a]}}}function lgt(e,t){let{textNodeName:r}=t,n=Object.keys(e).length;return!!(n===0||n===1&&(e[r]||typeof e[r]=="boolean"||e[r]===0))}var Zd=class{constructor(t){this.externalEntities={},this.options=vBe(t)}parse(t,r){if(typeof t!="string"&&t.toString)t=t.toString();else if(typeof t!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(r){r===!0&&(r={});let s=DBe(t,r);if(s!==!0)throw Error(`${s.err.msg}:${s.err.line}:${s.err.col}`)}let n=new lb(this.options,this.externalEntities),i=n.parseXml(t);return this.options.preserveOrder||i===void 0?i:lG(i,this.options,n.matcher,n.readonlyMatcher)}addEntity(t,r){if(r.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(r==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=r}static getMetaDataSymbol(){return Ks.getMetaDataSymbol()}};In();In();function zs(e){if(typeof e!="string"||!e.trim())return{safe:!1,error:"URL required"};let t;try{t=new URL(e.trim())}catch{return{safe:!1,error:"Invalid URL format"}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{safe:!1,error:"Only http and https protocols are supported"};let r=t.hostname.toLowerCase();if(r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="0.0.0.0"||r.endsWith(".localhost")||r.endsWith(".local")||r.endsWith(".internal"))return{safe:!1,error:"Access to loopback/local addresses is forbidden"};let n=r.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(n){let i=Number(n[1]),s=Number(n[2]),o=Number(n[3]),a=Number(n[4]);if([i,s,o,a].some(A=>A<0||A>255))return{safe:!1,error:"Invalid IP address format"};if(i===0||i===10||i===127||i===172&&s>=16&&s<=31||i===192&&s===168||i===169&&s===254)return{safe:!1,error:"Access to private or link-local IP addresses is forbidden"}}if(r.startsWith("[")||r.includes(":")){let i=r.replace(/^\[|\]$/g,"").toLowerCase();if(i==="::1"||i==="::"||i.startsWith("fe80:")||i.startsWith("fc00:")||i.startsWith("fd00:")||i.startsWith("::ffff:127.")||i.startsWith("::ffff:192.168.")||i.startsWith("::ffff:10.")||i.startsWith("::ffff:172.")||i.startsWith("::ffff:169.254."))return{safe:!1,error:"Access to private or link-local IPv6 addresses is forbidden"}}return{safe:!0,url:t}}function WBe(e,t,r){let n=s=>s?.split(",")[0]?.trim(),i=n(r);if(!i)return e;try{let s=new URL(e),o=n(t)||s.protocol.slice(0,-1);return new URL(`${o}://${i}`).origin}catch{return e}}function db(e,t){if(!e)return!0;try{let r=new URL(e);if(Ae.ALLOWED_ORIGINS.includes(r.origin))return!0;if(!t)return!1;let n=new URL(t);if(r.origin===n.origin)return!0;let i=s=>["localhost","127.0.0.1","[::1]"].includes(s);return r.hostname===n.hostname&&!i(r.hostname)?!0:Ae.IS_DEV&&i(r.hostname)&&i(n.hostname)&&r.port===String(Ae.DEV_PORT)}catch{return!1}}In();import hb from"crypto";import Fx from"fs";import dgt from"path";var hG="dango_lan_auth",hgt=720*60*60*1e3;function dG(){return dgt.join(Pn.ROOT,"lan_sessions.json")}function fG(){try{if(!Fx.existsSync(dG()))return{};let e=Fx.readFileSync(dG(),"utf8"),t=JSON.parse(e),r=Date.now(),n=!1;for(let[i,s]of Object.entries(t))(typeof s!="number"||s<r)&&(delete t[i],n=!0);return n&&fb(t),t}catch{return{}}}function fb(e){try{Fx.mkdirSync(Pn.ROOT,{recursive:!0}),Fx.writeFileSync(dG(),JSON.stringify(e))}catch{}}function qBe(){return process.env.APP_PASSWORD_HASH||Pn.APP_PASSWORD_HASH||""}function eh(){return!!qBe()}function gG(e){let t=hb.randomBytes(16).toString("hex"),r=hb.scryptSync(e,t,32).toString("hex");return`scrypt:${t}:${r}`}function JBe(e){return Ux(e,qBe())}function Ux(e,t){if(!t)return!1;let r=t.split(":");if(r.length!==3||r[0]!=="scrypt")return!1;let[,n,i]=r;try{let s=hb.scryptSync(e,n,32),o=Buffer.from(i,"hex");return s.length!==o.length?!1:hb.timingSafeEqual(s,o)}catch{return!1}}async function jBe(e){let{updateEnvFile:t}=await Promise.resolve().then(()=>(bh(),vL));if(!e){await t({APP_PASSWORD_HASH:""}),Pn.APP_PASSWORD_HASH="";return}let r=gG(e);await t({APP_PASSWORD_HASH:r}),Pn.APP_PASSWORD_HASH=r}function $Be(){let e=hb.randomBytes(32).toString("hex"),t=Date.now()+hgt,r=fG();return r[e]=t,fb(r),{token:e,expiry:t}}function gb(e){if(!e)return!1;let t=fG(),r=t[e];return r?r<Date.now()?(delete t[e],fb(t),!1):!0:!1}function KBe(e){if(!e)return;let t=fG();t[e]&&(delete t[e],fb(t))}function XBe(){fb({})}function fgt(e){return e?e.startsWith("::ffff:")?e.slice(7):e:""}function pG(e){let t=fgt(e);return t==="127.0.0.1"||t==="::1"}function Qm(e,t){if(e&&e.toLowerCase().startsWith("bearer "))return e.slice(7).trim()||null;if(t){let r=t.split(";");for(let n of r){let i=n.indexOf("=");if(i===-1)continue;if(n.slice(0,i).trim()===hG)return decodeURIComponent(n.slice(i+1).trim())||null}}return null}var zBe=new Set(["/api/auth/app-status","/api/auth/app-login","/api/auth/app-logout","/api/internal/shutdown"]);function ZBe(e,t){let r=Math.max(1,Math.floor((t-Date.now())/1e3));return`${hG}=${encodeURIComponent(e)}; HttpOnly; Path=/; Max-Age=${r}; SameSite=Lax`}function eye(){return`${hG}=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax`}var pb=co("manga_library",{id:Ge("id").notNull(),provider:Ge("provider").notNull(),mangaId:Ge("mangaId").notNull(),title:Ge("title"),cover:Ge("cover"),status:Ge("status"),author:Ge("author"),altTitle:Ge("altTitle"),contentRating:Ge("contentRating"),lastChapterId:Ge("lastChapterId"),lastChapterNumber:Ge("lastChapterNumber"),lastPage:Mn("lastPage"),updatedAt:Mn("updatedAt"),anilistId:Mn("anilistId"),anilistIdSource:Ge("anilistIdSource")},e=>[ea({columns:[e.id]})]),QHt=co("manga_progress",{mangaId:Ge("mangaId").notNull(),chapterId:Ge("chapterId").notNull(),chapterNumber:Ge("chapterNumber"),page:Mn("page"),pageCount:Mn("pageCount"),updatedAt:Mn("updatedAt"),title:Ge("title"),cover:Ge("cover"),provider:Ge("provider"),altTitle:Ge("altTitle"),contentRating:Ge("contentRating")},e=>[ea({columns:[e.mangaId,e.chapterId]})]);var tye=["watchlist","watched_episodes","queue","shows_meta","dismissed_notifications","discovered_notifications","legacy_id_mapping","temp_show_ids"],rye=["manga_library","manga_progress"],nye=["tv_library","tv_progress"],iye=["asmr_library","asmr_progress"];async function _x(e,t){let r={};for(let n of t)try{let i=await re(e).all(b`SELECT COUNT(*) AS rows FROM ${b.raw(`"${n}"`)}`);r[n]=i[0]?.rows??0}catch{r[n]=0}return r}async function Ox(e,t){for(let r of t)try{await re(e).run(b`DELETE FROM ${b.raw(`"${r}"`)}`)}catch{}}function wm(e){let t=b.raw(`"${e}"`);return{getById:async(r,n)=>(await re(r).all(b`SELECT * FROM ${t} WHERE id = ${n}`))[0],getAll:(r,n,i,s)=>{let o=b`SELECT * FROM ${t}`;return n&&n!=="All"&&o.append(b` WHERE status = ${n}`),o.append(b` ORDER BY updatedAt DESC`),i!==void 0&&s!==void 0&&o.append(b` LIMIT ${i} OFFSET ${s}`),re(r).all(o)},getCount:async(r,n)=>n&&n!=="All"?(await re(r).all(b`SELECT COUNT(*) as total FROM ${t} WHERE status = ${n}`))[0]?.total||0:(await re(r).all(b`SELECT COUNT(*) as total FROM ${t}`))[0]?.total||0,getIds:async r=>(await re(r).all(b`SELECT id FROM ${t}`)).map(i=>i.id),updateStatus:(r,n,i)=>re(r).run(b`
|
package/server/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o as y,a as I,d as T,h as b,T as S,u as e}from"./vendor-core-DfaOB3Rn.js";import{I as o}from"./vendor-icons-C1Pj_eSX.js";import{d as B,e as w,f as m,a8 as M,s as x,Q as A,B as p}from"./index-BHWOY-pi.js";import{u as D}from"./useAnimeInfoData-DhoidxrL.js";import{A as G}from"./AnimeMetaDetails-B3-A7O5H.js";import{S as P}from"./SynopsisText-B3Sa5pRv.js";import{Q as W}from"./QueueOptionsButton-BubxC3vl.js";import"./vendor-query-BBT5_sHx.js";import"./useIsMobile-Dvx1uJ82.js";import"./vendor-ui-3qrARCPr.js";const O="_container_1obln_1",$="_heroSection_1obln_11",U="_bannerContainer_1obln_17",j="_banner_1obln_17",q="_bannerOverlay_1obln_37",z="_heroContent_1obln_49",Q="_posterContainer_1obln_62",V="_floatIn_1obln_1",E="_poster_1obln_62",F="_infoGlass_1obln_86",H="_slideUpIn_1obln_1",J="_title_1obln_100",K="_quickMeta_1obln_109",L="_metaItem_1obln_117",R="_iconStar_1obln_126",X="_iconTv_1obln_129",Y="_iconType_1obln_132",Z="_iconClock_1obln_135",ee="_genres_1obln_139",ne="_genre_1obln_139",te="_infoColumns_1obln_165",oe="_synopsisSection_1obln_180",se="_sectionTitleSmall_1obln_188",ae="_actions_1obln_210",ie="_watchBtn_1obln_216",le="_watchlistBtn_1obln_238",ce="_active_1obln_258",re="_detailsToggleBtn_1obln_265",me="_expandedContent_1obln_288",_e="_fadeIn_1obln_1",de="_detailsGridContainer_1obln_293",he="_detailItem_1obln_301",be="_airingValue_1obln_320",pe="_loadingDetails_1obln_325",ue="_spinner_1obln_334",ve="_spin_1obln_334",ge="_heroSkeleton_1obln_349",ke="_skeletonBanner_1obln_353",fe="_skeletonPoster_1obln_354",Ne="_skeletonTitle_1obln_355",Ce="_skeletonMeta_1obln_356",ye="_skeletonDesc_1obln_357",Ie="_skeletonActions_1obln_358",Te="_skeletonContent_1obln_391",Se="_skeletonInfo_1obln_405",t={container:O,heroSection:$,bannerContainer:U,banner:j,bannerOverlay:q,heroContent:z,posterContainer:Q,floatIn:V,poster:E,infoGlass:F,slideUpIn:H,title:J,quickMeta:K,metaItem:L,iconStar:R,iconTv:X,iconType:Y,iconClock:Z,genres:ee,genre:ne,infoColumns:te,synopsisSection:oe,sectionTitleSmall:se,actions:ae,watchBtn:ie,watchlistBtn:le,active:ce,detailsToggleBtn:re,expandedContent:me,fadeIn:_e,detailsGridContainer:de,detailItem:he,airingValue:be,loadingDetails:pe,spinner:ue,spin:ve,heroSkeleton:ge,skeletonBanner:ke,skeletonPoster:fe,skeletonTitle:Ne,skeletonMeta:Ce,skeletonDesc:ye,skeletonActions:Ie,"skeleton-wave":"_skeleton-wave_1obln_1",skeletonContent:Te,skeletonInfo:Se};function $e(){const{id:s}=y(),a=I(),{titlePreference:l}=B(),[i,u]=T(!1),{showMeta:n,loadingMeta:v,toggleWatchlist:g,inWatchlist:c}=D(s),{hasConsent:k,grant:f}=w();b(()=>{s&&n?.id&&n.id!==s&&a(`/anime/${n.id}`,{replace:!0})},[s,n,a]),b(()=>{document.title=n?.name?`${n.name} - dango`:"Anime - dango"},[n?.name]);const N=()=>n?.name?l==="name"?n.name:l==="nativeName"?n.names?.native||n.name:l==="englishName"&&n.names?.english||n.name:"",C=()=>{s&&a(`/watch/${s}`)},_=S(()=>n?.bannerImage?m(n.bannerImage):n?.thumbnail?m(n.thumbnail,1200,450):"",[n?.bannerImage,n?.thumbnail]);if(v||!n?.name)return e("div",{className:t.container,children:e("div",{className:t.heroSkeleton,children:[e("div",{className:t.skeletonBanner}),e("div",{className:t.skeletonContent,children:[e("div",{className:t.skeletonPoster}),e("div",{className:t.skeletonInfo,children:[e("div",{className:t.skeletonTitle}),e("div",{className:t.skeletonMeta}),e("div",{className:t.skeletonDesc}),e("div",{className:t.skeletonActions})]})]})]})});const d=n.isAdult===!0&&!k;return e("div",{className:t.container,style:d?{filter:"blur(14px)",pointerEvents:"none",userSelect:"none"}:void 0,children:[e("div",{className:t.heroSection,children:[e("div",{className:t.bannerContainer,children:[e("div",{className:t.banner,style:_?{backgroundImage:`url(${_})`}:void 0}),e("div",{className:t.bannerOverlay})]}),e("div",{className:t.heroContent,children:[e("div",{className:t.posterContainer,children:e(M,{src:m(n.thumbnail||"",320,480),alt:n.name,className:t.poster,decoding:"async"})}),e("div",{className:t.infoGlass,children:[e("div",{children:[e("h1",{className:t.title,children:N()}),e("div",{className:t.quickMeta,children:[n.score&&e("div",{className:t.metaItem,children:[e(o,{name:"star",className:t.iconStar}),e("span",{children:n.score})]}),n.status&&e("div",{className:t.metaItem,children:[e(o,{name:"tv",className:t.iconTv}),e("span",{children:n.status})]}),n.type&&e("div",{className:t.metaItem,children:[e(o,{name:"layer-group",className:t.iconType}),e("span",{children:n.type})]})]}),Array.isArray(n.genres)&&n.genres.length>0&&e("div",{className:t.genres,children:n.genres.filter(Boolean).slice(0,5).map(r=>{const h=typeof r=="string"?r:r?.name;return e("span",{className:t.genre,children:h},h)})})]}),e("div",{className:t.infoColumns,children:[e("div",{className:t.synopsisSection,children:[e("h2",{className:t.sectionTitleSmall,children:"Synopsis"}),e(P,{text:x(n.description),emptyText:"No description available."}),e("button",{className:t.detailsToggleBtn,onClick:()=>{u(!i)},children:[i?e(o,{name:"chevron-up"}):e(o,{name:"chevron-down"}),i?"Hide Details":"Show Details"]})]}),i&&e("div",{className:t.expandedContent,children:e(G,{showMeta:n,styles:t})})]}),e("div",{className:t.actions,children:[e("button",{className:t.watchBtn,onClick:C,children:[e(o,{name:"play",size:14}),"Start Watching"]}),e("button",{className:`${t.watchlistBtn} ${c?t.active:""}`,onClick:g,children:[c?e(o,{name:"check",size:14}):e(o,{name:"plus",size:14}),c?"In Watchlist":"Add to Watchlist"]}),e(W,{showId:s,showName:n.name||n.names?.romaji,showThumbnail:n.thumbnail,nativeName:n.names?.native,englishName:n.names?.english,showType:n.type,className:t.watchlistBtn,activeClassName:t.active})]})]})]})]}),d&&e(A,{isOpen:!0,title:"Content Warning",onClose:()=>a("/"),children:e("div",{style:{padding:"1rem",textAlign:"center"},children:[e("p",{children:"This title contains mature content intended for adult audiences."}),e("p",{children:["By proceeding, you confirm that you are ",e("strong",{children:"18 years of age or older"})," (or the age of majority in your jurisdiction) and wish to view this content."]}),e("div",{style:{marginTop:"1rem",display:"flex",gap:"10px",justifyContent:"center"},children:[e(p,{variant:"secondary",onClick:()=>a("/"),children:"Go Back"}),e(p,{onClick:f,children:"I'm 18+, Continue"})]})]})})]})}export{$e as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as B,A as F,h as x,q as P,g as q,u as e,L as Oe,T as Q,S as se,a as ee,_ as et}from"./vendor-core-DfaOB3Rn.js";import{u as ke,a as ie,b as tt,c as at,q as ze,t as nt,d as Ve,s as rt,f as Ne,B as Fe,e as ot,g as st,m as Ce,p as re,h as oe,i as lt,j as it,k as ct,l as Ie,M as dt,T as ut,n as ht,o as mt,r as Me,v as gt,w as pt,x as vt,y as _t,z as yt,A as bt,C as ft,D as Tt,E as Nt,F as wt}from"./index-BHWOY-pi.js";import{b as St,u as kt,a as Ct}from"./vendor-query-BBT5_sHx.js";import{M as pe,P as It}from"./MediaCard-BbqpD03k.js";import{A as ce}from"./AnimeCard-DpZ4X9XD.js";import{S as je,A as Ge}from"./SkeletonGrid-U0v5ZOMU.js";import{I as E}from"./vendor-icons-C1Pj_eSX.js";import{u as Rt}from"./vendor-ui-3qrARCPr.js";import{E as Re}from"./ErrorMessage-hMt90aG4.js";import{R as Ue}from"./ResetProgressModal-tI6IHvmP.js";import{Q as At}from"./QueueRail-CUsYeL0A.js";import{u as qe,M as Qe}from"./useMangaPopup-BV_Jk_2y.js";import{M as Lt}from"./MangaResetProgressModal-CVPwJSlW.js";import{u as Ye,m as Se,i as He,a as Xe,b as $t}from"./useMangaLibrary-Bogr8MQ7.js";import{u as Mt}from"./useProviders-CbFHcVVq.js";import{u as Ke,a as Be,T as Bt}from"./useTv-DBYyKAM6.js";import{T as xt}from"./TvPopup-B_BBkSA6.js";import{u as Pt,a as Et,b as Dt}from"./useTvLibrary-D2tKj7cP.js";import{A as Wt}from"./AsmrResetProgressModal-BOXFH3f2.js";import{u as Ot,a as zt,A as Vt,b as Ft,c as jt}from"./AsmrPopup-CNqixGCf.js";import"./useIsMobile-Dvx1uJ82.js";import"./MatureConsentModal-BoSwjOI5.js";import"./useAnimeInfoData-DhoidxrL.js";import"./QueueOptionsButton-BubxC3vl.js";import"./playbackCompletion-Cq6Pbug7.js";import"./usePopup-DS9jMzp6.js";import"./libraryInvalidation-D8h84CFM.js";const Gt="_sectionWrapper_x6wvn_9",Ut="_sectionTitleNoMargin_x6wvn_19",qt="_carousel_x6wvn_195",M={"section-header":"_section-header_x6wvn_1",sectionWrapper:Gt,sectionTitleNoMargin:Ut,"title-wrapper":"_title-wrapper_x6wvn_23","header-controls":"_header-controls_x6wvn_30","header-select":"_header-select_x6wvn_37","collapse-button":"_collapse-button_x6wvn_86","title-link":"_title-link_x6wvn_106","continue-watching":"_continue-watching_x6wvn_125","nav-arrows":"_nav-arrows_x6wvn_147","nav-button":"_nav-button_x6wvn_153","carousel-container":"_carousel-container_x6wvn_195",carousel:qt,"carousel-inner":"_carousel-inner_x6wvn_204","carousel-card":"_carousel-card_x6wvn_210"};function ve({align:n="start",containScroll:l="trimSnaps",scrollFraction:h=.8,threshold:t=.6,onReachThreshold:o,slideCount:i=0}={}){const[p,s]=Rt({align:n,containScroll:l,dragFree:!0}),[S,y]=B(!1),[N,m]=B(!1),c=F({scrollFraction:h,threshold:t,onReachThreshold:o}),r=F(!1);x(()=>{c.current={scrollFraction:h,threshold:t,onReachThreshold:o}});const w=P(g=>{y(g.canScrollPrev()),m(g.canScrollNext())},[]);x(()=>{if(!s)return;const g=()=>{const u=s.scrollProgress();u>=c.current.threshold&&!r.current?(r.current=!0,c.current.onReachThreshold?.()):u<c.current.threshold&&(r.current=!1),w(s)};return s.on("init",g),s.on("reInit",g),s.on("scroll",g),s.on("resize",g),()=>{s.off("init",g),s.off("reInit",g),s.off("scroll",g),s.off("resize",g)}},[s,w]),x(()=>{s?.reInit()},[s,i]);const C=P(g=>{const u=g.containerNode().firstElementChild;if(!u)return 1;const f=g.rootNode().getBoundingClientRect().width,R=u.getBoundingClientRect().width;return R?Math.max(1,Math.round(f/R)):1},[]),k=P((g,u=!1)=>{if(!s)return;const f=Math.max(1,Math.round(C(s)*c.current.scrollFraction)),R=s.selectedScrollSnap()+(g==="left"?-f:f);s.scrollTo(R,u)},[s,C]),d=P((g=!1)=>{s?.scrollTo(0,g)},[s]);return{emblaRef:p,api:s,canScrollPrev:S,canScrollNext:N,stepBy:k,scrollToStart:d}}const Z=({title:n,eyebrow:l,titleLink:h,loading:t,emptyState:o,carousel:i,layout:p,collapsible:s,defaultExpanded:S=!0,onReachThreshold:y,scrollThreshold:N,isFetchingNextPage:m,resetScrollOnShrink:c,itemCount:r=0,highlight:w,headerActions:C,loadingSkeleton:k,skeletonCount:d=7,children:g})=>{const{lowEndMode:u}=ke(),{emblaRef:f,stepBy:R,scrollToStart:z,canScrollPrev:A,canScrollNext:D}=ve({onReachThreshold:y,threshold:N,slideCount:r}),[L,V]=q.useState(S);q.useEffect(()=>{V(S)},[S]);const j=q.useRef(0);return q.useEffect(()=>{c&&r>0&&L&&(r<=j.current||j.current===0)&&z(),r>0&&(j.current=r)},[r,c,L,z]),!t&&r===0&&!o&&!s?null:e("section",{className:`${M.sectionWrapper} ${w?M["continue-watching"]:""}`,children:[e("div",{className:M["section-header"],children:[e("div",{className:M["title-wrapper"],children:e("div",{className:"title-stack",children:[l&&e("div",{className:"section-eyebrow",children:l}),h?e(Oe,{to:h,className:M["title-link"],children:e("div",{className:`section-title ${M.sectionTitleNoMargin}`,children:n})}):e("div",{className:`section-title ${M.sectionTitleNoMargin}`,children:n})]})}),e("div",{className:M["header-controls"],children:[C,i&&r>0&&L&&(A||D)&&e("div",{className:M["nav-arrows"],children:[A&&e("button",{className:M["nav-button"],type:"button","aria-label":"Scroll left",onClick:I=>{I.preventDefault(),R("left",u)},children:e(E,{name:"chevron-left"})}),D&&e("button",{className:M["nav-button"],type:"button","aria-label":"Scroll right",onClick:I=>{I.preventDefault(),R("right",u)},children:e(E,{name:"chevron-right"})})]}),s&&e("button",{className:M["collapse-button"],type:"button",onClick:()=>V(I=>!I),"aria-expanded":L,"aria-label":L?`Collapse ${n}`:`Expand ${n}`,children:L?e(E,{name:"chevron-up"}):e(E,{name:"chevron-down"})})]})]}),L&&(i?!t&&r===0&&o?e("div",{children:o}):e("div",{className:M["carousel-container"],children:e("div",{className:M.carousel,ref:f,children:e("div",{className:M["carousel-inner"],children:[t&&r===0?Array.from({length:d}).map((I,U)=>e("div",{className:M["carousel-card"],children:k},U)):q.Children.map(g,(I,U)=>e("div",{className:M["carousel-card"],children:I},q.isValidElement(I)&&I.key!=null?I.key:`slide-${U}`)),m&&k&&e("div",{className:M["carousel-card"],children:k})]})})}):e("div",{className:"grid-container",children:t&&r===0?e(je,{count:6,layout:p}):r>0?g:t?null:e("div",{style:{gridColumn:"1 / -1"},children:o})}))]})},Qt=({title:n,eyebrow:l,animeList:h,continueWatching:t,episodeBadge:o,titleLink:i,onRemove:p,loading:s,emptyState:S,carousel:y,cardConfig:N,layout:m,onReachThreshold:c,scrollThreshold:r,isFetchingNextPage:w,collapsible:C,defaultExpanded:k=!0})=>{const d=m||"vertical";return e(Z,{title:n,eyebrow:l,titleLink:i,loading:s,emptyState:S,carousel:y,layout:d,collapsible:C,defaultExpanded:k,onReachThreshold:c,scrollThreshold:r,isFetchingNextPage:w,resetScrollOnShrink:t,highlight:t,itemCount:h.length,loadingSkeleton:e(Ge,{layout:d}),skeletonCount:7,children:h.map(g=>e(ce,{anime:g,continueWatching:t,episodeBadge:o,onRemove:p,config:N,layout:d},g._id))})},xe=q.memo(Qt),Yt="_wrapper_j52nn_1",Ht="_arrow_j52nn_6",Xt="_select_j52nn_15",we={wrapper:Yt,arrow:Ht,select:Xt},J=({value:n,options:l,onChange:h,ariaLabel:t,width:o})=>e("span",{className:we.wrapper,children:[e("select",{className:we.select,style:o!==void 0?{width:o}:void 0,value:n,"aria-label":t,onChange:i=>h(i.currentTarget.value),children:l.map(i=>e("option",{value:i.value,children:i.label},i.value))}),e(E,{name:"chevron-down",size:12,className:we.arrow})]}),Kt="_sectionWrapper_b6zf8_2",Zt="_sectionTitleNoMargin_b6zf8_12",Jt="_carouselContainer_b6zf8_100",ea="_carousel_b6zf8_100",ta="_carouselInner_b6zf8_111",aa="_carouselItem_b6zf8_117",na="_rankCard_b6zf8_154",ra="_rankPill_b6zf8_158",oa="_rankGold_b6zf8_169",sa="_rankSilver_b6zf8_173",la="_rankBronze_b6zf8_177",ia="_skeletonPoster_b6zf8_188",ca="_skeletonText_b6zf8_189",_={sectionWrapper:Kt,sectionTitleNoMargin:Zt,"section-header":"_section-header_b6zf8_17","title-wrapper":"_title-wrapper_b6zf8_25","header-actions":"_header-actions_b6zf8_45","nav-arrows":"_nav-arrows_b6zf8_51","nav-button":"_nav-button_b6zf8_57",carouselContainer:Jt,carousel:ea,carouselInner:ta,carouselItem:aa,rankCard:na,rankPill:ra,rankGold:oa,rankSilver:sa,rankBronze:la,skeletonPoster:ia,skeletonText:ca},Pe="TRENDING_DESC",da="POPULARITY_DESC",ua=10;function ha({title:n,eyebrow:l}){const{lowEndMode:h}=ke(),[t,o]=ie("trending_sort",Pe),i=[{value:Pe,label:"Trending"},{value:da,label:"All Time"}],{data:p,fetchNextPage:s,hasNextPage:S,isFetchingNextPage:y,isLoading:N,isError:m,error:c}=tt(t,ua),r=Q(()=>p?.pages.flatMap(u=>u)||[],[p]),w=P(()=>{S&&!y&&!N&&s()},[S,y,N,s]),{emblaRef:C,stepBy:k,canScrollPrev:d,canScrollNext:g}=ve({onReachThreshold:w,slideCount:r.length});return e("section",{className:_.sectionWrapper,children:[e("div",{className:_["section-header"],children:[e("div",{className:_["title-wrapper"],children:e("div",{className:"title-stack",children:[l&&e("div",{className:"section-eyebrow",children:l}),e("div",{className:`section-title ${_.sectionTitleNoMargin}`,children:n})]})}),e("div",{className:_["header-actions"],children:[e(J,{ariaLabel:"Trending sort",width:120,value:t,options:i,onChange:o}),(d||g)&&e("div",{className:_["nav-arrows"],children:[d&&e("button",{className:_["nav-button"],type:"button",onClick:u=>{u.preventDefault(),k("left",h)},"aria-label":"Scroll left",children:e(E,{name:"chevron-left"})}),g&&e("button",{className:_["nav-button"],type:"button",onClick:u=>{u.preventDefault(),k("right",h)},"aria-label":"Scroll right",children:e(E,{name:"chevron-right"})})]})]})]}),N?e("div",{className:_.carouselContainer,children:e("div",{className:_.carousel,children:e("div",{className:_.carouselInner,children:Array.from({length:7}).map((u,f)=>e("div",{className:_.carouselItem,children:[e("div",{className:_.skeletonPoster}),e("div",{className:_.skeletonText})]},f))})})}):m?e(Re,{message:c instanceof Error?c.message:"An unknown error occurred"}):e("div",{className:_.carouselContainer,children:e("div",{className:_.carousel,ref:C,children:e("div",{className:_.carouselInner,children:[r.map((u,f)=>e("div",{className:_.carouselItem,children:[e("div",{className:_.rankCard,children:e(ce,{anime:u})}),e("div",{className:`${_.rankPill} ${f===0?_.rankGold:f===1?_.rankSilver:f===2?_.rankBronze:""}`,children:f+1})]},u._id)),y&&e("div",{className:_.carouselItem,style:{minWidth:"150px",display:"flex",alignItems:"center",justifyContent:"center"},children:e("div",{className:_.skeletonPoster})})]})})})]})}const ma=[{value:"TV",label:"TV"},{value:"ONA",label:"ONA"},{value:"OVA",label:"OVA"},{value:"MOVIE",label:"Movie"},{value:"ALL",label:"All"},{value:"ADULT",label:"Mature"}],ga=10;function pa({eyebrow:n}){const{lowEndMode:l}=ke(),[h,t]=ie("latest_releases_format","TV"),{data:o,fetchNextPage:i,hasNextPage:p,isFetchingNextPage:s,isLoading:S,isError:y,error:N}=at(h,ga),m=Q(()=>o?.pages.flatMap(d=>d)||[],[o]),c=P(()=>{p&&!s&&!S&&i()},[p,s,S,i]),{emblaRef:r,stepBy:w,canScrollPrev:C,canScrollNext:k}=ve({onReachThreshold:c,slideCount:m.length});return e("section",{className:_.sectionWrapper,children:[e("div",{className:_["section-header"],children:[e("div",{className:_["title-wrapper"],children:e("div",{className:"title-stack",children:[n&&e("div",{className:"section-eyebrow",children:n}),e("div",{className:`section-title ${_.sectionTitleNoMargin}`,children:"Latest Releases"})]})}),e("div",{className:_["header-actions"],children:[e(J,{ariaLabel:"Latest releases format",width:120,value:h,options:ma,onChange:t}),(C||k)&&e("div",{className:_["nav-arrows"],children:[C&&e("button",{className:_["nav-button"],type:"button",onClick:d=>{d.preventDefault(),w("left",l)},"aria-label":"Scroll left",children:e(E,{name:"chevron-left"})}),k&&e("button",{className:_["nav-button"],type:"button",onClick:d=>{d.preventDefault(),w("right",l)},"aria-label":"Scroll right",children:e(E,{name:"chevron-right"})})]})]})]}),S?e("div",{className:_.carouselContainer,children:e("div",{className:_.carousel,children:e("div",{className:_.carouselInner,children:Array.from({length:7}).map((d,g)=>e("div",{className:_.carouselItem,children:[e("div",{className:_.skeletonPoster}),e("div",{className:_.skeletonText})]},g))})})}):y?e(Re,{message:N instanceof Error?N.message:"An unknown error occurred"}):e("div",{className:_.carouselContainer,children:e("div",{className:_.carousel,ref:r,children:e("div",{className:_.carouselInner,children:[m.map(d=>e("div",{className:_.carouselItem,children:e(ce,{anime:d})},d._id)),s&&e("div",{className:_.carouselItem,style:{minWidth:"150px",display:"flex",alignItems:"center",justifyContent:"center"},children:e("div",{className:_.skeletonPoster})})]})})})]})}const va="_scheduleSection_ngtwy_1",_a="_sectionTitleRow_ngtwy_5",ya="_sectionTitleNoMargin_ngtwy_11",ba="_sectionHeader_ngtwy_15",fa="_headerActions_ngtwy_25",Ta="_daySelectorContainer_ngtwy_33",Na="_daySelector_ngtwy_33",wa="_daySelectorInner_ngtwy_50",Sa="_dayBtn_ngtwy_61",ka="_active_ngtwy_84",Ca="_dayMonth_ngtwy_92",Ia="_dayNum_ngtwy_100",Ra="_dayName_ngtwy_106",Aa="_navArrows_ngtwy_119",La="_navButton_ngtwy_125",$a="_carouselContainer_ngtwy_168",Ma="_carousel_ngtwy_168",Ba="_carouselInner_ngtwy_180",xa="_carouselCard_ngtwy_186",$={scheduleSection:va,sectionTitleRow:_a,sectionTitleNoMargin:ya,sectionHeader:ba,headerActions:fa,daySelectorContainer:Ta,daySelector:Na,daySelectorInner:wa,dayBtn:Sa,active:ka,dayMonth:Ca,dayNum:Ia,dayName:Ra,navArrows:Aa,navButton:La,carouselContainer:$a,carousel:Ma,carouselInner:Ba,carouselCard:xa},de=n=>{const l=n.getFullYear(),h=String(n.getMonth()+1).padStart(2,"0"),t=String(n.getDate()).padStart(2,"0");return`${l}-${h}-${t}`},Pa=async(n,l)=>await nt.data.schedule.query({date:n,format:l}),Ea=({eyebrow:n})=>{const[l,h]=B(()=>de(new Date)),[t,o]=ie("schedule_format","TV"),i=F(null),p=F(!0),{data:s=[],isLoading:S,error:y}=St({queryKey:[ze.schedule,l,t],queryFn:()=>Pa(l,t),staleTime:1e3*60*5}),{emblaRef:N,canScrollPrev:m,canScrollNext:c,stepBy:r,scrollToStart:w}=ve({slideCount:s.length}),C=Q(()=>{const d=[],g=new Date,u=de(g),f=new Date(g);f.setDate(g.getDate()-1);const R=de(f),z=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];for(let A=-6;A<=6;A++){const D=new Date(g);D.setDate(g.getDate()+A),d.push(D)}return d.map(A=>{const D=de(A),j=D===u?"Today":D===R?"Yest":z[A.getDay()],I=A.getDate(),U=new Intl.DateTimeFormat("en-US",{month:"short"}).format(A);return{dateString:D,dayLabel:j,dayNum:I,monthName:U}})},[]);x(()=>{const d=i.current,g=d?.querySelector(`[data-date="${l}"]`);if(!d||!g)return;const u=d.getBoundingClientRect(),f=g.getBoundingClientRect(),R=d.scrollLeft+(f.left-u.left)-(u.width-f.width)/2;d.scrollTo({left:Math.max(0,R),behavior:p.current?"auto":"smooth"}),p.current=!1},[l]),x(()=>{w(!0)},[l,w]);const k=[{value:"TV",label:"TV"},{value:"ONA",label:"ONA"},{value:"OVA",label:"OVA"},{value:"MOVIE",label:"Movie"},{value:"ALL",label:"All"},{value:"ADULT",label:"Mature"}];return e("div",{className:$.scheduleSection,children:[e("div",{className:$.sectionHeader,children:[e("div",{className:$.sectionTitleRow,children:e("div",{className:"title-stack",children:[n&&e("div",{className:"section-eyebrow",children:n}),e("h2",{className:`section-title ${$.sectionTitleNoMargin}`,children:"Episode Schedule"})]})}),e("div",{className:$.headerActions,children:[e(J,{ariaLabel:"Schedule format",width:120,value:t,options:k,onChange:o}),s.length>0&&(m||c)&&e("div",{className:$.navArrows,children:[m&&e("button",{className:$.navButton,onClick:()=>r("left"),"aria-label":"Scroll left",children:e(E,{name:"chevron-left"})}),c&&e("button",{className:$.navButton,onClick:()=>r("right"),"aria-label":"Scroll right",children:e(E,{name:"chevron-right"})})]})]})]}),e("div",{className:$.daySelectorContainer,children:e("div",{className:$.daySelector,ref:i,children:e("div",{className:$.daySelectorInner,children:C.map(d=>e("button",{type:"button","data-date":d.dateString,"aria-pressed":l===d.dateString,className:`${$.dayBtn} ${l===d.dateString?$.active:""}`,onClick:()=>h(d.dateString),children:[e("span",{className:$.dayMonth,children:d.monthName}),e("span",{className:$.dayNum,children:d.dayNum}),e("span",{className:$.dayName,children:d.dayLabel})]},d.dateString))})})}),e("div",{className:$.carouselContainer,children:e("div",{className:$.carousel,ref:N,children:e("div",{className:$.carouselInner,children:S?Array.from({length:7}).map((d,g)=>e("div",{className:$.carouselCard,children:e(Ge,{layout:"vertical"})},g)):y?e("div",{style:{width:"100%"},children:e(Re,{message:y instanceof Error?y.message:"An unknown error occurred"})}):s.length===0?e("p",{style:{textAlign:"center",marginTop:"1rem",width:"100%"},children:"No episodes scheduled for this day."}):s.map(d=>e("div",{className:$.carouselCard,children:e(ce,{anime:d,continueWatching:!1,episodeBadge:!0,layout:"vertical"},d._id)},d._id))})})})]})},Da="_bannerContainer_lye2m_1",Wa="_hero_lye2m_28",Oa="_ambient_lye2m_37",za="_ambientShow_lye2m_49",Va="_scrim_lye2m_53",Fa="_progressLine_lye2m_64",ja="_paused_lye2m_84",Ga="_dots_lye2m_98",Ua="_dot_lye2m_98",qa="_dotActive_lye2m_121",Qa="_viewport_lye2m_132",Ya="_track_lye2m_139",Ha="_slide_lye2m_145",Xa="_slideInner_lye2m_153",Ka="_poster_lye2m_163",Za="_posterLandscape_lye2m_174",Ja="_info_lye2m_198",en="_kicker_lye2m_207",tn="_featureLabel_lye2m_214",an="_scoreChip_lye2m_226",nn="_rise_lye2m_244",rn="_active_lye2m_248",on="_metaRow_lye2m_304",sn="_metaItem_lye2m_315",ln="_metaDivider_lye2m_321",cn="_title_lye2m_328",dn="_genres_lye2m_347",un="_genreTag_lye2m_355",hn="_summary_lye2m_366",mn="_actions_lye2m_378",gn="_watchBtn_lye2m_386",pn="_detailsBtn_lye2m_418",vn="_secondaryRow_lye2m_449",_n="_secondaryBtn_lye2m_456",yn="_navArrow_lye2m_479",bn="_prevArrow_lye2m_512",fn="_nextArrow_lye2m_516",v={bannerContainer:Da,hero:Wa,ambient:Oa,ambientShow:za,scrim:Va,progressLine:Fa,paused:ja,dots:Ga,dot:Ua,dotActive:qa,viewport:Qa,track:Ya,slide:Ha,slideInner:Xa,poster:Ka,posterLandscape:Za,info:Ja,kicker:en,featureLabel:tn,scoreChip:an,rise:nn,active:rn,metaRow:on,metaItem:sn,metaDivider:ln,title:cn,genres:dn,genreTag:un,summary:hn,actions:mn,watchBtn:gn,detailsBtn:pn,secondaryRow:vn,secondaryBtn:_n,navArrow:yn,prevArrow:bn,nextArrow:fn},Tn=8e3,ue=()=>e("div",{className:"skeleton",style:{width:"100vw",maxWidth:"100vw",position:"relative",left:"50%",right:"50%",marginLeft:"-50vw",marginRight:"-50vw",height:"clamp(480px, 72vh, 660px)",marginTop:"calc(-1 * var(--header-height))",marginBottom:"2.5rem"}}),_e=({slides:n,posterAspect:l="portrait",eyebrow:h="Spotlight"})=>{const[t,o]=B(0),[i,p]=B(0),[s,S]=B(!1),[y,N]=B(null),[m,c]=B(0),[r,w]=B({front:"",back:"",flip:!1}),C=F(0),k=F(0),d=F(new Set),g=F(null),u=F(0),f=P(a=>a.bannerSrc,[]),R=P(()=>{p(a=>a+1)},[]),z=P(a=>{g.current!==null&&(window.clearTimeout(g.current),g.current=null),N(null),R();const b=f(n[a]);w(T=>T.flip?{front:b,back:T.back,flip:!1}:{front:T.front,back:b,flip:!0}),o(a)},[R,n,f]),A=P(a=>{if(n.length===0)return;const b=(a%n.length+n.length)%n.length;d.current.has(f(n[b]))?z(b):N(b)},[n,f,z]);x(()=>{let a=!1;return n.forEach(b=>{const T=f(b);if(!T||d.current.has(T))return;const W=new Image;W.src=T;const X=()=>{a||d.current.has(T)||(d.current.add(T),c(G=>G+1))};W.onload=X,W.onerror=X}),()=>{a=!0}},[n,f]),x(()=>{if(n.length!==0&&!r.front){const a=f(n[0]);w({front:a,back:"",flip:!1})}},[n,r.front,f]),x(()=>{if(y!==null){if(y<0||y>=n.length){N(null);return}d.current.has(f(n[y]))&&z(y)}},[y,m,n,f,z]),x(()=>{if(y===null)return;g.current!==null&&window.clearTimeout(g.current);const a=y;return g.current=window.setTimeout(()=>{g.current=null,z(a)},2500),()=>{g.current!==null&&(window.clearTimeout(g.current),g.current=null)}},[y,z]);const D=P(a=>{A(a)},[A]),L=P(()=>{A(u.current+1)},[A]),V=P(()=>{A(u.current-1)},[A]),j=F(null);if(x(()=>{const a=j.current;if(!a)return;const b=T=>{if(Math.abs(T.deltaY)>Math.abs(T.deltaX)&&Math.abs(T.deltaY)>5){T.preventDefault(),T.stopPropagation();const W=Date.now();if(W-C.current<300)return;C.current=W,R(),T.deltaY>0?L():V()}};return a.addEventListener("wheel",b,{passive:!1}),()=>a.removeEventListener("wheel",b)},[n.length,L,V,R]),x(()=>{if(n.length===0||s)return;const a=setTimeout(L,Tn);return()=>clearTimeout(a)},[t,L,n.length,i,s]),x(()=>{const a=b=>{const T=b.target;T&&(T.tagName==="INPUT"||T.tagName==="TEXTAREA"||T.tagName==="SELECT"||T.isContentEditable)||(b.key==="ArrowRight"?(b.preventDefault(),L()):b.key==="ArrowLeft"&&(b.preventDefault(),V()))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[L,V]),x(()=>{t>=n.length&&o(0)},[n.length,t]),n.length===0)return null;const I=t>=n.length?0:t;u.current=I;const U=a=>{k.current=a.touches[0].clientX},H=a=>{const T=a.changedTouches[0].clientX-k.current;Math.abs(T)>50&&(R(),T>0?V():L())};return e("div",{className:v.bannerContainer,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),children:e("div",{className:`${v.hero} ${s?v.paused:""}`,onTouchStart:U,onTouchEnd:H,children:[r.front&&e("img",{src:r.front,alt:"","aria-hidden":"true",className:`${v.ambient} ${r.flip?"":v.ambientShow}`}),r.back&&e("img",{src:r.back,alt:"","aria-hidden":"true",className:`${v.ambient} ${r.flip?v.ambientShow:""}`}),e("div",{className:v.scrim,"aria-hidden":"true"}),n.length>1&&e("div",{className:v.progressLine,"aria-hidden":"true"},`progress-${i}-${I}`),n.length>1&&e("div",{className:v.dots,ref:j,role:"tablist","aria-label":"Spotlight slides",children:n.map((a,b)=>e("button",{role:"tab","aria-selected":b===I,"aria-label":`Go to slide ${b+1}: ${a.title}`,className:`${v.dot} ${b===I?v.dotActive:""}`,onClick:()=>D(b),tabIndex:b===I?0:-1},a.key))}),e("div",{className:v.viewport,children:e("div",{className:v.track,style:{transform:`translateX(-${I*100}%)`},children:n.map((a,b)=>e("div",{className:`${v.slide} ${b===I?v.active:""}`,"aria-hidden":b!==I,children:e("div",{className:v.slideInner,children:[e("img",{src:a.posterSrc,alt:a.posterAlt,className:l==="landscape"?v.posterLandscape:v.poster,decoding:"async"}),e("div",{className:v.info,children:[e("div",{className:`${v.kicker} ${v.rise}`,children:[e("span",{className:v.featureLabel,children:h}),a.score!==void 0&&a.score!==null&&a.score!==""&&e("span",{className:v.scoreChip,children:[e(E,{name:"star",size:12}),e("span",{children:a.score})]})]}),e(Oe,{to:a.detailTo,className:`${v.title} ${v.rise}`,"aria-label":`View details for ${a.title}`,tabIndex:b===I?0:-1,children:a.title}),a.metaItems.length>0&&e("div",{className:`${v.metaRow} ${v.rise}`,children:a.metaItems.map((T,W)=>e(q.Fragment,{children:[e("span",{className:v.metaItem,children:T}),W<a.metaItems.length-1&&e("div",{className:v.metaDivider})]},W))}),a.tags.length>0&&e("div",{className:`${v.genres} ${v.rise}`,children:a.tags.slice(0,3).map(T=>e("span",{className:v.genreTag,children:T},T))}),a.synopsis&&e("p",{className:`${v.summary} ${v.rise}`,children:a.synopsis}),e("div",{className:`${v.actions} ${v.rise}`,children:[e("button",{className:v.watchBtn,onClick:a.onPrimary,tabIndex:b===I?0:-1,children:[e(E,{name:a.primaryIcon,size:14}),e("span",{children:a.primaryLabel})]}),e("div",{className:v.secondaryRow,children:[e("button",{className:v.detailsBtn,onClick:a.onDetails,tabIndex:b===I?0:-1,children:[e(E,{name:"info-circle",size:15}),e("span",{children:"Details"})]}),a.onWatchlist&&e("button",{className:v.secondaryBtn,onClick:a.onWatchlist,tabIndex:b===I?0:-1,children:[e(E,{name:"plus",size:14}),e("span",{children:"Watchlist"})]})]})]})]})]})},a.key))})}),n.length>1&&e(se,{children:[e("button",{className:`${v.navArrow} ${v.prevArrow}`,onClick:()=>{R(),V()},"aria-label":"Previous slide",children:e(E,{name:"chevron-left",size:20})}),e("button",{className:`${v.navArrow} ${v.nextArrow}`,onClick:()=>{R(),L()},"aria-label":"Next slide",children:e(E,{name:"chevron-right",size:20})})]})]})})},Nn=({animeList:n})=>{const{titlePreference:l}=Ve(),h=ee(),t=Q(()=>n.slice(0,6).map(o=>{const i=l==="nativeName"?o.nativeName||o.name:l==="englishName"&&o.englishName||o.name;return{key:o._id,bannerSrc:o.bannerImage?Ne(o.bannerImage,1280,560):Ne(o.thumbnail,1280,450),posterSrc:Ne(o.thumbnail,460,650),posterAlt:i,title:i,detailTo:`/anime/${o._id}`,score:o.score,metaItems:[o.type||"Anime",o.status,o.episodeCount?`${o.episodeCount} Episodes`:void 0,o.rating].filter(p=>!!p),tags:(o.genres??[]).slice(0,3).map(p=>typeof p=="string"?p:p?.name).filter(p=>!!p),synopsis:rt(o.description??""),primaryLabel:"Watch Now",primaryIcon:"play",onPrimary:()=>h(`/watch/${o._id}`),onDetails:()=>h(`/anime/${o._id}`)}}),[n,l,h]);return e(_e,{slides:t})},wn="_emptyState_19tmt_1",Sn="_emptyStateIcon_19tmt_16",kn="_emptyStateTitle_19tmt_23",Cn="_emptyStateText_19tmt_30",he={emptyState:wn,emptyStateIcon:Sn,emptyStateTitle:kn,emptyStateText:Cn},ye=({icon:n,text:l,actionLabel:h,onAction:t,title:o="Nothing is here..."})=>e("div",{className:he.emptyState,children:[e(E,{name:n,size:48,className:he.emptyStateIcon}),e("div",{children:[e("h3",{className:he.emptyStateTitle,children:o}),e("p",{className:he.emptyStateText,children:l})]}),e(Fe,{variant:"primary",size:"sm",onClick:t,style:{marginTop:"1rem"},children:h})]}),In="_tabBar_1mv4x_1",Rn="_tabIndicator_1mv4x_24",An="_tabButton_1mv4x_38",Ln="_tabActive_1mv4x_53",me={tabBar:In,tabIndicator:Rn,tabButton:An,tabActive:Ln};function $n({options:n,value:l,onChange:h,ariaLabel:t},o){const i=F(null),p=F(new Map),s=F(null),[S,y]=B({left:0,width:0}),N=P((m,c)=>{const r=p.current.get(m),w=i.current;if(r&&w){const C=w.getBoundingClientRect(),k=r.getBoundingClientRect();y({left:k.left-C.left+w.scrollLeft,width:k.width}),c&&r.scrollIntoView({block:"nearest",inline:"nearest"})}},[]);return et(()=>{const m=s.current!==null&&s.current!==l;s.current=l,N(l,m)},[l,n.length,N]),x(()=>{if(N(l,!1),typeof ResizeObserver>"u")return;let m=0;const c=i.current;if(!c)return;const r=new ResizeObserver(()=>{cancelAnimationFrame(m),m=requestAnimationFrame(()=>N(l,!1))});r.observe(c);let w=!1;return document.fonts?.ready&&document.fonts.ready.then(()=>{w||N(l,!1)}),()=>{w=!0,cancelAnimationFrame(m),r.disconnect()}},[l,n.length,N]),e("div",{className:me.tabBar,ref:m=>{i.current=m,typeof o=="function"?o(m):o&&(o.current=m)},"aria-label":t,children:[e("div",{className:me.tabIndicator,style:{left:S.left,width:S.width}}),n.map(m=>e(Fe,{ref:c=>{c&&p.current.set(m.value,c)},variant:"secondary",size:"sm",className:`${me.tabButton} ${l===m.value?me.tabActive:""}`,onClick:()=>h(m.value),children:m.label},m.value))]})}const ge=q.forwardRef($n),Mn=[{value:"popular",label:"Popular"},{value:"followed",label:"Most Followed"},{value:"rating",label:"Top Rated"}],Ee=({title:n,eyebrow:l,sort:h,mature:t,headerActions:o})=>{const{toggle:i,bookmarkedIds:p}=Ye(),{popup:s,openPopup:S,scheduleClose:y,cancelClose:N,closePopup:m}=qe(),{data:c,isLoading:r,fetchNextPage:w,hasNextPage:C,isFetchingNextPage:k}=st({provider:"",query:"",sort:h,status:"",type:"",rating:t?"safe,suggestive,erotica,pornographic":"safe",mature:t}),d=Q(()=>c?.pages.flatMap(u=>u.items)??[],[c]),g=P(()=>{C&&!k&&!r&&w()},[C,k,r,w]);return e(se,{children:[e(Z,{title:n,eyebrow:l,loading:r,carousel:!0,itemCount:d.length,headerActions:o,onReachThreshold:g,isFetchingNextPage:k,loadingSkeleton:e("div",{className:"skeleton",style:{aspectRatio:"3 / 4"}}),skeletonCount:7,children:d.map(u=>{const f=Se(u.provider,u.id);return e(pe,{item:{id:f,title:u.title,...Xe(u),thumbnail:Ce(u.provider,u.cover),typeBadge:u.type||void 0,chapterBadge:u.latestChapter?`Ch. ${u.latestChapter}`:null,isAdult:He(u)},linkTo:`/manga/${u.provider}/${encodeURIComponent(u.id)}`,hoverIcon:"info",showInfoButton:!0,display:{elements:{poster:{typeBadge:!0,chapterBadge:!0,adultBadge:!0},info:{title:!0,mobileBadges:!0,progress:!1,meta:!1}}},onOpenDetails:R=>S(R,{provider:u.provider,mangaId:u.id,title:u.title,altTitle:u.altTitle,cover:u.cover,contentRating:u.contentRating,readTarget:`/manga/${u.provider}/${encodeURIComponent(u.id)}`,mature:t}),onPopupHoverIntent:R=>R?N():y(),rawThumbnail:!0},`${u.provider}-${u.id}`)})}),s&&e(Qe,{data:s.data,anchorRect:s.rect,bookmarked:p.has(Se(s.data.provider,s.data.mangaId)),onToggleBookmark:()=>i({id:s.data.mangaId,provider:s.data.provider,title:s.data.title,cover:s.data.cover,altTitle:s.data.altTitle??void 0,contentRating:s.data.contentRating}),onMouseEnter:N,onMouseLeave:y,onRequestClose:m})]})},Bn=()=>{const{options:n}=Mt(),l=Q(()=>n.some(s=>s.kind==="manga"),[n]),{hasConsent:h}=ot(),[t,o]=ie("manga_discover_tab","latest"),[i,p]=ie("manga_trending_sort","popular");return l?e(se,{children:[e(ge,{ariaLabel:"Discover manga",options:[{value:"latest",label:"Latest Releases"},{value:"trending",label:"Trending"}],value:t,onChange:o}),t==="latest"?e(Ee,{title:"Latest Releases",eyebrow:"Fresh chapters",sort:"latest",mature:h}):e(Ee,{title:"Trending",eyebrow:"Discover",sort:i,mature:h,headerActions:e("select",{className:M["header-select"],value:i,onChange:s=>p(s.currentTarget.value),"aria-label":"Trending sort",children:Mn.map(s=>e("option",{value:s.value,children:s.label},s.value))})})]}):null},xn=()=>{const n=ee(),{data:l,isLoading:h}=$t(24),[t,o]=B(null),{popup:i,openPopup:p,scheduleClose:s,cancelClose:S,closePopup:y}=qe(),{toggle:N,bookmarkedIds:m}=Ye(),c=l?.data??[];return e("div",{style:{paddingBottom:"2rem"},children:[e(Z,{title:"Continue Reading",eyebrow:"Pick up where you left off",titleLink:"/reading-list/Continue Reading",loading:h,carousel:!0,collapsible:!0,defaultExpanded:c.length>0,highlight:!0,itemCount:c.length,loadingSkeleton:e("div",{className:"skeleton",style:{aspectRatio:"3 / 4"}}),skeletonCount:7,emptyState:e(ye,{icon:"book",text:"You haven't read anything yet. Browse manga and open a chapter to start tracking.",actionLabel:"Browse Manga",onAction:()=>n("/manga")}),children:c.map(r=>{const w=r.page??0,C=r.pageCount??0,k=r.chapterId&&r.provider?`/manga/${r.provider}/${encodeURIComponent(r.mangaId)}/read?chapter=${encodeURIComponent(r.chapterId)}`:r.provider?`/manga/${r.provider}/${encodeURIComponent(r.mangaId)}`:"#";return e(pe,{item:{id:r.id,title:r.title||"",...Xe({title:r.title||"",altTitle:r.altTitle}),thumbnail:r.provider?Ce(r.provider,r.cover||""):r.cover||"",chapterBadge:r.chapterNumber?`Ch. ${r.chapterNumber}`:null,isAdult:He(r)},linkTo:k,hoverIcon:"book",progress:C>0?{percent:w/C*100,label:`Ch. ${r.chapterNumber} · p. ${w}/${C}`}:void 0,showProgress:!0,display:{elements:{poster:{typeBadge:!1,chapterBadge:!0,adultBadge:!0,removeButton:!0},info:{title:!0,mobileBadges:!0,progress:!0,meta:!1}}},onRemove:()=>o({libId:r.id,title:r.title||""}),onOpenDetails:d=>p(d,{provider:r.provider||"",mangaId:r.mangaId||"",title:r.title||"",altTitle:r.altTitle,cover:r.cover||"",contentRating:r.contentRating||void 0,readTarget:k}),onPopupHoverIntent:d=>d?S():s(),rawThumbnail:!0},r.id)})}),e(Lt,{mangaId:t?t.libId:null,title:t?.title,onClose:()=>o(null)}),i&&i.data.provider&&e(Qe,{data:i.data,anchorRect:i.rect,bookmarked:m.has(Se(i.data.provider,i.data.mangaId)),onToggleBookmark:()=>N({id:i.data.mangaId,provider:i.data.provider,title:i.data.title,cover:i.data.cover,altTitle:i.data.altTitle??void 0,contentRating:i.data.contentRating}),onMouseEnter:S,onMouseLeave:s,onRequestClose:y}),e(Bn,{})]})},Pn="_emptyState_bpz5x_1",De={emptyState:Pn},En=[{value:"latest",label:"Latest Releases"},{value:"trending",label:"Trending"}],Dn=[{value:"trending_week",label:"Trending Now"},{value:"trending_day",label:"Trending Today"},{value:"popular",label:"Popular All Time"},{value:"top_rated",label:"Top Rated"}],Wn=()=>{const n=ee(),{data:l,isLoading:h}=Pt(24),t=Et(),o=Dt(),[i,p]=B(null),[s,S]=B(()=>re.getItem("tv_home_activeTab")||"latest"),[y,N]=B("tv"),[m,c]=B("trending_week"),[r,w]=B("multi"),C=l?.data??[];q.useEffect(()=>{re.setItem("tv_home_activeTab",s)},[s]);const k=m.startsWith("trending_"),d=m==="trending_day"?"day":"week",g={popular:"popularity.desc",top_rated:"vote_average.desc"},{data:u,isLoading:f}=Ke(r==="multi"?"all":r,d,1,k&&s==="trending"),{data:R,isLoading:z}=Be({type:r,sort_by:g[m]||"popularity.desc",page:1}),A=k?u?.results||[]:R?.results||[],D=k?f:z,{data:L,isLoading:V}=Be({type:y,sort_by:"primary_release_date.desc",page:1}),j=L?.results||[],I=a=>{i&&(o.mutate({mediaId:i.libId}),a&&t.mutate(i.libId))},U=P(a=>e(Bt,{item:{id:a.id,title:a.title,year:a.year,type:a.type,image:a.image,vote_average:a.vote_average,adult:a.adult}},`${a.type}-${a.id}`),[]),H=()=>{switch(s){case"latest":return e(Z,{title:"Latest Releases",eyebrow:"Fresh picks",loading:V,carousel:!0,itemCount:j.length,headerActions:e(J,{ariaLabel:"Latest type",value:y,onChange:a=>N(a),options:[{value:"tv",label:"TV Shows"},{value:"movie",label:"Movies"}]}),loadingSkeleton:e("div",{className:"skeleton",style:{aspectRatio:"3 / 4",borderRadius:"var(--radius-lg)"}}),emptyState:e("div",{className:De.emptyState,children:e("p",{children:"No latest releases available right now."})}),children:j.map(U)});case"trending":return e(Z,{title:"Trending",eyebrow:"Discover",loading:D,carousel:!0,itemCount:A.length,headerActions:e(se,{children:[e(J,{ariaLabel:"Trending sort",value:m,onChange:c,options:Dn.map(a=>({value:a.value,label:a.label}))}),e(J,{ariaLabel:"Trending type",value:r,onChange:a=>w(a),options:[{value:"multi",label:"All"},{value:"tv",label:"TV Shows"},{value:"movie",label:"Movies"}]})]}),loadingSkeleton:e("div",{className:"skeleton",style:{aspectRatio:"3 / 4",borderRadius:"var(--radius-lg)"}}),emptyState:e("div",{className:De.emptyState,children:e("p",{children:"No trending content available right now."})}),children:A.map(U)})}};return e("div",{style:{paddingBottom:"2rem"},children:[e(Z,{title:"Continue Watching",eyebrow:"Pick up where you left off",titleLink:"/tv-watchlist/Continue Watching",loading:h,carousel:!0,collapsible:!0,defaultExpanded:C.length>0,highlight:!0,itemCount:C.length,loadingSkeleton:e("div",{className:"skeleton",style:{aspectRatio:"3 / 4"}}),skeletonCount:7,emptyState:e(ye,{icon:"tv",text:"You haven't watched anything yet. Search TV & Movies and start watching to track progress.",actionLabel:"Browse TV & Movies",onAction:()=>n("/tv-search")}),children:C.map(a=>{const b=a.currentTime??0,T=a.duration??0,W=a.season??1,X=a.episode??1,G=a.mediaType==="movie",K=G?"Movie":`S${W} E${X}`,te=a.completed===1||T>0&&b>=T*.8,ae=te?100:T>0&&b>0?b/T*100:0,be=te?"Watched":T>0?G?`${oe(b)} / ${oe(T)}`:`${K} · ${oe(b)} / ${oe(T)}`:K;return e(pe,{item:{id:a.id,title:a.title||"",thumbnail:a.poster||"",typeBadge:G?"Movie":"TV",chapterBadge:K,isAdult:it({adult:a.adult===1})},linkTo:lt(a.mediaType,a.tmdbId??0,G?void 0:W,G?void 0:X),hoverIcon:"play",progress:(T>0||te)&&ae>0?{percent:ae,label:be}:void 0,showProgress:!0,metaRow:a.year?e("span",{style:{opacity:.75},children:a.year}):void 0,onRemove:()=>p({libId:a.id,title:a.title||""}),renderPopup:(fe,le)=>e(xt,{item:{id:a.tmdbId??0,title:a.title||"",year:a.year||"",type:a.mediaType||"tv",image:a.poster||""},anchorRect:fe,onMouseEnter:le.onMouseEnter,onMouseLeave:le.onMouseLeave,onRequestClose:le.close})},a.id)})}),e(ge,{ariaLabel:"Browse TV",options:En,value:s,onChange:S}),e("div",{children:H()}),e(Ue,{isOpen:!!i,itemName:i?.title,progressKind:"watch",listLabel:"my TV watchlist",onClose:()=>{p(null)},onConfirm:I})]})};function We(n){const l=n.currentTime??0,h=n.duration??0,t=(n.trackIndex??0)+1;return h>0?`Track ${t} · ${oe(l)} / ${oe(h)}`:n.trackLabel?`Track ${t} · ${n.trackLabel}`:`Track ${t}`}const On=({title:n="Continue Listening",limit:l=24,titleLink:h,showEmptyState:t=!0})=>{const o=ee(),{data:i,isLoading:p}=Ot(l),{toggle:s,bookmarkedIds:S}=zt(),[y,N]=B(null),m=i?.data??[];return e(se,{children:[e(Z,{title:n,eyebrow:"Pick up where you left off",titleLink:h??"/listening-list/Continue Listening",loading:p,carousel:!0,collapsible:!0,defaultExpanded:m.length>0,highlight:!0,itemCount:m.length,loadingSkeleton:e("div",{className:"skeleton",style:{aspectRatio:"16 / 9"}}),skeletonCount:7,emptyState:t?e(ye,{icon:"headphones",text:"You haven't listened to anything yet. Browse ASMR and play a track to start tracking.",actionLabel:"Browse ASMR",onAction:()=>o("/asmr")}):void 0,children:m.map(c=>{const r=c.currentTime??0,w=c.duration??0,C=c.rjCode||c.id;return e(pe,{item:{id:c.id,title:c.title||"",thumbnail:c.thumbnail||"",chapterBadge:`Track ${(c.trackIndex??0)+1}`,isAdult:!!c.isAdult},linkTo:`/asmr/${encodeURIComponent(C)}`,hoverIcon:"play",layout:"horizontal",progress:w>0?{percent:Math.min(100,r/w*100),label:We(c)??""}:void 0,showProgress:!0,display:{elements:{poster:{typeBadge:!1,chapterBadge:!0,adultBadge:!0,removeButton:!0},info:{title:!0,mobileBadges:!0,progress:!0,meta:!1}}},onRemove:()=>N({workId:c.id,title:c.title||""}),renderPopup:(k,d)=>e(Vt,{data:{rjCode:c.rjCode||c.id,title:c.title||"",thumbnail:c.thumbnail||"",isAdult:!!c.isAdult,listenTarget:`/asmr/${encodeURIComponent(c.rjCode||c.id)}`,progressLabel:We(c)},anchorRect:k,bookmarked:S.has(Ft(c.rjCode||c.id)),onToggleBookmark:()=>s({rjCode:c.rjCode||c.id,title:c.title||"",thumbnail:c.thumbnail||"",isAdult:!!c.isAdult}),onMouseEnter:d.onMouseEnter,onMouseLeave:d.onMouseLeave,onRequestClose:d.close}),rawThumbnail:!0},c.id)})}),e(Wt,{workId:y?y.workId:null,title:y?.title,onClose:()=>N(null)})]})},zn=()=>e("div",{style:{paddingBottom:"2rem"},children:e(On,{})}),Vn=({items:n})=>{const l=ee(),h=Q(()=>n.slice(0,6).map(t=>{const o=ct(t.type,t.id);return{key:String(t.id),bannerSrc:t.backdrop?t.backdrop:t.image,posterSrc:t.image,posterAlt:t.title,title:t.title,detailTo:o,score:t.vote_average>0?Number(t.vote_average).toFixed(1):null,metaItems:[t.type==="tv"?"TV Show":"Movie",t.year].filter(Boolean),tags:t.genre_ids.slice(0,3).map(i=>dt[i]??ut[i]).filter(Boolean),synopsis:Ie(t.overview,200),primaryLabel:"Watch Now",primaryIcon:"play",onPrimary:()=>l(o),onDetails:()=>l(o)}}),[n,l]);return e(_e,{slides:h,eyebrow:"TV Spotlight"})},Fn=({mangaList:n})=>{const l=ee(),h=Q(()=>n.slice(0,6).map(t=>{const o=`/manga/${t.provider||"mangadex"}/${t.id}`,i=Ce(t.provider||"mangadex",t.cover||"");return{key:`${t.provider}-${t.id}`,bannerSrc:i,posterSrc:i,posterAlt:t.title,title:t.title,detailTo:o,metaItems:[t.year?String(t.year):void 0,t.status??void 0].filter(p=>!!p),tags:t.tags.slice(0,3),synopsis:Ie(t.description,200,""),primaryLabel:"Read Now",primaryIcon:"book",onPrimary:()=>l(o),onDetails:()=>l(o)}}),[n,l]);return e(_e,{slides:h,eyebrow:"Manga Spotlight"})};function jn(n){const l=n.availableEpisodes?.sub;if(typeof l=="number"&&l>0)return l;const h=n.availableEpisodesDetail?.sub,t=n.availableEpisodesDetail?.dub,o=(Array.isArray(h)?h.length:0)+(Array.isArray(t)?t.length:0);return o>0?o:null}const Gn=({works:n})=>{const l=ee(),h=Q(()=>n.slice(0,6).map((t,o)=>{const i=ht(t),p=`/asmr/${encodeURIComponent(i)}`,s=jn(t);return{key:i||t._id||String(o),bannerSrc:t.thumbnail||"",posterSrc:t.thumbnail||"",posterAlt:t.name,title:t.name,detailTo:p,metaItems:[t.rating?t.rating.toUpperCase():void 0,s?`${s} track${s===1?"":"s"}`:void 0].filter(S=>!!S),tags:[],synopsis:Ie(t.description,160,""),primaryLabel:"Listen Now",primaryIcon:"play",onPrimary:()=>l(p),onDetails:()=>l(p)}}),[n,l]);return e(_e,{slides:h,eyebrow:"ASMR Spotlight",posterAspect:"landscape"})},Un="_seasonSection_6ckjf_34",qn="_seasonGrid_6ckjf_38",ne={"section-header":"_section-header_6ckjf_1","content-type-nav":"_content-type-nav_6ckjf_8","title-wrapper":"_title-wrapper_6ckjf_18","pagination-controls":"_pagination-controls_6ckjf_24",seasonSection:Un,seasonGrid:qn},Qn=[{value:"anime",label:"Anime"},{value:"manga",label:"Manga"},{value:"tv",label:"TV & Movies"},{value:"asmr",label:"ASMR"}],Tr=()=>{const n=kt(),l=mt(),[h,t]=q.useState(1),[o,i]=B(()=>re.getItem("home_activeTab")||"latest"),[p,s]=B(()=>re.getItem("season_format")||"TV"),S=F(null),{data:y}=Me(h+1,p,o==="season"),{titlePreference:N}=Ve(),{contentType:m,setContentType:c}=gt(),[r,w]=q.useState(null),C=pt(),{data:k=[]}=vt(),d=_t(),g=yt(),u=bt();x(()=>{document.title="Home - dango"},[]);const{data:f,isLoading:R}=ft();x(()=>{re.setItem("home_activeTab",o)},[o]),x(()=>{re.setItem("season_format",p),t(1)},[p]),x(()=>{f!==void 0&&f.length===0&&o==="week"&&i("latest")},[f,o]);const{data:z,isLoading:A,fetchNextPage:D,hasNextPage:L,isFetchingNextPage:V}=Tt(),j=P(()=>{L&&!V&&!A&&D()},[L,V,A,D]),{data:I,isLoading:U}=Nt(),{data:H,isLoading:a}=Ke("all","week",1,m==="tv"),{data:b,isLoading:T}=jt(m==="asmr"),{data:W,isLoading:X}=wt(),G=Q(()=>z?.pages||[],[z]),{data:K,isLoading:te}=Me(h,p,o==="season"),ae=14,be=K&&K.length>=ae&&y&&y.length>0,fe=Ct(l.continueWatching.remove.mutationOptions({onSuccess:async()=>{n.invalidateQueries(l.continueWatching.pathFilter()),await n.invalidateQueries({queryKey:[ze.continueWatching]}),L&&G.length-1<14&&D()}})),le=P(O=>{const Y=G?.find(Te=>String(Te.id)===String(O));if(Y){const Te=Y[N]||Y.name;w({id:O,name:Te})}},[G,N]),Ae=[{key:"latest",label:"Latest Releases"},{key:"season",label:"Current Season"},{key:"popular",label:"Trending"}],Le=f!==void 0&&f.length>0,Ze=Le?[{key:"week",label:"This Week"},...Ae]:Ae,$e=o==="week"&&!Le?"latest":o,Je=()=>{switch($e){case"latest":return e(pa,{eyebrow:"Fresh episodes"});case"season":return e("section",{className:ne.seasonSection,children:[e("div",{className:ne["section-header"],ref:S,children:[e("div",{className:ne["title-wrapper"],children:e("div",{className:"title-stack",children:[e("div",{className:"section-eyebrow",children:"This season"}),e("div",{className:"section-title",style:{marginBottom:0},children:"Current Season"})]})}),e("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[e(J,{ariaLabel:"Season format",width:90,value:p,onChange:s,options:[{value:"TV",label:"TV"},{value:"ONA",label:"ONA"},{value:"OVA",label:"OVA"},{value:"MOVIE",label:"Movie"},{value:"ALL",label:"All"},{value:"ADULT",label:"Mature"}]}),e("div",{className:ne["pagination-controls"],children:e(It,{page:h,canGoNext:be,onChange:O=>{if(t(O),S.current){const Y=S.current.getBoundingClientRect().top+window.scrollY-120;window.scrollTo({top:Y,behavior:"smooth"})}},isLoading:te})})]})]}),e("div",{className:`grid-container ${ne.seasonGrid}`,style:{minHeight:"300px",alignContent:"start"},children:te?e(je,{count:ae}):K?.slice(0,ae).map(O=>e(ce,{anime:O},O._id))})]});case"popular":return e(ha,{title:"Trending",eyebrow:"Discover"});case"week":return e(xe,{title:"This Week",eyebrow:"Aired this week",animeList:f||[],continueWatching:!1,episodeBadge:!0,carousel:!0,loading:R});default:return null}};return e("div",{style:{paddingBottom:"2rem"},children:[m==="anime"&&(U&&!I?.length?e(ue,{}):I&&I.length>0&&e(Nn,{animeList:I})),m==="tv"&&(a&&!H?.results?.length?e(ue,{}):H?.results&&H.results.length>0&&e(Vn,{items:H.results})),m==="manga"&&(X&&!W?.length?e(ue,{}):W&&W.length>0&&e(Fn,{mangaList:W})),m==="asmr"&&(T&&!b?.length?e(ue,{}):b&&b.length>0&&e(Gn,{works:b})),e("div",{className:ne["content-type-nav"],children:e(ge,{ariaLabel:"Content type",options:Qn,value:m,onChange:c})}),m==="manga"?e(xn,{}):m==="tv"?e(Wn,{}):m==="asmr"?e(zn,{}):e(se,{children:[e(xe,{title:"Continue Watching",eyebrow:"Pick up where you left off",titleLink:"/watchlist/Continue Watching",animeList:G,continueWatching:!0,carousel:!0,collapsible:!0,defaultExpanded:G.length>0,onRemove:le,loading:A,onReachThreshold:j,scrollThreshold:.7,isFetchingNextPage:V,emptyState:e(ye,{icon:"history",text:"You haven't watched anything yet. Start exploring and watch something first!",actionLabel:"Explore Trending",onAction:()=>i("popular")})}),e(At,{title:"Queue",eyebrow:"Up next",items:k,onRemove:O=>d.mutate({showId:O.showId,episodeNumber:O.episodeNumber}),showClearAll:!0,onClear:()=>g.mutate(),onReorder:O=>u.mutate(O.map(Y=>({id:Y.id,showId:Y.showId,episodeNumber:Y.episodeNumber})))}),e(ge,{ariaLabel:"Browse anime",options:Ze.map(O=>({value:O.key,label:O.label})),value:$e,onChange:i}),e("div",{children:Je()}),e(Ea,{eyebrow:"Never miss an episode"}),e(Ue,{isOpen:!!r,itemName:r?.name,progressKind:"watch",listLabel:"my watchlist",onClose:()=>{w(null)},onConfirm:O=>{r&&(fe.mutate({showId:r.id}),O&&C.mutate({id:r.id}))}})]})]})};export{Tr as default};
|