@serifpersia/dango 3.8.7 → 3.8.9
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-DeOILoQY.js → AnimeCard-DrSVvS_S.js} +1 -1
- package/client/dist/assets/{AnimeInfo-CEWjWNK4.js → AnimeInfo-D0vHYtBM.js} +1 -1
- package/client/dist/assets/{AnimeInfoPage-BBB8hD_-.js → AnimeInfoPage-BWibeLB6.js} +2 -2
- package/client/dist/assets/{Asmr-BJjmJorV.js → Asmr-BEXvABMt.js} +1 -1
- package/client/dist/assets/{AsmrPopup-BW-iFW3L.js → AsmrPopup-Cew16o-s.js} +1 -1
- package/client/dist/assets/{AsmrResetProgressModal-BAp7wa4X.js → AsmrResetProgressModal-C7xQiadp.js} +1 -1
- package/client/dist/assets/Home-B5pAkvRG.js +1 -0
- package/client/dist/assets/{Home-grKghNM9.css → Home-ujV6ObHi.css} +1 -1
- package/client/dist/assets/{Insights-D3-riQFt.js → Insights-BRCgYmWi.js} +1 -1
- package/client/dist/assets/{LibraryListPage-CKEWlzgR.js → LibraryListPage-rbFrP8AU.js} +1 -1
- package/client/dist/assets/{ListeningList-WhGQuOYx.js → ListeningList-C5wWr4II.js} +1 -1
- package/client/dist/assets/{Manga-XJEPnce1.js → Manga-C1yiScAz.js} +1 -1
- package/client/dist/assets/{MangaInfoPage-B3xV4o8C.js → MangaInfoPage-Ce0v7YXA.js} +1 -1
- package/client/dist/assets/{MangaReadPage-BdmcONww.js → MangaReadPage-BC9zFplq.js} +1 -1
- package/client/dist/assets/{MangaResetProgressModal-C1Bfn9O_.js → MangaResetProgressModal-C7Dcvjh7.js} +1 -1
- package/client/dist/assets/{Mature-VH_PWwEN.js → Mature-DtqYOqXU.js} +1 -1
- package/client/dist/assets/{MatureConsentModal-Do1CtwDw.js → MatureConsentModal-rgNaRRTN.js} +1 -1
- package/client/dist/assets/{MediaCard-BikTKuG3.js → MediaCard-CHoNwTm1.js} +1 -1
- package/client/dist/assets/{OptionListMenu-BReFoLC2.js → OptionListMenu-Bff1pUmQ.js} +1 -1
- package/client/dist/assets/{Player-CUTDxVY5.js → Player-DIVG2848.js} +2 -2
- package/client/dist/assets/{PlayerProvider-D60eCjik.js → PlayerProvider-DJzS5Axp.js} +1 -1
- package/client/dist/assets/{PlayerSettings-C2pu0sQt.js → PlayerSettings-CK78X3rR.js} +1 -1
- package/client/dist/assets/{QueueOptionsButton-CUyJPdwg.js → QueueOptionsButton-Cl2642YU.js} +1 -1
- package/client/dist/assets/{QueueRail-DqyZVaD-.js → QueueRail-DwQDZ_XG.js} +1 -1
- package/client/dist/assets/{ReadingList-BXR1JrJ_.js → ReadingList-DlbXml2-.js} +1 -1
- package/client/dist/assets/{ResetProgressModal-YVCqneQ5.js → ResetProgressModal-DAErKwey.js} +1 -1
- package/client/dist/assets/{Search-C27b6qOV.js → Search-CIKq5G-z.js} +1 -1
- package/client/dist/assets/{Settings-DEWZN-A-.js → Settings-DRwq3zlT.js} +1 -1
- package/client/dist/assets/{SkeletonGrid-BpsynMj7.js → SkeletonGrid-M1g3xkeh.js} +1 -1
- package/client/dist/assets/{Trackers-B3EMJMgo.js → Trackers-BQ1gMcBW.js} +1 -1
- package/client/dist/assets/{Tv-BfDkrKuI.js → Tv-BTYVOvyH.js} +1 -1
- package/client/dist/assets/{TvInfo-BkABl1xJ.js → TvInfo-6znmxCqw.js} +1 -1
- package/client/dist/assets/{TvPopup-RchqnXJt.js → TvPopup-UKd0aKWm.js} +1 -1
- package/client/dist/assets/{TvSearch-C9oRGjgC.js → TvSearch-BWJrtULY.js} +1 -1
- package/client/dist/assets/{TvWatchlist-ClRCXsXi.js → TvWatchlist-D8jWKOKv.js} +1 -1
- package/client/dist/assets/{VirtualKeyboard-C0Yf-_br.js → VirtualKeyboard-D1u3DQoA.js} +1 -1
- package/client/dist/assets/{WatchAlong-CIBT0VHg.js → WatchAlong-D6n1LExO.js} +1 -1
- package/client/dist/assets/{WatchAlongPanel-D87h_8qM.js → WatchAlongPanel-B2bTYI7S.js} +1 -1
- package/client/dist/assets/{Watchlist-1rn0IRne.js → Watchlist-B8C9o6d8.js} +1 -1
- package/client/dist/assets/index-Cm_HHHID.js +178 -0
- package/client/dist/assets/index-RwPVmyxh.css +1 -0
- package/client/dist/assets/{libraryInvalidation-BHknhNAw.js → libraryInvalidation-DGehx23C.js} +1 -1
- package/client/dist/assets/{playbackCompletion-ZhAwimeL.js → playbackCompletion-CXC4JK-B.js} +1 -1
- package/client/dist/assets/{useAnimeInfoData-l7nCKCe5.js → useAnimeInfoData-D-mV_H44.js} +1 -1
- package/client/dist/assets/{useMangaLibrary-DAPvo2xZ.js → useMangaLibrary-DaYUfUQF.js} +1 -1
- package/client/dist/assets/{useMangaPopup-B5LPCa2N.js → useMangaPopup-B9f7xCrw.js} +1 -1
- package/client/dist/assets/{useProviders-DsY_iifL.js → useProviders-CeVxWJvx.js} +1 -1
- package/client/dist/assets/{useTv-olJK7WfQ.js → useTv-CE8cK_Di.js} +1 -1
- package/client/dist/assets/{useTvLibrary-Deie_gJF.js → useTvLibrary-Cx4wzWcB.js} +1 -1
- package/client/dist/assets/{useWatchAlongPlayer-cl8kIOvd.js → useWatchAlongPlayer-BBcOZEFU.js} +1 -1
- package/client/dist/index.html +2 -2
- package/package.json +2 -2
- package/server/dist/server.js +1 -1
- package/server/package.json +1 -1
- package/client/dist/assets/Home-BqE0OcxM.js +0 -1
- package/client/dist/assets/index-Cd1-bH35.js +0 -178
- package/client/dist/assets/index-Ej7BS74s.css +0 -1
package/server/dist/server.js
CHANGED
|
@@ -466,7 +466,7 @@ ${u}
|
|
|
466
466
|
}
|
|
467
467
|
}
|
|
468
468
|
`,y=t?.toLowerCase().replace(/[^a-z0-9]/g,""),x=t?.trim()?fB(t).filter(Be=>Be.toLowerCase().replace(/[^a-z0-9]/g,"")===y):[""],M=new Map,O=null,W=!1;for(let[Be,Ne]of x.entries()){if(O=await ur(S,{...C,...Ne?{search:Ne}:{}}),!O?.data)break;for(let X of O.data.Page.media??[])X.id&&M.set(X.id,X);if(Be>0&&(W=!0),(O.data.Page.media?.length??0)>=n)break}if(!O?.data&&M.size===0){if(Ui()){let Ne=await _f(async()=>{let j=Wr(),z=await Qd(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:h,averageScore_greater:g,episodes_greater:p,isAdult:i==="ADULT"?!0:m,sort:I});if(z.length>0)try{let Ie=await Qd(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},()=>ya({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:h,averageScore_greater:g,episodes_greater:p,isAdult:i==="ADULT"?!0:m,sort:I}));try{await gD(Wr(),Ne)}catch{}let X=tae(Ne);if(X.length===0&&t?.trim())try{let z=(await wB(Wr(),t,r)).entries.map(Ie=>Bd(Ie));try{await gD(Wr(),z)}catch{}X=z.map(Ie=>Er(Ie))}catch{}return X}return[]}let ee=[...M.values()];if(!ee||ee.length===0)return[];W&&ee.sort((Be,Ne)=>{let X=j=>Math.max(0,...[j.title?.romaji,j.title?.english,j.title?.native].filter(z=>!!z).map(z=>Rc([{title:z}],[t??""])?.score??0));return X(Ne)-X(Be)});let Ae=new Set,fe=[];for(let Be of ee)!Be.id||Ae.has(Be.id)||(Ae.add(Be.id),fe.push(Er(Be)));return fe.slice(0,n)}function F8(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 lae=/^[a-z0-9][a-z0-9-]*$/i,Z$e=/^[0-9a-f]{64}$/i,dae=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function hae(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 DB(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)=>eKe(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 eKe(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"||!lae.test(n.trim()))throw new Error(`registry.providers[${t}].id must match ${lae}`);if(typeof s!="string"||!s.trim())throw new Error(`registry.providers[${t}].label must be a non-empty string`);if(typeof o!="string"||!dae.test(o.trim()))throw new Error(`registry.providers[${t}].version must be major.minor.patch`);if(r.minDango!==void 0&&(typeof r.minDango!="string"||!dae.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"||!Z$e.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:rKe(r.browse,t),proxy:tKe(r.proxy,t),auth:r.auth==="cookie"?"cookie":void 0,enabledByDefault:r.enabledByDefault!==!1}}function tKe(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 rKe(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,fae=JSON.parse(Oi.readFileSync(as.join(Pn.PACKAGE_ROOT,"package.json"),"utf8")).version;async function ID(e,t){let r=`${e}.${yD.randomUUID()}.tmp`;try{await Oi.promises.writeFile(r,t),await Oi.promises.rename(r,e)}finally{await Oi.promises.rm(r,{force:!0})}}var RB="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";function xB(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 vB(e){return/^https?:\/\//i.test(e)}function _8(e){return e.startsWith("file://")?iKe(e):e}function aKe(e){return vB(e)||e.startsWith("file://")?!1:e.includes("/")||e.includes("\\")||e.endsWith(".json")}async function AKe(e){if(vB(e)){let r=await xB(fetch(e,{headers:{"User-Agent":RB,Accept:"application/json"}}),QD,"registry fetch");if(!r.ok)throw new Error(`registry HTTP ${r.status}: ${e}`);return Sl(Buffer.from(await r.arrayBuffer()))}let t=as.resolve(_8(e));return await Oi.promises.readFile(t)}async function uKe(e){if(vB(e)){let r=await xB(fetch(e,{headers:{"User-Agent":RB,Accept:"text/javascript,*/*"}}),QD,"provider fetch");if(!r.ok)throw new Error(`provider HTTP ${r.status}: ${e}`);return Sl(Buffer.from(await r.arrayBuffer()))}let t=as.resolve(_8(e));return await Oi.promises.readFile(t)}function cKe(e,t){let r=(e??"").trim();if(vB(r)||r.startsWith("file://"))return r;if(vB(t))return new URL(r,t).href;let n=as.dirname(as.resolve(_8(t)));return as.resolve(n,r)}function CD(e){return yD.createHash("sha256").update(e).digest("hex")}function lKe(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=yD.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 gae(e,t){let r=["-sSL","-A",RB,...Object.entries(t??{}).flatMap(([o,a])=>["-H",`${o}: ${a}`]),"--max-time","15","-w",`
|
|
469
|
-
__HTTP_STATUS__%{http_code}`,"--",e],n;try{n=nKe("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)=>xB(fetch(r,{...n,headers:{"User-Agent":RB,...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)=>{_.info(r,n)},warn:(r,n)=>{_.warn(r,n)},error:(r,n)=>{_.error(r,n)},debug:(r,n)=>{_.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 Kt(i)},proxyUrl:(r,n)=>`/api/proxy?url=${encodeURIComponent(r)}&referer=${encodeURIComponent(n)}`,userAgent:RB,titleMatch:{buildQueryVariants:fB,pickBestMatch:Rc},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 fB(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=Rc(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:IB},tmdb:{base:wo,image:bd,get:async r=>{try{let n=await Lc(),i=r.includes("?")?"&":"?",s=await t(`${wo}${r}${i}api_key=${n}`);return s.ok?Kt(s):null}catch{return null}}},request:{get:r=>ZT.getStore()?.get(r)},cookies:{sanitizeCfClearance:Lp,buildCfClearanceCookie:hu},crypto:{aes256CbcDecryptJson:lKe,hmacSha256Base64Url:(r,n)=>yD.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 oKe({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=gae(r,n);return!i||i.status!==200?null:JSON.parse(i.body)}catch{return null}},getText:async(r,n)=>{let i=gae(r,n);return!i||i.status!==200?null:i.body}},cheerio:{load:r=>B2(r)}}}function O8(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.name=="string"?t:null}function Cae(e,t){return t.every(r=>typeof e[r]=="function")}function Bae(e){let t=O8(e);return!!t&&Cae(t,["search","getEpisodes","getStreamUrls"])}function yae(e){let t=O8(e);return!!t&&Cae(t,["search","getDetail","getChapters","getPages"])}function Qae(e){let t=O8(e);return!!t&&(typeof t.getSources=="function"||typeof t.getEmbedUrl=="function")}function hKe(e,t){return e==="manga"?yae(t):e==="tv"?Qae(t):e==="asmr"?F8(t):Bae(t)}function pae(e,t,r,n){return t.kind==="manga"?yae(n)?(e.mangaProviders[r]=n,!0):!1:t.kind==="tv"?Qae(n)?(e.tvProviders[r]=n,!0):!1:t.kind==="asmr"?F8(n)?(e.asmrProviders[r]=n,!0):!1:Bae(n)?(e.providers[r]=n,!0):!1}function fKe(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 U8(e,t,r,n,i){if(e.minDango&&!hae(fae,e.minDango))return{provider:null,error:`requires dango ${e.minDango}, running ${fae}`};if(e.embedBase)return{provider:fKe(e.id,e.embedBase)};let s=cKe(e.entry,t);await Oi.promises.mkdir(r,{recursive:!0});let o=NB(e),a=as.join(r,o),A=`${a}:${e.kind??"anime"}`,u=null;try{let d=await Oi.promises.readFile(a);(e.sha256&&CD(d)===e.sha256||!e.sha256&&i)&&(u=d)}catch{}if(u){let d=BD.get(A);if(d)return _.debug({provider:e.id,version:e.version},"remote provider reused cached instance"),{provider:d.provider,facets:d.facets}}else{try{u=await uKe(s)}catch(d){return{provider:null,error:`download failed: ${d.message}`}}if(e.sha256){if(CD(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 ID(a,u)}let c=`${e.version}-${e.sha256??"nosha"}`,l=await pKe(a,c,n,e);return l.provider&&!l.error&&BD.set(A,{provider:l.provider,facets:l.facets}),l}var BD=new Map;function NB(e){return`${e.id}-${e.version}-${e.sha256??"nosha"}.mjs`}function gKe(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 pKe(e,t,r,n){let i=n.id,s;try{let A=`${sKe(e).href}?v=${encodeURIComponent(t)}`;s=await xB(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 xB(Promise.resolve(o(r)),1e4,`factory ${i}`)}catch(A){return{provider:null,error:`factory failed: ${A.message}`}}return hKe(n.kind,a)?{provider:a,facets:gKe(s)}:{provider:null,error:"invalid provider shape"}}async function EKe(e,t,r){if(e.embedBase)return U8(e,"",t,r,!1);if(!e.sha256)return{provider:null,error:"no verified fallback"};let n=as.join(t,NB(e)),i;try{i=await Oi.promises.readFile(n)}catch{return{provider:null,error:"no cached fallback file"}}return CD(i)!==e.sha256?{provider:null,error:"cached fallback failed verification"}:U8(e,"",t,r,!1)}var Eae;function bae(e){return Eae??=mKe(e).finally(()=>{Eae=void 0})}async function mKe(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=DB(JSON.parse(await Oi.promises.readFile(s,"utf8")))}catch{try{o=DB(JSON.parse(await Oi.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 Oi.promises.readFile(g);CD(p)===f.sha256&&await ID(as.join(n,NB(f)),p)}catch{}}}catch{}}let a=new Map((o?.providers??[]).map(f=>[f.id.toLowerCase(),f])),A;try{let f=await AKe(t);A=DB(JSON.parse(f.toString("utf8")))}catch(f){_.error({err:f,registryUrl:t},"remote providers: manifest fetch failed, trying disk cache");try{A=DB(JSON.parse(await Oi.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,d=dKe(e.cache),h=e.allowUnsigned??(process.env.DANGO_ALLOW_UNSIGNED_PROVIDERS==="1"||aKe(t));for(let f of A.providers){let g=f.id.toLowerCase();if(f.enabledByDefault===!1&&(!l||!c.has(g))){r.catalog.push(Gp(f,!1,"disabled by default"));continue}if(l&&!c.has(g)){r.catalog.push(Gp(f,!1,"not in enabledProviders"));continue}let{provider:p,facets:m,error:I}=await U8(f,t,n,d,h);if(p&&!I){if(!pae(r,f,g,p)){r.catalog.push(Gp(f,!1,"invalid provider shape for kind")),_.warn({provider:f.id},"remote provider kind mismatch, skipped");continue}r.catalog.push(Iae(m,mae(f,p,Gp(f,!0)))),u.push(f),f.proxy&&r.proxyRules.push(f.proxy),_.info({provider:f.id,version:f.version},"remote provider loaded")}else{let C=a.get(g);if(C){let B=await EKe(C,n,d);if(B.provider&&!B.error&&(pae(r,C,g,B.provider)||(B.error="cached fallback failed validation")),B.provider&&!B.error){r.catalog.push({...Iae(B.facets,mae(C,B.provider,Gp(C,!0))),error:`serving cached ${C.version}: ${I}`}),u.push(C),C.proxy&&r.proxyRules.push(C.proxy),_.warn({provider:f.id,error:I,fallback:C.version},"remote provider update failed, serving cached version");continue}}r.catalog.push(Gp(f,!1,I)),C&&u.push(C),f.proxy&&r.proxyRules.push(f.proxy),_.warn({provider:f.id,error:I},"remote provider skipped")}}await Oi.promises.mkdir(n,{recursive:!0}),await ID(s,JSON.stringify({...A,providers:u})),await ID(i,JSON.stringify(A));try{let f=new Set([...A.providers,...u].map(m=>NB(m))),g=new Set([...A.providers,...u].map(m=>{let I=m.embedBase?"tv":m.kind??"anime";return`${as.join(n,NB(m))}:${I}`}));for(let m of BD.keys())g.has(m)||BD.delete(m);let p=await Oi.promises.readdir(n);for(let m of p)m.toLowerCase().endsWith(".mjs")&&(f.has(m)||(await Oi.promises.unlink(as.join(n,m)),_.info({file:m},"remote providers: removed superseded module")))}catch(f){_.warn({err:f},"remote providers: superseded module cleanup failed")}return r}function mae(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 Iae(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 Gp(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 um=rr(WCe(),1);mn();var pht=rr(I4(),1),Eht=rr(qB(),1),mht=rr(Gf(),1),Iht=rr(jD(),1),Cht=rr(KD(),1),Bht=rr(tN(),1),qCe=rr(JB(),1),yht=rr(B4(),1);var Qg=qCe.default;mn();var JCe=rr(Fb(),1),Ma=_.child({module:"DiscordGateway"}),D5=class{gateway=null;heartbeat=null;token=null;reconnectTimeout=null;lastActivity=null;isEnabled=!1;RECONNECT_DELAY=15e3;externalAssetCache=new Map;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}reloadToken(){JCe.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 Ma.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 Ma.warn({err:n},"external-assets proxy error"),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(o){if(ae.DISCORD_CLIENT_ID){let c=await this.getExternalAsset(o);c?a={large_image:c,large_text:t.title.slice(0,128),small_image:"small",small_text:"dango"}:a={large_image:"logo",large_text:t.title.slice(0,128)}}}else ae.DISCORD_CLIENT_ID&&(a={large_image:"logo",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){Ma.error({err:c},"Failed to send gateway presence update")}}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"};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}:{},...ae.DISCORD_CLIENT_ID?{assets:{large_image:"logo",large_text:"dango"}}:{},buttons:["Learn More"],metadata:{button_urls:["https://github.com/serifpersia/dango"]},status_display_type:2}],status:"online",afk:!1}}))}catch(i){Ma.error({err:i},"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";Ma.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"&&(Ma.info(`Gateway READY as ${i.d.user?.username||"unknown"}`),this.lastActivity&&this.updatePresence(this.lastActivity).catch(s=>Ma.warn({err:s},"failed to restore presence after READY"))):i.op===7?(Ma.warn("Gateway reconnect requested by Discord"),this.handleDisconnect()):i.op===9&&(Ma.warn("Gateway invalid session, reconnecting..."),this.handleDisconnect()))}catch(i){Ma.debug({err:i},"Gateway message parse error")}}),this.gateway.on("close",(n,i)=>{Ma.warn(`Gateway closed ${n} ${i.toString().slice(0,100)}`),this.handleDisconnect()}),this.gateway.on("error",n=>{Ma.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 D5;var mi=_.child({module:"DiscordRPC"}),N5=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){mi.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()}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.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){mi.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){mi.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){mi.debug("DISCORD_CLIENT_ID is not configured. Discord Rich Presence is disabled."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}try{this.client=new um.Client({clientId:n}),this.client.on("ready",()=>{mi.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",()=>{mi.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){mi.debug("Discord client not detected. Rich Presence disabled for this session."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}mi.debug("Discord client not running or connection refused."),this.scheduleReconnect()}else mi.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){mi.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?mi.debug(`Discord RPC login failed ${this.retryCount} times. Retrying in ${Math.round(t/1e3)}s...`):mi.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.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,...n!=="logo"?{smallImageKey:"small",smallImageText:"dango"}:{},type:t.providerName==="ASMR"||t.providerName==="Radio"||t.providerName==="Music"?2:3,statusDisplayType:um.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,...n!=="logo"?{smallImageKey:"small",smallImageText:"dango"}:{},type:t.providerName==="ASMR"||t.providerName==="Radio"||t.providerName==="Music"?2:3,statusDisplayType:um.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){mi.error({err:i},"Failed to set Discord activity")}}async setIdleStatus(t){if(!this.isEnabled)return;if($r.serviceEnabled){$r.setIdleStatus(t);return}if(!this.client||!this.client.user){mi.warn("Discord client not connected, skipping idle status update");return}let r={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"}},n=r[t]??{details:"dango",state:"Idle"};try{if(!this.client||!this.client.user){mi.warn("Discord client not connected, skipping idle status update");return}await this.client.user.setActivity({details:n.details,state:n.state,largeImageKey:"logo",largeImageText:"dango",type:t==="asmr"||t==="radio"||t==="music"?2:3,statusDisplayType:um.StatusDisplayType.DETAILS,buttons:[{label:"Learn More",url:"https://github.com/serifpersia/dango"}]}),this.hasPagePresence=t in r}catch(i){i.message==="Closed by Discord"?mi.warn("Discord connection ended, skipping idle status update"):mi.error({err:i},"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")}}},eQ=new N5;var R5=(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 Ii="ALL",jCe="all",$Ce=["get","post","put","delete","options","patch","query"],Qx="Can not add a route since the matcher is already built.",bx=class extends Error{};var KCe="__COMPOSED_HANDLER";var Qht=e=>e.text("404 Not Found",404),XCe=(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)},zCe=class ZCe{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...$Ce,jCe].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(Ii,this.#e,a)}),this);let{strict:n,...i}=t;Object.assign(this,i),this.getPath=n??!0?t.getPath??ok:C9}#t(){let t=new ZCe({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Qht;errorHandler=XCe;route(t,r){let n=this.basePath(t);return r.routes.map(i=>{let s;r.errorHandler===XCe?s=i.handler:(s=async(o,a)=>(await R5([],r.errorHandler)(o,()=>i.handler(o,a))).res,s[KCe]=i.handler),n.#i(i.method,i.path,s,i.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=El(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=El(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(Ii,El(t,"*"),a),this}#i(t,r,n,i){r=El(this._basePath,r);let s={basePath:i!==void 0?El(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 Ak(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=R5(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${El("/",t)}`,r),n,i));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var ni=()=>Object.create(null);var wx=[];function x5(e,t){let r=this.buildAllMatchers(),n=((i,s)=>{let o=r[i]||r[Ii],a=o[2][s];if(a)return a;let A=s.match(o[0]);if(!A)return[[],wx];let u=A.indexOf("",1);return[o[1][u],A]});return this.match=n,n(e,t)}var cm="[^/]+",Kd=".*",tl="(?:|/.*)",$d=Symbol(),eBe=new Set(".\\+*[^]$()");function bht(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===Kd||e===tl?t===tl?-1:1:t===Kd||t===tl?-1:e===cm?1:t===cm?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var tBe=class v5{#e;#t;#r=ni();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?["","",Kd]:["","",cm]:null:u==="/*"?["","",tl]:u.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let d=c[1],h=c[2]||cm;if(d&&c[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))||h.length===1&&eBe.has(h)))throw $d;if(l=o.#r[h],!l){if(h!==Kd&&h!==tl){for(let f in o.#r)if((h.length>1||f.length>1)&&f!==Kd&&f!==tl)throw $d}l=o.#r[h]=new v5}d!==""&&(l.#t??=i.varIndex++,n.push([d,l.#t]))}else if(l=o.#r[u],!l){for(let d in o.#r)if(d.length>1&&d!==Kd&&d!==tl)throw $d;l=o.#r[u]=new v5}o=l}if(o.#e!==void 0)throw $d;o.#e=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(bht).map(n=>{let i=this.#r[n],s=i.buildRegExpStr();return s===""?"":(typeof i.#t=="number"?`(${n})@${i.#t}`:eBe.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 k5=class{#e={varIndex:0};#t=new tBe;#r=0;paths=ni();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 rBe=ni();function nBe(e){return rBe[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?tl:t==="*"?Kd:`/:${cm}`)}$`)}function Sx(e,t){for(let r of Object.keys(e).sort((n,i)=>i.length-n.length))if(nBe(r).test(t))return[...e[r]]}var Tx=class{name="RegExpRouter";#e;#t;#r;constructor(){this.#e={[Ii]:ni()},this.#t={[Ii]:ni()},this.#r={[Ii]:new k5}}#i(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===$d?new bx(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 k5;for(let a of[n,i]){a[e]=ni();for(let A in a[Ii])a[e][A]=[...a[Ii][A]],this.#i(e,A)}}t==="/*"&&(t="*");let s=e===Ii?Object.keys(n):[e];if(/\*$/.test(t)){let a=nBe(t);for(let A of s)n[A][t]||(this.#i(A,t),n[A][t]=Sx(n[A],t)||Sx(n[Ii],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=ob(t)||[t];for(let a of o)for(let A of s)i[A][a]||(this.#i(A,a),i[A][a]=Sx(n[A],a)||Sx(n[Ii],a)||[]),i[A][a].push([r,a])}match=x5;buildAllMatchers(){let e=ni();for(let t of Object.keys(this.#t))e[t]=this.#s(t);return this.#e=this.#t=this.#r=void 0,rBe=ni(),e}#s(e){let t=this.#e[e],r=this.#t[e],n=this.#r[e],i=ni(),s=[],[o,a,A]=n.buildRegExp();for(let u of[t,r])for(let c in u){let l=u[c],d=n.paths[c];if(!d){i[c]=[l.map(([h])=>[h,ni()]),wx];continue}s[d[0]]=l.map(([h,f])=>[h,n.paths[f][1].reduceRight((g,[p],m)=>(g[p]=A[d[1][m][1]],g),ni())])}return[o,a.map(u=>s[u]),i]}};var L5=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 bx)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 M5=ni(),wht=0,iBe=class sBe{#e=[];#t=ni();#r=[];#i;#s=M5;insert(t,r,n){let i=this,s=E9(r),o=new Set,a=0;for(let A of s){let u=s[++a],c=m9(A,u)||(u===void 0&&A&&A.indexOf("*")===A.length-1?A:null),l=Array.isArray(c),d=l?c[0]:c||A,h=i.#t[d]||=new sBe;c&&!h.#i&&(h.#i=c,i.#r.push(h)),i=h,l&&o.add(c[1])}i.#e.push({[t]:{handler:n,possibleKeys:[...o],score:++wht}})}#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[Ii];if(u){u.params=ni(),t.push(u);for(let c=0,l=u.possibleKeys.length;c<l;c++){let d=u.possibleKeys[c];u.params[d]=s?.[d]&&!c?s[d]:i[d]??s?.[d]}}}}search(t,r){let n=[];this.#s=M5;let s=[this],o=sk(r),a=[],A=o.length,u=null;for(let c=0;c<A;c++){let l=o[c],d=c===A-1,h=[];for(let g=0,p=s.length;g<p;g++){let m=s[g],I=m.#t[l];I&&(I.#s=m.#s,d?(I.#t["*"]&&this.#n(n,I.#t["*"],t,m.#s),this.#n(n,I,t,m.#s)):h.push(I));for(let C of m.#r){let B=C.#i,b=m.#s===M5?{}:{...m.#s};if(typeof B=="string"){(B==="*"||l.startsWith(B.slice(0,-1)))&&(this.#n(n,C,t,m.#s),B==="*"&&(C.#s=b,h.push(C)));continue}let[,D,N]=B;if(!(!l&&N===!0)){if(N!==!0){if(!u){u=[];let x=r[0]==="/"?1:0;for(let M=0;M<A;M++)u[M]=x,x+=o[M].length+1}let S=r.slice(u[c]),y=N.exec(S);if(y){b[D]=y[0],this.#n(n,C,t,m.#s,b),y[0].length===S.length&&C.#t["*"]&&this.#n(n,C.#t["*"],t,m.#s,b);for(let x in C.#t){C.#s=b;let M=y[0].match(/\//g)?.length??0;(a[M]||=[]).push(C);break}continue}}(N===!0||N.test(l))&&(b[D]=l,d?(this.#n(n,C,t,b,m.#s),C.#t["*"]&&this.#n(n,C.#t["*"],t,b,m.#s)):(C.#s=b,h.push(C)))}}}let f=a.shift();s=f?h.concat(f):h}return n[1]&&n.sort((c,l)=>c.score-l.score),[n.map(({handler:c,params:l})=>[c,l])]}};var F5=class{name="TrieRouter";#e=new iBe;add(e,t,r){for(let n of ob(t)||[t])this.#e.insert(e,n,r)}match(e,t){return this.#e.search(e,t)}};var U5=class extends zCe{constructor(e={}){super(e),this.router=e.router??new L5({routers:[new Tx,new F5]})}};var aBe=e=>e===32||e===9||e===10||e===13,Dx=(e,t)=>{for(;t<e.length&&aBe(e.charCodeAt(t));)t++;return t},tQ=(e,t)=>{for(;t>0&&aBe(e.charCodeAt(t-1));)t--;return t},oBe=(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]},Sht=(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},Tht=(e,t)=>{t=Dx(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,tQ(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=Dx(e,r),e.charCodeAt(r)===61){let A=oBe(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=Dx(e,r+1),c=e.charCodeAt(u);if(u<e.length&&!(c===59||c===44)){let l=oBe(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,tQ(e,r)),A===59&&(s=!0),r++;break}r++}return[r,n,i??e.slice(a,tQ(e,r)),s]},Dht=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Dx(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,tQ(e,n)),n++,a===44)return[n,r.type?r:void 0];if(!r.type)return[Sht(e,n),void 0];break}n++}if(!r.type)return r.type=e.slice(t,tQ(e,e.length)),[e.length,r.type?r:void 0];let i,s,o;for(;n<e.length&&([n,i,s,o]=Tht(e,n),i&&s&&(r.params[i]=s),!!o););return[n,r]},ABe=e=>{if(!e)return[];let t=[],r=0,n,i=!1,s;for(;r<e.length;)[r,n]=Dht(e,r),n&&(n.q=Nht(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},Nht=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 uBe=/^\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 Rht=["gzip","deflate"],xht=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,vht=(e,t)=>{if(e===void 0)return;let r=ABe(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},kht=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,cBe=e=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:Rht,n=e?.contentTypeFilter??uBe,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)||!Lht(o.res))return;let u=o.res.headers.get("Vary");u!=="*"&&!(u&&kht.test(u))&&o.header("Vary",u?`${u}, Accept-Encoding`:"Accept-Encoding");let c=o.req.header("Accept-Encoding"),l=vht(c,r);if(!l||!o.res.body)return;let d=new CompressionStream(l);o.res=new Response(o.res.body.pipeThrough(d),o.res),o.res.headers.delete("Content-Length"),o.res.headers.set("Content-Encoding",l);let h=o.res.headers.get("ETag");h&&!h.startsWith("W/")&&o.res.headers.set("ETag",`W/${h}`)}},Lht=e=>{let t=e.headers.get("Cache-Control");return!t||!xht.test(t)};import cwe from"path";import Gm from"fs";var lBe=":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",Mht=lBe+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Fht="["+lBe+"]["+Mht+"]*",Uht=new RegExp("^"+Fht+"$");function dBe(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 _5=function(e){let t=Uht.exec(e);return!(t===null||typeof t>"u")};function hBe(e){return typeof e<"u"}var rQ=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],Nx=["__proto__","constructor","prototype"];var _ht={allowBooleanAttributes:!1,unpairedTags:[]};function EBe(e,t){t=Object.assign({},_ht,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=fBe(e,s),s.err)return s}else if(e[s]==="<"){let o=s;if(s++,e[s]==="!"){s=gBe(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=nKe("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)=>xB(fetch(r,{...n,headers:{"User-Agent":RB,...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)=>{_.info(r,n)},warn:(r,n)=>{_.warn(r,n)},error:(r,n)=>{_.error(r,n)},debug:(r,n)=>{_.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 Kt(i)},proxyUrl:(r,n)=>`/api/proxy?url=${encodeURIComponent(r)}&referer=${encodeURIComponent(n)}`,userAgent:RB,titleMatch:{buildQueryVariants:fB,pickBestMatch:Rc},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 fB(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=Rc(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:IB},tmdb:{base:wo,image:bd,get:async r=>{try{let n=await Lc(),i=r.includes("?")?"&":"?",s=await t(`${wo}${r}${i}api_key=${n}`);return s.ok?Kt(s):null}catch{return null}}},request:{get:r=>ZT.getStore()?.get(r)},cookies:{sanitizeCfClearance:Lp,buildCfClearanceCookie:hu},crypto:{aes256CbcDecryptJson:lKe,hmacSha256Base64Url:(r,n)=>yD.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 oKe({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=gae(r,n);return!i||i.status!==200?null:JSON.parse(i.body)}catch{return null}},getText:async(r,n)=>{let i=gae(r,n);return!i||i.status!==200?null:i.body}},cheerio:{load:r=>B2(r)}}}function O8(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.name=="string"?t:null}function Cae(e,t){return t.every(r=>typeof e[r]=="function")}function Bae(e){let t=O8(e);return!!t&&Cae(t,["search","getEpisodes","getStreamUrls"])}function yae(e){let t=O8(e);return!!t&&Cae(t,["search","getDetail","getChapters","getPages"])}function Qae(e){let t=O8(e);return!!t&&(typeof t.getSources=="function"||typeof t.getEmbedUrl=="function")}function hKe(e,t){return e==="manga"?yae(t):e==="tv"?Qae(t):e==="asmr"?F8(t):Bae(t)}function pae(e,t,r,n){return t.kind==="manga"?yae(n)?(e.mangaProviders[r]=n,!0):!1:t.kind==="tv"?Qae(n)?(e.tvProviders[r]=n,!0):!1:t.kind==="asmr"?F8(n)?(e.asmrProviders[r]=n,!0):!1:Bae(n)?(e.providers[r]=n,!0):!1}function fKe(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 U8(e,t,r,n,i){if(e.minDango&&!hae(fae,e.minDango))return{provider:null,error:`requires dango ${e.minDango}, running ${fae}`};if(e.embedBase)return{provider:fKe(e.id,e.embedBase)};let s=cKe(e.entry,t);await Oi.promises.mkdir(r,{recursive:!0});let o=NB(e),a=as.join(r,o),A=`${a}:${e.kind??"anime"}`,u=null;try{let d=await Oi.promises.readFile(a);(e.sha256&&CD(d)===e.sha256||!e.sha256&&i)&&(u=d)}catch{}if(u){let d=BD.get(A);if(d)return _.debug({provider:e.id,version:e.version},"remote provider reused cached instance"),{provider:d.provider,facets:d.facets}}else{try{u=await uKe(s)}catch(d){return{provider:null,error:`download failed: ${d.message}`}}if(e.sha256){if(CD(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 ID(a,u)}let c=`${e.version}-${e.sha256??"nosha"}`,l=await pKe(a,c,n,e);return l.provider&&!l.error&&BD.set(A,{provider:l.provider,facets:l.facets}),l}var BD=new Map;function NB(e){return`${e.id}-${e.version}-${e.sha256??"nosha"}.mjs`}function gKe(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 pKe(e,t,r,n){let i=n.id,s;try{let A=`${sKe(e).href}?v=${encodeURIComponent(t)}`;s=await xB(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 xB(Promise.resolve(o(r)),1e4,`factory ${i}`)}catch(A){return{provider:null,error:`factory failed: ${A.message}`}}return hKe(n.kind,a)?{provider:a,facets:gKe(s)}:{provider:null,error:"invalid provider shape"}}async function EKe(e,t,r){if(e.embedBase)return U8(e,"",t,r,!1);if(!e.sha256)return{provider:null,error:"no verified fallback"};let n=as.join(t,NB(e)),i;try{i=await Oi.promises.readFile(n)}catch{return{provider:null,error:"no cached fallback file"}}return CD(i)!==e.sha256?{provider:null,error:"cached fallback failed verification"}:U8(e,"",t,r,!1)}var Eae;function bae(e){return Eae??=mKe(e).finally(()=>{Eae=void 0})}async function mKe(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=DB(JSON.parse(await Oi.promises.readFile(s,"utf8")))}catch{try{o=DB(JSON.parse(await Oi.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 Oi.promises.readFile(g);CD(p)===f.sha256&&await ID(as.join(n,NB(f)),p)}catch{}}}catch{}}let a=new Map((o?.providers??[]).map(f=>[f.id.toLowerCase(),f])),A;try{let f=await AKe(t);A=DB(JSON.parse(f.toString("utf8")))}catch(f){_.error({err:f,registryUrl:t},"remote providers: manifest fetch failed, trying disk cache");try{A=DB(JSON.parse(await Oi.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,d=dKe(e.cache),h=e.allowUnsigned??(process.env.DANGO_ALLOW_UNSIGNED_PROVIDERS==="1"||aKe(t));for(let f of A.providers){let g=f.id.toLowerCase();if(f.enabledByDefault===!1&&(!l||!c.has(g))){r.catalog.push(Gp(f,!1,"disabled by default"));continue}if(l&&!c.has(g)){r.catalog.push(Gp(f,!1,"not in enabledProviders"));continue}let{provider:p,facets:m,error:I}=await U8(f,t,n,d,h);if(p&&!I){if(!pae(r,f,g,p)){r.catalog.push(Gp(f,!1,"invalid provider shape for kind")),_.warn({provider:f.id},"remote provider kind mismatch, skipped");continue}r.catalog.push(Iae(m,mae(f,p,Gp(f,!0)))),u.push(f),f.proxy&&r.proxyRules.push(f.proxy),_.info({provider:f.id,version:f.version},"remote provider loaded")}else{let C=a.get(g);if(C){let B=await EKe(C,n,d);if(B.provider&&!B.error&&(pae(r,C,g,B.provider)||(B.error="cached fallback failed validation")),B.provider&&!B.error){r.catalog.push({...Iae(B.facets,mae(C,B.provider,Gp(C,!0))),error:`serving cached ${C.version}: ${I}`}),u.push(C),C.proxy&&r.proxyRules.push(C.proxy),_.warn({provider:f.id,error:I,fallback:C.version},"remote provider update failed, serving cached version");continue}}r.catalog.push(Gp(f,!1,I)),C&&u.push(C),f.proxy&&r.proxyRules.push(f.proxy),_.warn({provider:f.id,error:I},"remote provider skipped")}}await Oi.promises.mkdir(n,{recursive:!0}),await ID(s,JSON.stringify({...A,providers:u})),await ID(i,JSON.stringify(A));try{let f=new Set([...A.providers,...u].map(m=>NB(m))),g=new Set([...A.providers,...u].map(m=>{let I=m.embedBase?"tv":m.kind??"anime";return`${as.join(n,NB(m))}:${I}`}));for(let m of BD.keys())g.has(m)||BD.delete(m);let p=await Oi.promises.readdir(n);for(let m of p)m.toLowerCase().endsWith(".mjs")&&(f.has(m)||(await Oi.promises.unlink(as.join(n,m)),_.info({file:m},"remote providers: removed superseded module")))}catch(f){_.warn({err:f},"remote providers: superseded module cleanup failed")}return r}function mae(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 Iae(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 Gp(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 um=rr(WCe(),1);mn();var pht=rr(I4(),1),Eht=rr(qB(),1),mht=rr(Gf(),1),Iht=rr(jD(),1),Cht=rr(KD(),1),Bht=rr(tN(),1),qCe=rr(JB(),1),yht=rr(B4(),1);var Qg=qCe.default;mn();var JCe=rr(Fb(),1),Ma=_.child({module:"DiscordGateway"}),D5=class{gateway=null;heartbeat=null;token=null;reconnectTimeout=null;lastActivity=null;isEnabled=!1;RECONNECT_DELAY=15e3;externalAssetCache=new Map;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}reloadToken(){JCe.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 Ma.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 Ma.warn({err:n},"external-assets proxy error"),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(o){if(ae.DISCORD_CLIENT_ID){let c=await this.getExternalAsset(o);c?a={large_image:c,large_text:t.title.slice(0,128)}:a={large_image:"logo",large_text:t.title.slice(0,128)}}}else ae.DISCORD_CLIENT_ID&&(a={large_image:"logo",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){Ma.error({err:c},"Failed to send gateway presence update")}}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"};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}:{},...ae.DISCORD_CLIENT_ID?{assets:{large_image:"logo",large_text:"dango"}}:{},buttons:["Learn More"],metadata:{button_urls:["https://github.com/serifpersia/dango"]},status_display_type:2}],status:"online",afk:!1}}))}catch(i){Ma.error({err:i},"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";Ma.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"&&(Ma.info(`Gateway READY as ${i.d.user?.username||"unknown"}`),this.lastActivity&&this.updatePresence(this.lastActivity).catch(s=>Ma.warn({err:s},"failed to restore presence after READY"))):i.op===7?(Ma.warn("Gateway reconnect requested by Discord"),this.handleDisconnect()):i.op===9&&(Ma.warn("Gateway invalid session, reconnecting..."),this.handleDisconnect()))}catch(i){Ma.debug({err:i},"Gateway message parse error")}}),this.gateway.on("close",(n,i)=>{Ma.warn(`Gateway closed ${n} ${i.toString().slice(0,100)}`),this.handleDisconnect()}),this.gateway.on("error",n=>{Ma.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 D5;var mi=_.child({module:"DiscordRPC"}),N5=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){mi.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()}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.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){mi.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){mi.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){mi.debug("DISCORD_CLIENT_ID is not configured. Discord Rich Presence is disabled."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}try{this.client=new um.Client({clientId:n}),this.client.on("ready",()=>{mi.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",()=>{mi.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){mi.debug("Discord client not detected. Rich Presence disabled for this session."),this.isEnabled=!1,this.permanentlyDisabled=!0;return}mi.debug("Discord client not running or connection refused."),this.scheduleReconnect()}else mi.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){mi.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?mi.debug(`Discord RPC login failed ${this.retryCount} times. Retrying in ${Math.round(t/1e3)}s...`):mi.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.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:um.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:um.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){mi.error({err:i},"Failed to set Discord activity")}}async setIdleStatus(t){if(!this.isEnabled)return;if($r.serviceEnabled){$r.setIdleStatus(t);return}if(!this.client||!this.client.user){mi.warn("Discord client not connected, skipping idle status update");return}let r={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"}},n=r[t]??{details:"dango",state:"Idle"};try{if(!this.client||!this.client.user){mi.warn("Discord client not connected, skipping idle status update");return}await this.client.user.setActivity({details:n.details,state:n.state,largeImageKey:"logo",largeImageText:"dango",type:t==="asmr"||t==="radio"||t==="music"?2:3,statusDisplayType:um.StatusDisplayType.DETAILS,buttons:[{label:"Learn More",url:"https://github.com/serifpersia/dango"}]}),this.hasPagePresence=t in r}catch(i){i.message==="Closed by Discord"?mi.warn("Discord connection ended, skipping idle status update"):mi.error({err:i},"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")}}},eQ=new N5;var R5=(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 Ii="ALL",jCe="all",$Ce=["get","post","put","delete","options","patch","query"],Qx="Can not add a route since the matcher is already built.",bx=class extends Error{};var KCe="__COMPOSED_HANDLER";var Qht=e=>e.text("404 Not Found",404),XCe=(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)},zCe=class ZCe{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...$Ce,jCe].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(Ii,this.#e,a)}),this);let{strict:n,...i}=t;Object.assign(this,i),this.getPath=n??!0?t.getPath??ok:C9}#t(){let t=new ZCe({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Qht;errorHandler=XCe;route(t,r){let n=this.basePath(t);return r.routes.map(i=>{let s;r.errorHandler===XCe?s=i.handler:(s=async(o,a)=>(await R5([],r.errorHandler)(o,()=>i.handler(o,a))).res,s[KCe]=i.handler),n.#i(i.method,i.path,s,i.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=El(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=El(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(Ii,El(t,"*"),a),this}#i(t,r,n,i){r=El(this._basePath,r);let s={basePath:i!==void 0?El(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 Ak(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=R5(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${El("/",t)}`,r),n,i));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var ni=()=>Object.create(null);var wx=[];function x5(e,t){let r=this.buildAllMatchers(),n=((i,s)=>{let o=r[i]||r[Ii],a=o[2][s];if(a)return a;let A=s.match(o[0]);if(!A)return[[],wx];let u=A.indexOf("",1);return[o[1][u],A]});return this.match=n,n(e,t)}var cm="[^/]+",Kd=".*",tl="(?:|/.*)",$d=Symbol(),eBe=new Set(".\\+*[^]$()");function bht(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===Kd||e===tl?t===tl?-1:1:t===Kd||t===tl?-1:e===cm?1:t===cm?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var tBe=class v5{#e;#t;#r=ni();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?["","",Kd]:["","",cm]:null:u==="/*"?["","",tl]:u.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let d=c[1],h=c[2]||cm;if(d&&c[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))||h.length===1&&eBe.has(h)))throw $d;if(l=o.#r[h],!l){if(h!==Kd&&h!==tl){for(let f in o.#r)if((h.length>1||f.length>1)&&f!==Kd&&f!==tl)throw $d}l=o.#r[h]=new v5}d!==""&&(l.#t??=i.varIndex++,n.push([d,l.#t]))}else if(l=o.#r[u],!l){for(let d in o.#r)if(d.length>1&&d!==Kd&&d!==tl)throw $d;l=o.#r[u]=new v5}o=l}if(o.#e!==void 0)throw $d;o.#e=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(bht).map(n=>{let i=this.#r[n],s=i.buildRegExpStr();return s===""?"":(typeof i.#t=="number"?`(${n})@${i.#t}`:eBe.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 k5=class{#e={varIndex:0};#t=new tBe;#r=0;paths=ni();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 rBe=ni();function nBe(e){return rBe[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?tl:t==="*"?Kd:`/:${cm}`)}$`)}function Sx(e,t){for(let r of Object.keys(e).sort((n,i)=>i.length-n.length))if(nBe(r).test(t))return[...e[r]]}var Tx=class{name="RegExpRouter";#e;#t;#r;constructor(){this.#e={[Ii]:ni()},this.#t={[Ii]:ni()},this.#r={[Ii]:new k5}}#i(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===$d?new bx(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 k5;for(let a of[n,i]){a[e]=ni();for(let A in a[Ii])a[e][A]=[...a[Ii][A]],this.#i(e,A)}}t==="/*"&&(t="*");let s=e===Ii?Object.keys(n):[e];if(/\*$/.test(t)){let a=nBe(t);for(let A of s)n[A][t]||(this.#i(A,t),n[A][t]=Sx(n[A],t)||Sx(n[Ii],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=ob(t)||[t];for(let a of o)for(let A of s)i[A][a]||(this.#i(A,a),i[A][a]=Sx(n[A],a)||Sx(n[Ii],a)||[]),i[A][a].push([r,a])}match=x5;buildAllMatchers(){let e=ni();for(let t of Object.keys(this.#t))e[t]=this.#s(t);return this.#e=this.#t=this.#r=void 0,rBe=ni(),e}#s(e){let t=this.#e[e],r=this.#t[e],n=this.#r[e],i=ni(),s=[],[o,a,A]=n.buildRegExp();for(let u of[t,r])for(let c in u){let l=u[c],d=n.paths[c];if(!d){i[c]=[l.map(([h])=>[h,ni()]),wx];continue}s[d[0]]=l.map(([h,f])=>[h,n.paths[f][1].reduceRight((g,[p],m)=>(g[p]=A[d[1][m][1]],g),ni())])}return[o,a.map(u=>s[u]),i]}};var L5=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 bx)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 M5=ni(),wht=0,iBe=class sBe{#e=[];#t=ni();#r=[];#i;#s=M5;insert(t,r,n){let i=this,s=E9(r),o=new Set,a=0;for(let A of s){let u=s[++a],c=m9(A,u)||(u===void 0&&A&&A.indexOf("*")===A.length-1?A:null),l=Array.isArray(c),d=l?c[0]:c||A,h=i.#t[d]||=new sBe;c&&!h.#i&&(h.#i=c,i.#r.push(h)),i=h,l&&o.add(c[1])}i.#e.push({[t]:{handler:n,possibleKeys:[...o],score:++wht}})}#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[Ii];if(u){u.params=ni(),t.push(u);for(let c=0,l=u.possibleKeys.length;c<l;c++){let d=u.possibleKeys[c];u.params[d]=s?.[d]&&!c?s[d]:i[d]??s?.[d]}}}}search(t,r){let n=[];this.#s=M5;let s=[this],o=sk(r),a=[],A=o.length,u=null;for(let c=0;c<A;c++){let l=o[c],d=c===A-1,h=[];for(let g=0,p=s.length;g<p;g++){let m=s[g],I=m.#t[l];I&&(I.#s=m.#s,d?(I.#t["*"]&&this.#n(n,I.#t["*"],t,m.#s),this.#n(n,I,t,m.#s)):h.push(I));for(let C of m.#r){let B=C.#i,b=m.#s===M5?{}:{...m.#s};if(typeof B=="string"){(B==="*"||l.startsWith(B.slice(0,-1)))&&(this.#n(n,C,t,m.#s),B==="*"&&(C.#s=b,h.push(C)));continue}let[,D,N]=B;if(!(!l&&N===!0)){if(N!==!0){if(!u){u=[];let x=r[0]==="/"?1:0;for(let M=0;M<A;M++)u[M]=x,x+=o[M].length+1}let S=r.slice(u[c]),y=N.exec(S);if(y){b[D]=y[0],this.#n(n,C,t,m.#s,b),y[0].length===S.length&&C.#t["*"]&&this.#n(n,C.#t["*"],t,m.#s,b);for(let x in C.#t){C.#s=b;let M=y[0].match(/\//g)?.length??0;(a[M]||=[]).push(C);break}continue}}(N===!0||N.test(l))&&(b[D]=l,d?(this.#n(n,C,t,b,m.#s),C.#t["*"]&&this.#n(n,C.#t["*"],t,b,m.#s)):(C.#s=b,h.push(C)))}}}let f=a.shift();s=f?h.concat(f):h}return n[1]&&n.sort((c,l)=>c.score-l.score),[n.map(({handler:c,params:l})=>[c,l])]}};var F5=class{name="TrieRouter";#e=new iBe;add(e,t,r){for(let n of ob(t)||[t])this.#e.insert(e,n,r)}match(e,t){return this.#e.search(e,t)}};var U5=class extends zCe{constructor(e={}){super(e),this.router=e.router??new L5({routers:[new Tx,new F5]})}};var aBe=e=>e===32||e===9||e===10||e===13,Dx=(e,t)=>{for(;t<e.length&&aBe(e.charCodeAt(t));)t++;return t},tQ=(e,t)=>{for(;t>0&&aBe(e.charCodeAt(t-1));)t--;return t},oBe=(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]},Sht=(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},Tht=(e,t)=>{t=Dx(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,tQ(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=Dx(e,r),e.charCodeAt(r)===61){let A=oBe(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=Dx(e,r+1),c=e.charCodeAt(u);if(u<e.length&&!(c===59||c===44)){let l=oBe(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,tQ(e,r)),A===59&&(s=!0),r++;break}r++}return[r,n,i??e.slice(a,tQ(e,r)),s]},Dht=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Dx(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,tQ(e,n)),n++,a===44)return[n,r.type?r:void 0];if(!r.type)return[Sht(e,n),void 0];break}n++}if(!r.type)return r.type=e.slice(t,tQ(e,e.length)),[e.length,r.type?r:void 0];let i,s,o;for(;n<e.length&&([n,i,s,o]=Tht(e,n),i&&s&&(r.params[i]=s),!!o););return[n,r]},ABe=e=>{if(!e)return[];let t=[],r=0,n,i=!1,s;for(;r<e.length;)[r,n]=Dht(e,r),n&&(n.q=Nht(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},Nht=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 uBe=/^\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 Rht=["gzip","deflate"],xht=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,vht=(e,t)=>{if(e===void 0)return;let r=ABe(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},kht=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,cBe=e=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:Rht,n=e?.contentTypeFilter??uBe,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)||!Lht(o.res))return;let u=o.res.headers.get("Vary");u!=="*"&&!(u&&kht.test(u))&&o.header("Vary",u?`${u}, Accept-Encoding`:"Accept-Encoding");let c=o.req.header("Accept-Encoding"),l=vht(c,r);if(!l||!o.res.body)return;let d=new CompressionStream(l);o.res=new Response(o.res.body.pipeThrough(d),o.res),o.res.headers.delete("Content-Length"),o.res.headers.set("Content-Encoding",l);let h=o.res.headers.get("ETag");h&&!h.startsWith("W/")&&o.res.headers.set("ETag",`W/${h}`)}},Lht=e=>{let t=e.headers.get("Cache-Control");return!t||!xht.test(t)};import cwe from"path";import Gm from"fs";var lBe=":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",Mht=lBe+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Fht="["+lBe+"]["+Mht+"]*",Uht=new RegExp("^"+Fht+"$");function dBe(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 _5=function(e){let t=Uht.exec(e);return!(t===null||typeof t>"u")};function hBe(e){return typeof e<"u"}var rQ=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],Nx=["__proto__","constructor","prototype"];var _ht={allowBooleanAttributes:!1,unpairedTags:[]};function EBe(e,t){t=Object.assign({},_ht,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=fBe(e,s),s.err)return s}else if(e[s]==="<"){let o=s;if(s++,e[s]==="!"){s=gBe(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--),!qht(A)){let l;return A.trim().length===0?l="Invalid space after '<'.":l="Tag '"+A+"' is an invalid name.",fn("InvalidTag",l,ls(e,s))}let u=Hht(e,s);if(u===!1)return fn("InvalidAttr","Attributes for '"+A+"' have open quote.",ls(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 d=pBe(c,t);if(d===!0)n=!0;else return fn(d.err.code,d.err.msg,ls(e,l+d.err.line))}else if(a)if(u.tagClosed){if(c.trim().length>0)return fn("InvalidTag","Closing tag '"+A+"' can't have attributes or invalid starting.",ls(e,o));if(r.length===0)return fn("InvalidTag","Closing tag '"+A+"' has not been opened.",ls(e,o));{let l=r.pop();if(A!==l.tagName){let d=ls(e,l.tagStartPos);return fn("InvalidTag","Expected closing tag '"+l.tagName+"' (opened in line "+d.line+", col "+d.col+") instead of closing tag '"+A+"'.",ls(e,o))}r.length==0&&(i=!0)}}else return fn("InvalidTag","Closing tag '"+A+"' doesn't have proper closing.",ls(e,s));else{let l=pBe(c,t);if(l!==!0)return fn(l.err.code,l.err.msg,ls(e,s-c.length+l.err.line));if(i===!0)return fn("InvalidXml","Multiple possible root nodes found.",ls(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=gBe(e,s);continue}else if(e[s+1]==="?"){if(s=fBe(e,++s),s.err)return s}else break;else if(e[s]==="&"){let l=Vht(e,s);if(l==-1)return fn("InvalidChar","char '&' is not expected.",ls(e,s));s=l}else if(i===!0&&!lm(e[s]))return fn("InvalidXml","Extra text at the end",ls(e,s));e[s]==="<"&&s--}}else{if(lm(e[s]))continue;return fn("InvalidChar","char '"+e[s]+"' is not expected.",ls(e,s))}if(n){if(r.length==1)return fn("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",ls(e,r[0].tagStartPos));if(r.length>0)return fn("InvalidXml","Invalid '"+JSON.stringify(r.map(s=>s.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return fn("InvalidXml","Start tag expected.",1);return!0}function lm(e){return e===" "||e===" "||e===`
|
|
471
471
|
`||e==="\r"}function fBe(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 fn("InvalidXml","XML declaration allowed only at the start of the document.",ls(e,t));if(e[t]=="?"&&e[t+1]==">"){t++;break}else continue}return t}function gBe(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 Oht='"',Pht="'";function Hht(e,t){let r="",n="",i=!1;for(;t<e.length;t++){if(e[t]===Oht||e[t]===Pht)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 Ght(e){let t=[],r=e.length,n=0;for(;n<r;){let i=n;for(;n<r&&lm(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&&!lm(e[n])&&e[n]!=="=";)n++;let a=e.slice(o,n),A,u=n;for(;u<r&&lm(e[u]);)u++;u<r&&e[u]==="="&&(A=e.slice(n,u+1),n=u+1);let c,l,d=n;for(;d<r&&lm(e[d]);)d++;if(d<r&&(e[d]==='"'||e[d]==="'")){let f=d+1,g=e.indexOf(e[d],f);g!==-1&&(c=e[d],l=e.slice(f,g),n=g+1)}let h={startIndex:i};h[1]=s,h[2]=a,h[3]=A,h[4]=c!==void 0?!0:void 0,h[5]=c,h[6]=l,t.push(h)}return t}function pBe(e,t){let r=Ght(e),n={};for(let i=0;i<r.length;i++){if(r[i][1].length===0)return fn("InvalidAttr","Attribute '"+r[i][2]+"' has no space in starting.",nQ(r[i]));if(r[i][3]!==void 0&&r[i][4]===void 0)return fn("InvalidAttr","Attribute '"+r[i][2]+"' is without value.",nQ(r[i]));if(r[i][3]===void 0&&!t.allowBooleanAttributes)return fn("InvalidAttr","boolean attribute '"+r[i][2]+"' is not allowed.",nQ(r[i]));let s=r[i][2];if(!Wht(s))return fn("InvalidAttr","Attribute '"+s+"' is an invalid name.",nQ(r[i]));if(!Object.prototype.hasOwnProperty.call(n,s))n[s]=1;else return fn("InvalidAttr","Attribute '"+s+"' is repeated.",nQ(r[i]))}return!0}function Yht(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 Vht(e,t){if(t++,e[t]===";")return-1;if(e[t]==="#")return t++,Yht(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 fn(e,t,r){return{err:{code:e,msg:t,line:r.line||r,col:r.col}}}function Wht(e){return _5(e)}function qht(e){return _5(e)}function ls(e,t){let r=e.substring(0,t).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function nQ(e){return e.startIndex+e[1].length}var O5={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 iQ={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},P5={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 dm=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),Jht=new Set("!?\\\\/[]$%{}^&*()<>|+");function mBe(e){if(e[0]==="#")throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${e}"`);for(let t of e)if(Jht.has(t))throw new Error(`[EntityReplacer] Invalid character '${t}' in entity name: "${e}"`);return e}function sQ(...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 bg="external",Rx="base",H5="all";function jht(e){return!e||e===bg?new Set([bg]):e===H5?new Set([H5]):e===Rx?new Set([Rx]):Array.isArray(e)?new Set(e):new Set([bg])}var js=Object.freeze({allow:0,leave:1,remove:2,throw:3}),$ht=new Set([9,10,13]);function Kht(e){if(!e)return{xmlVersion:1,onLevel:js.allow,nullLevel:js.remove};let t=e.xmlVersion===1.1?1.1:1,r=js[e.onNCR]??js.allow,n=js[e.nullNCR]??js.remove,i=Math.max(n,js.remove);return{xmlVersion:t,onLevel:r,nullLevel:i}}var hm=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=jht(this._limit.applyLimitsTo??bg),this._numericAllowed=t.numericAllowed??!0,this._baseMap=sQ(iQ,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=Kht(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===dm.BLOCK)return!1;if(s===dm.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))mBe(i);if(!this._onExternalEntity){this._externalMap=sQ(t);return}let r=sQ(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){mBe(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=sQ(t);return}let r=sQ(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 d=t.slice(o+1,l);if(d.length===0){o++;continue}let h,f;if(this._removeSet.has(d))h="",f===void 0&&(f=bg);else if(this._leaveSet.has(d)){o++;continue}else if(d.charCodeAt(0)===35){let g=this._resolveNCR(d);if(g===void 0){o++;continue}h=g,f=Rx}else{let g=this._resolveName(d);h=g?.value,f=g?.tier}if(h===void 0){o++;continue}if(o>s&&n.push(t.slice(s,o)),n.push(h),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=h.length-(d.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(H5)?!0:this._limitTiers.has(t)}_resolveName(t){if(t in this._inputMap)return{value:this._inputMap[t],tier:bg};if(t in this._externalMap)return{value:this._externalMap[t],tier:bg};if(t in this._baseMap)return{value:this._baseMap[t],tier:Rx}}_classifyNCR(t){return t===0?this._ncrNullLevel:t>=55296&&t<=57343||this._ncrXmlVersion===1&&t>=1&&t<=31&&!$ht.has(t)?js.remove:-1}_applyNCRAction(t,r,n){switch(t){case js.allow:return String.fromCodePoint(n);case js.remove:return"";case js.leave:return;case js.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<js.remove)return;let s=i===-1?this._ncrOnLevel:Math.max(this._ncrOnLevel,i);return this._applyNCRAction(s,t,n)}};var IBe=e=>rQ.includes(e)?"__"+e:e,Xht={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:IBe};function zht(e,t){if(typeof e!="string")return;let r=e.toLowerCase();if(rQ.some(n=>r===n.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);if(Nx.some(n=>r===n.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`)}function CBe(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"}:CBe(!0)}var BBe=function(e){let t=Object.assign({},Xht,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&&zht(n,i);return t.onDangerousProperty===null&&(t.onDangerousProperty=IBe),t.processEntities=CBe(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 wg;typeof Symbol!="function"?wg="@@xmlMetadata":wg=Symbol("XML Node Metadata");var $s=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][wg]={startIndex:t})}addEndIndex(t){let r=this.child[this.child.length-1];r!==void 0&&r[wg]!==void 0&&r[wg].endIndex===void 0&&(r[wg].endIndex=t)}static getMetaDataSymbol(){return wg}};var yBe=":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",Zht=yBe+"\\-\\.\\d\xB7\u0300-\u036F\u203F-\u2040",QBe=":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}",eft=QBe+"\\-\\.\\d\xB7\u0300-\u036F\u0487\u203F-\u2040",G5=(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)}},tft=G5(yBe,Zht),rft=G5(QBe,eft,"u"),bBe=":A-Za-z_",nft=bBe+"\\-\\.\\d",ift=G5(bBe,nft),sft=(e="1.0",t=!1)=>t?ift:e==="1.1"?rft:tft;var Y5=(e,{xmlVersion:t="1.0",asciiOnly:r=!1}={})=>sft(t,r).qName.test(e);var aQ=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&&Sg(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&&Sg(t,"!ELEMENT",r)){r+=8;let{index:c}=this.readElementExp(t,r+1);r=c}else if(o&&Sg(t,"!ATTLIST",r))r+=8;else if(o&&Sg(t,"!NOTATION",r)){r+=9;let{index:c}=this.readNotationExp(t,r+1,this.suppressValidationErr);r=c}else if(Sg(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=Ks(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(oQ(i,{xmlVersion:this.xmlVersion}),r=Ks(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=Ks(t,r);let n=r;for(;r<t.length&&!/\s/.test(t[r]);)r++;let i=t.substring(n,r);!this.suppressValidationErr&&oQ(i,{xmlVersion:this.xmlVersion}),r=Ks(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=Ks(t,r);let o=null,a=null;if(s==="PUBLIC")[r,o]=this.readIdentifierVal(t,r,"publicIdentifier"),r=Ks(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=Ks(t,r);let n=r;for(;r<t.length&&!/\s/.test(t[r]);)r++;let i=t.substring(n,r);if(!this.suppressValidationErr&&!Y5(i,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid element name: "${i}"`);r=Ks(t,r);let s="";if(t[r]==="E"&&Sg(t,"MPTY",r))r+=4;else if(t[r]==="A"&&Sg(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=Ks(t,r);let n=r;for(;r<t.length&&!/\s/.test(t[r]);)r++;let i=t.substring(n,r);for(oQ(i,{xmlVersion:this.xmlVersion}),r=Ks(t,r),n=r;r<t.length&&!/\s/.test(t[r]);)r++;let s=t.substring(n,r);if(!oQ(s,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid attribute name: "${s}"`);r=Ks(t,r);let o="";if(t.substring(r,r+8).toUpperCase()==="NOTATION"){if(o="NOTATION",r+=8,r=Ks(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(),!oQ(c,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid notation name: "${c}"`);A.push(c),t[r]==="|"&&(r++,r=Ks(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=Ks(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}}},Ks=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function Sg(e,t,r){for(let n=0;n<t.length;n++)if(t[n]!==e[r+n+1])return!1;return!0}function oQ(e,t){if(Y5(e,{xmlVersion:t}))return e;throw new Error(`Invalid entity name ${e}`)}var oft=[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],xx=255,vx=new Map,wBe=65535,SBe=1632,fm=SBe,aft=wBe-SBe+1,kx=new Uint8Array(aft).fill(xx);for(let e of oft)for(let t=0;t<10;t++){let r=e+t;r<=wBe?kx[r-fm]=t:vx.set(r,t)}var TBe=48,DBe=57,NBe=45,Lx=new Set([8722,65293,65123]);function Aft(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>=TBe&&s<=DBe||s===NBe)){if(s<fm){if(Lx.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(vx.has(a)){r=i;break}}}continue}if(kx[s-fm]!==xx||Lx.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>=TBe&&s<=DBe||s===NBe){n.push(e[i]);continue}if(s<fm){n.push(Lx.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=vx.get(A);if(u!==void 0){n.push(String.fromCharCode(u+48)),i++;continue}}}n.push(e[i]);continue}if(Lx.has(s)){n.push("-");continue}let o=kx[s-fm];n.push(o!==xx?String.fromCharCode(o+48):e[i])}return n.join("")}var RBe=Aft;var uft=/^[-+]?0x[a-fA-F0-9]+$/,cft=/^0b[01]+$/,lft=/^0o[0-7]+$/,dft=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,hft={hex:!0,binary:!1,octal:!1,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original",unicode:!1};function W5(e,t={}){if(t=Object.assign({},hft,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=RBe(r),r==="0"))return 0;if(t.hex&&uft.test(r))return V5(r,16);if(t.binary&&cft.test(r))return V5(r,2);if(t.octal&&lft.test(r))return V5(r,8);if(isFinite(r)){if(r.includes("e")||r.includes("E"))return gft(e,r,t);{let n=dft.exec(r);if(n){let i=n[1]||"",s=n[2],o=pft(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 Eft(e,Number(r),t)}var fft=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function gft(e,t,r){if(!r.eNotation)return e;let n=t.match(fft);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 pft(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 V5(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 Eft(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 q5(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 Tg=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(),d=a.substring(c+1).trim();["first","last","odd","even"].includes(d)||/^nth\(\d+\)$/.test(d)?(A=l,u=d):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 gm=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 J5=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)}},pm=class{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new J5(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,d=i!==null?i.keep:null;if(d!=null&&d.length>0&&r)for(let h=0;h<d.length;h++){let f=d[h];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 mft=[{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}],Em=mft;var Ift=[{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:/\?>/}],mm=Ift;var Cft=[{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}],j5=Cft;var Bft=[{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}],AQ=Bft;var yft=[{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}],$5=yft;var Qft=[{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,}\)/}],K5=Qft;var _o=`["'\\s]*:`,bft=[{id:"nosql-where-operator",description:"$where \u2014 executes arbitrary JavaScript server-side in MongoDB",pattern:new RegExp(`\\$where${_o}`,"i")},{id:"nosql-ne-operator",description:'$ne \u2014 "not equal" operator used to bypass equality checks',pattern:new RegExp(`\\$ne${_o}`,"i")},{id:"nosql-gt-operator",description:'$gt \u2014 "greater than" used to bypass password/value checks',pattern:new RegExp(`\\$gte?${_o}`,"i")},{id:"nosql-lt-operator",description:'$lt / $lte \u2014 "less than" bypass variants',pattern:new RegExp(`\\$lte?${_o}`,"i")},{id:"nosql-regex-operator",description:"$regex \u2014 can be used to extract data character by character (blind injection)",pattern:new RegExp(`\\$regex${_o}`,"i")},{id:"nosql-or-operator",description:"$or \u2014 logical OR; used to create always-true conditions",pattern:new RegExp(`\\$or${_o}\\s*\\[`,"i")},{id:"nosql-and-operator",description:"$and \u2014 logical AND operator injection",pattern:new RegExp(`\\$and${_o}\\s*\\[`,"i")},{id:"nosql-nor-operator",description:"$nor \u2014 logical NOR operator injection",pattern:new RegExp(`\\$nor${_o}\\s*\\[`,"i")},{id:"nosql-exists-operator",description:"$exists \u2014 can enumerate fields to determine schema",pattern:new RegExp(`\\$exists${_o}`,"i")},{id:"nosql-in-operator",description:"$in \u2014 matches any value in a list; can enumerate values",pattern:new RegExp(`\\$in${_o}\\s*\\[`,"i")},{id:"nosql-expr-operator",description:"$expr \u2014 allows aggregation expressions in queries (MongoDB 3.6+)",pattern:new RegExp(`\\$expr${_o}`,"i")},{id:"nosql-function-operator",description:"$function \u2014 executes arbitrary JavaScript in MongoDB 4.4+",pattern:new RegExp(`\\$function${_o}`,"i")},{id:"nosql-accumulator-operator",description:"$accumulator \u2014 custom aggregation with arbitrary JS execution",pattern:new RegExp(`\\$accumulator${_o}`,"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__["']\]/}],X5=bft;var wft=[{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\[/}],z5=wft;var Sft=[{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}],Tft=[...AQ,...Sft],Z5=Tft;Em.label="HTML";mm.label="XML";j5.label="SVG";AQ.label="SQL";Z5.label="SQL-STRICT";$5.label="SHELL";K5.label="REDOS";X5.label="NOSQL";z5.label="LOG";var E3t=Object.freeze({HTML:Em,XML:mm,SVG:j5,SQL:AQ,"SQL-STRICT":Z5,SHELL:$5,REDOS:K5,NOSQL:X5,LOG:z5});function Dft(e){if(typeof e!="string")throw new TypeError(`is-unsafe: first argument must be a string, got ${typeof e}`)}function Nft(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 Rft(e){return e instanceof RegExp?{lists:null,regex:e}:Array.isArray(e[0])?{lists:e,regex:null}:{lists:[e],regex:null}}function xft(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 xBe(e,t){Dft(e),Nft(t);let{lists:r,regex:n}=Rft(t);if(n)return n.test(e);for(let i of r)if(xft(e,i)!==null)return!0;return!1}function vft(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 kft(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 uQ=class{constructor(t,r){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=_ft,this.parseTextData=Lft,this.resolveNameSpace=Mft,this.buildAttributesMap=Uft,this.isItStopNode=Gft,this.replaceEntitiesValue=Pft,this.readStopNodeData=Wft,this.saveTextToParentTag=Hft,this.addChild=Oft,this.ignoreAttributesFn=q5(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.doctypefound=!1;let n={...iQ};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:(typeof this.options.htmlEntities=="object"?n=this.options.htmlEntities:this.options.htmlEntities===!0&&(n={...P5,...O5}),this.entityDecoder=new hm({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)=>xBe(o,[Em,mm])?dm.BLOCK:dm.ALLOW})),this.matcher=new pm,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new gm;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 Tg(o)):o instanceof Tg&&this.stopNodeExpressionsSet.add(o)}this.stopNodeExpressionsSet.seal()}}};function Lft(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?rG(e,a.parseTagValue,a.numberParseOptions):e}}function Mft(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 Fft=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Uft(e,t,r,n=!1){let i=this.options;if(n===!0||i.ignoreAttributes!==!0&&typeof e=="string"){let s=dBe(e,Fft),o=s.length,a={},A=new Array(o),u=!1,c={};for(let h=0;h<o;h++){let f=this.resolveNameSpace(s[h][1]),g=s[h][4];if(f.length&&g!==void 0){let p=g;i.trimValues&&(p=p.trim()),p=this.replaceEntitiesValue(p,r,this.readonlyMatcher),A[h]=p,c[f]=p,u=!0}}u&&typeof t=="object"&&t.updateCurrent&&t.updateCurrent(c);let l=i.jPath?t.toString():this.readonlyMatcher,d=!1;for(let h=0;h<o;h++){let f=this.resolveNameSpace(s[h][1]);if(this.ignoreAttributesFn(f,l))continue;let g=i.attributeNamePrefix+f;if(f.length)if(i.transformAttributeName&&(g=i.transformAttributeName(g)),g=vBe(g,i),s[h][4]!==void 0){let p=A[h],m=i.attributeValueProcessor(f,p,l);m==null?a[g]=p:typeof m!=typeof p||m!==p?a[g]=m:a[g]=rG(p,i.parseAttributeValue,i.numberParseOptions),d=!0}else i.allowBooleanAttributes&&(a[g]=!0,d=!0)}if(!d)return;if(i.attributesGroupName&&!i.preserveOrder){let h={};return h[i.attributesGroupName]=a,h}return a}}var _ft=function(e){e=e.replace(/\r\n?/g,`
|
|
472
472
|
`);let t=new $s("!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 aQ(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=Im(e,">",a,"Closing Tag is not closed."),l=e.substring(a+2,c).trim();if(i.removeNSPrefix){let h=l.indexOf(":");h!==-1&&(l=l.substr(h+1))}l=eG(i.transformTagName,l,"",i).tagName,r&&(n=this.saveTextToParentTag(n,r,this.readonlyMatcher));let d=this.matcher.getCurrentTag();if(l&&i.unpairedTagsSet.has(l))throw new Error(`Unpaired tag can not be used as closing tag: </${l}>`);d&&i.unpairedTagsSet.has(d)&&(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=tG(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 d=l[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(d)||1),s.setXmlVersion(Number(d)||1)}if(!(i.ignoreDeclaration&&c.tagName==="?xml"||i.ignorePiTags)){let d=new $s(c.tagName);d.add(i.textNodeName,""),c.tagName!==c.tagExp&&c.attrExpPresent&&i.ignoreAttributes!==!0&&(d[":@"]=l),this.addChild(r,d,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=Im(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=Im(e,"]]>",a,"CDATA is not closed.")-2,l=e.substring(a+9,c);n=this.saveTextToParentTag(n,r,this.readonlyMatcher);let d=this.parseTextData(l,r.tagname,this.readonlyMatcher,!0,!1,!0,!0);d==null&&(d=""),i.cdataPropName?r.add(i.cdataPropName,[{[i.textNodeName]:l}]):r.add(i.textNodeName,d),a=c+2}else{let c=tG(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,d=c.rawTagName,h=c.tagExp,f=c.attrExpPresent,g=c.closeIndex;if({tagName:l,tagExp:h}=eG(i.transformTagName,l,h,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;h.length>0&&h.lastIndexOf("/")===h.length-1&&(m=!0,l[l.length-1]==="/"?(l=l.substr(0,l.length-1),h=l):h=h.substr(0,h.length-1),f=l!==h);let I=null,C={},B;B=kft(d),l!==t.tagname&&this.matcher.push(l,{},B),l!==h&&f&&(I=this.buildAttributesMap(h,this.matcher,l),I&&(C=vft(I,i))),l!==t.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());let b=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,d,g+1);if(!S)throw new Error(`Unexpected end of ${d}`);a=S.i,D=S.tagContent}let N=new $s(l);I&&(N[":@"]=I),N.add(i.textNodeName,D),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(r,N,this.readonlyMatcher,b),i.captureMetaData&&r.addEndIndex(a+1)}else{if(m){({tagName:l,tagExp:h}=eG(i.transformTagName,l,h,i));let D=new $s(l);I&&(D[":@"]=I),this.addChild(r,D,this.readonlyMatcher,b),i.captureMetaData&&r.addEndIndex(g+1),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(i.unpairedTagsSet.has(l)){let D=new $s(l);I&&(D[":@"]=I),this.addChild(r,D,this.readonlyMatcher,b),i.captureMetaData&&r.addEndIndex(c.closeIndex+1),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=c.closeIndex;continue}else{let D=new $s(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,b),r=D}n="",a=g}}}else n+=e[a];return t.child};function Oft(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 Pft(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 Hft(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 Gft(){return this.stopNodeExpressionsSet.size===0?!1:this.matcher.matchesAny(this.stopNodeExpressionsSet)}function Yft(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 Im(e,t,r,n){let i=e.indexOf(t,r);if(i===-1)throw new Error(n);return i+t.length-1}function Vft(e,t,r,n){let i=e.indexOf(t,r);if(i===-1)throw new Error(n);return i}function tG(e,t,r,n=">"){let i=Yft(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 Wft(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=Vft(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=Im(e,"?>",r+1,"StopNode is not closed.");else if(o===33&&e.charCodeAt(r+2)===45&&e.charCodeAt(r+3)===45)r=Im(e,"-->",r+3,"StopNode is not closed.");else if(o===33&&e.charCodeAt(r+2)===91)r=Im(e,"]]>",r,"StopNode is not closed.")-2;else{let a=tG(e,r,!1);a&&((a&&a.tagName)===t&&a.tagExp[a.tagExp.length-1]!=="/"&&i++,r=a.closeIndex)}}}function rG(e,t,r){if(t&&typeof e=="string"){let n=e.trim();return n==="true"?!0:n==="false"?!1:W5(e,r)}else return hBe(e)?e:""}function eG(e,t,r,n){if(e){let i=e(t);r===t&&(r=i),t=i}return t=vBe(t,n),{tagName:t,tagExp:r}}function vBe(e,t){if(Nx.includes(e))throw new Error(`[SECURITY] Invalid name: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);return rQ.includes(e)?t.onDangerousProperty(e):e}var nG=$s.getMetaDataSymbol();function qft(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 iG(e,t,r,n){return kBe(e,t,r,n)}function kBe(e,t,r,n){let i,s={};for(let o=0;o<e.length;o++){let a=e[o],A=Jft(a);if(A!==void 0&&A!==t.textNodeName){let u=qft(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=kBe(a[A],t,r,n),c=$ft(u,t);if(Object.keys(u).length===0&&t.alwaysCreateTextNode&&(u[t.textNodeName]=""),a[":@"]?jft(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[nG]!==void 0&&typeof u=="object"&&u!==null&&(u[nG]=a[nG]),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 Jft(e){let t=Object.keys(e);for(let r=0;r<t.length;r++){let n=t[r];if(n!==":@")return n}}function jft(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 $ft(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 Xd=class{constructor(t){this.externalEntities={},this.options=BBe(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=EBe(t,r);if(s!==!0)throw Error(`${s.err.msg}:${s.err.line}:${s.err.col}`)}let n=new uQ(this.options,this.externalEntities),i=n.parseXml(t);return this.options.preserveOrder||i===void 0?i:iG(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 $s.getMetaDataSymbol()}};mn();mn();function Xs(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 LBe(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 cQ(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 ae.IS_DEV&&i(r.hostname)&&i(n.hostname)&&r.port===String(ae.DEV_PORT)}catch{return!1}}mn();import lQ from"crypto";import Mx from"fs";import Kft from"path";var oG="dango_lan_auth",Xft=720*60*60*1e3;function sG(){return Kft.join(Pn.ROOT,"lan_sessions.json")}function aG(){try{if(!Mx.existsSync(sG()))return{};let e=Mx.readFileSync(sG(),"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&&dQ(t),t}catch{return{}}}function dQ(e){try{Mx.mkdirSync(Pn.ROOT,{recursive:!0}),Mx.writeFileSync(sG(),JSON.stringify(e))}catch{}}function MBe(){return process.env.APP_PASSWORD_HASH||Pn.APP_PASSWORD_HASH||""}function zd(){return!!MBe()}function AG(e){let t=lQ.randomBytes(16).toString("hex"),r=lQ.scryptSync(e,t,32).toString("hex");return`scrypt:${t}:${r}`}function FBe(e){return Fx(e,MBe())}function Fx(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=lQ.scryptSync(e,n,32),o=Buffer.from(i,"hex");return s.length!==o.length?!1:lQ.timingSafeEqual(s,o)}catch{return!1}}async function UBe(e){let{updateEnvFile:t}=await Promise.resolve().then(()=>(Bh(),RL));if(!e){await t({APP_PASSWORD_HASH:""}),Pn.APP_PASSWORD_HASH="";return}let r=AG(e);await t({APP_PASSWORD_HASH:r}),Pn.APP_PASSWORD_HASH=r}function _Be(){let e=lQ.randomBytes(32).toString("hex"),t=Date.now()+Xft,r=aG();return r[e]=t,dQ(r),{token:e,expiry:t}}function hQ(e){if(!e)return!1;let t=aG(),r=t[e];return r?r<Date.now()?(delete t[e],dQ(t),!1):!0:!1}function OBe(e){if(!e)return;let t=aG();t[e]&&(delete t[e],dQ(t))}function PBe(){dQ({})}function zft(e){return e?e.startsWith("::ffff:")?e.slice(7):e:""}function uG(e){let t=zft(e);return t==="127.0.0.1"||t==="::1"}function Cm(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()===oG)return decodeURIComponent(n.slice(i+1).trim())||null}}return null}var HBe=new Set(["/api/auth/app-status","/api/auth/app-login","/api/auth/app-logout","/api/internal/shutdown"]);function GBe(e,t){let r=Math.max(1,Math.floor((t-Date.now())/1e3));return`${oG}=${encodeURIComponent(e)}; HttpOnly; Path=/; Max-Age=${r}; SameSite=Lax`}function YBe(){return`${oG}=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax`}var fQ=Ao("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:Ln("lastPage"),updatedAt:Ln("updatedAt"),anilistId:Ln("anilistId"),anilistIdSource:Ge("anilistIdSource")},e=>[zo({columns:[e.id]})]),$3t=Ao("manga_progress",{mangaId:Ge("mangaId").notNull(),chapterId:Ge("chapterId").notNull(),chapterNumber:Ge("chapterNumber"),page:Ln("page"),pageCount:Ln("pageCount"),updatedAt:Ln("updatedAt"),title:Ge("title"),cover:Ge("cover"),provider:Ge("provider"),altTitle:Ge("altTitle"),contentRating:Ge("contentRating")},e=>[zo({columns:[e.mangaId,e.chapterId]})]);var VBe=["watchlist","watched_episodes","queue","shows_meta","dismissed_notifications","discovered_notifications","legacy_id_mapping","temp_show_ids"],WBe=["manga_library","manga_progress"],qBe=["tv_library","tv_progress"],JBe=["asmr_library","asmr_progress"];async function Ux(e,t){let r={};for(let n of t)try{let i=await te(e).all(Q`SELECT COUNT(*) AS rows FROM ${Q.raw(`"${n}"`)}`);r[n]=i[0]?.rows??0}catch{r[n]=0}return r}async function _x(e,t){for(let r of t)try{await te(e).run(Q`DELETE FROM ${Q.raw(`"${r}"`)}`)}catch{}}function Bm(e){let t=Q.raw(`"${e}"`);return{getById:async(r,n)=>(await te(r).all(Q`SELECT * FROM ${t} WHERE id = ${n}`))[0],getAll:(r,n,i,s)=>{let o=Q`SELECT * FROM ${t}`;return n&&n!=="All"&&o.append(Q` WHERE status = ${n}`),o.append(Q` ORDER BY updatedAt DESC`),i!==void 0&&s!==void 0&&o.append(Q` LIMIT ${i} OFFSET ${s}`),te(r).all(o)},getCount:async(r,n)=>n&&n!=="All"?(await te(r).all(Q`SELECT COUNT(*) as total FROM ${t} WHERE status = ${n}`))[0]?.total||0:(await te(r).all(Q`SELECT COUNT(*) as total FROM ${t}`))[0]?.total||0,getIds:async r=>(await te(r).all(Q`SELECT id FROM ${t}`)).map(i=>i.id),updateStatus:(r,n,i)=>te(r).run(Q`
|
package/server/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as B,A as F,h as P,q as x,g as U,u as e,L as We,T as Q,S as oe,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 Oe,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 ne,h as re,i as lt,j as it,k as ct,l as Ie,M as dt,T as ut,n as ht,o as pt,r as Me,v as mt,w as gt,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-Cd1-bH35.js";import{b as St,u as kt,a as Ct}from"./vendor-query-BBT5_sHx.js";import{M as ge,P as It}from"./MediaCard-BikTKuG3.js";import{A as ce}from"./AnimeCard-DeOILoQY.js";import{S as ze,A as je}from"./SkeletonGrid-BpsynMj7.js";import{I as W}from"./vendor-icons-DrybRNxP.js";import{u as At}from"./vendor-ui-3qrARCPr.js";import{E as Ae}from"./ErrorMessage-DAxegITP.js";import{R as Ge}from"./ResetProgressModal-YVCqneQ5.js";import{Q as Rt}from"./QueueRail-DqyZVaD-.js";import{u as Ue,M as Qe}from"./useMangaPopup-B5LPCa2N.js";import{M as Lt}from"./MangaResetProgressModal-C1Bfn9O_.js";import{u as Ye,m as Se,i as He,a as Xe,b as $t}from"./useMangaLibrary-DAPvo2xZ.js";import{u as Mt}from"./useProviders-DsY_iifL.js";import{u as Ke,a as Be,T as Bt}from"./useTv-olJK7WfQ.js";import{T as Pt}from"./TvPopup-RchqnXJt.js";import{u as xt,a as Et,b as Dt}from"./useTvLibrary-Deie_gJF.js";import{A as qt}from"./AsmrResetProgressModal-BAp7wa4X.js";import{u as Wt,a as Ot,A as Vt,b as Ft,c as zt}from"./AsmrPopup-BW-iFW3L.js";import"./useIsMobile-Dvx1uJ82.js";import"./MatureConsentModal-Do1CtwDw.js";import"./useAnimeInfoData-l7nCKCe5.js";import"./QueueOptionsButton-CUyJPdwg.js";import"./playbackCompletion-ZhAwimeL.js";import"./usePopup-DS9jMzp6.js";import"./libraryInvalidation-BHknhNAw.js";const jt="_sectionWrapper_10ckl_9",Gt="_sectionTitleNoMargin_10ckl_13",Ut="_carousel_10ckl_189",M={"section-header":"_section-header_10ckl_1",sectionWrapper:jt,sectionTitleNoMargin:Gt,"title-wrapper":"_title-wrapper_10ckl_17","header-controls":"_header-controls_10ckl_24","header-select":"_header-select_10ckl_31","collapse-button":"_collapse-button_10ckl_80","title-link":"_title-link_10ckl_100","continue-watching":"_continue-watching_10ckl_119","nav-arrows":"_nav-arrows_10ckl_141","nav-button":"_nav-button_10ckl_147","carousel-container":"_carousel-container_10ckl_189",carousel:Ut,"carousel-inner":"_carousel-inner_10ckl_198","carousel-card":"_carousel-card_10ckl_203"};function ve({align:n="start",containScroll:l="trimSnaps",scrollFraction:h=.8,threshold:t=.6,onReachThreshold:o,slideCount:i=0}={}){const[g,s]=At({align:n,containScroll:l,dragFree:!0}),[k,y]=B(!1),[N,p]=B(!1),c=F({scrollFraction:h,threshold:t,onReachThreshold:o}),r=F(!1);P(()=>{c.current={scrollFraction:h,threshold:t,onReachThreshold:o}});const w=x(m=>{y(m.canScrollPrev()),p(m.canScrollNext())},[]);P(()=>{if(!s)return;const m=()=>{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",m),s.on("reInit",m),s.on("scroll",m),s.on("resize",m),()=>{s.off("init",m),s.off("reInit",m),s.off("scroll",m),s.off("resize",m)}},[s,w]),P(()=>{s?.reInit()},[s,i]);const C=x(m=>{const u=m.containerNode().firstElementChild;if(!u)return 1;const b=m.rootNode().getBoundingClientRect().width,A=u.getBoundingClientRect().width;return A?Math.max(1,Math.round(b/A)):1},[]),S=x((m,u=!1)=>{if(!s)return;const b=Math.max(1,Math.round(C(s)*c.current.scrollFraction)),A=s.selectedScrollSnap()+(m==="left"?-b:b);s.scrollTo(A,u)},[s,C]),d=x((m=!1)=>{s?.scrollTo(0,m)},[s]);return{emblaRef:g,api:s,canScrollPrev:k,canScrollNext:N,stepBy:S,scrollToStart:d}}const Z=({title:n,eyebrow:l,titleLink:h,loading:t,emptyState:o,carousel:i,layout:g,collapsible:s,defaultExpanded:k=!0,onReachThreshold:y,scrollThreshold:N,isFetchingNextPage:p,resetScrollOnShrink:c,itemCount:r=0,highlight:w,headerActions:C,loadingSkeleton:S,skeletonCount:d=7,children:m})=>{const{lowEndMode:u}=ke(),{emblaRef:b,stepBy:A,scrollToStart:O,canScrollPrev:R,canScrollNext:E}=ve({onReachThreshold:y,threshold:N,slideCount:r}),[L,V]=U.useState(k);U.useEffect(()=>{V(k)},[k]);const z=U.useRef(0);return U.useEffect(()=>{c&&r>0&&L&&(r<=z.current||z.current===0)&&O(),r>0&&(z.current=r)},[r,c,L,O]),!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(We,{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&&(R||E)&&e("div",{className:M["nav-arrows"],children:[R&&e("button",{className:M["nav-button"],type:"button","aria-label":"Scroll left",onClick:I=>{I.preventDefault(),A("left",u)},children:e(W,{name:"chevron-left"})}),E&&e("button",{className:M["nav-button"],type:"button","aria-label":"Scroll right",onClick:I=>{I.preventDefault(),A("right",u)},children:e(W,{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(W,{name:"chevron-up"}):e(W,{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:b,children:e("div",{className:M["carousel-inner"],children:[t&&r===0?Array.from({length:d}).map((I,G)=>e("div",{className:M["carousel-card"],children:S},G)):U.Children.map(m,(I,G)=>e("div",{className:M["carousel-card"],children:I},U.isValidElement(I)&&I.key!=null?I.key:`slide-${G}`)),p&&S&&e("div",{className:M["carousel-card"],children:S})]})})}):e("div",{className:"grid-container",children:t&&r===0?e(ze,{count:6,layout:g}):r>0?m:t?null:e("div",{style:{gridColumn:"1 / -1"},children:o})}))]})},Qt=({title:n,eyebrow:l,animeList:h,continueWatching:t,titleLink:o,onRemove:i,loading:g,emptyState:s,carousel:k,cardConfig:y,layout:N,onReachThreshold:p,scrollThreshold:c,isFetchingNextPage:r,collapsible:w,defaultExpanded:C=!0})=>{const S=N||"vertical";return e(Z,{title:n,eyebrow:l,titleLink:o,loading:g,emptyState:s,carousel:k,layout:S,collapsible:w,defaultExpanded:C,onReachThreshold:p,scrollThreshold:c,isFetchingNextPage:r,resetScrollOnShrink:t,highlight:t,itemCount:h.length,loadingSkeleton:e(je,{layout:S}),skeletonCount:7,children:h.map(d=>e(ce,{anime:d,continueWatching:t,onRemove:i,config:y,layout:S},d._id))})},Pe=U.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(W,{name:"chevron-down",size:12,className:we.arrow})]}),Kt="_sectionWrapper_1dwd0_2",Zt="_sectionTitleNoMargin_1dwd0_6",Jt="_carouselContainer_1dwd0_94",ea="_carousel_1dwd0_94",ta="_carouselInner_1dwd0_105",aa="_carouselItem_1dwd0_110",na="_rankCard_1dwd0_147",ra="_rankPill_1dwd0_151",oa="_rankGold_1dwd0_162",sa="_rankSilver_1dwd0_166",la="_rankBronze_1dwd0_170",ia="_skeletonPoster_1dwd0_181",ca="_skeletonText_1dwd0_182",v={sectionWrapper:Kt,sectionTitleNoMargin:Zt,"section-header":"_section-header_1dwd0_11","title-wrapper":"_title-wrapper_1dwd0_19","header-actions":"_header-actions_1dwd0_39","nav-arrows":"_nav-arrows_1dwd0_45","nav-button":"_nav-button_1dwd0_51",carouselContainer:Jt,carousel:ea,carouselInner:ta,carouselItem:aa,rankCard:na,rankPill:ra,rankGold:oa,rankSilver:sa,rankBronze:la,skeletonPoster:ia,skeletonText:ca},xe="TRENDING_DESC",da="POPULARITY_DESC",ua=10;function ha({title:n,eyebrow:l}){const{lowEndMode:h}=ke(),[t,o]=ie("trending_sort",xe),i=[{value:xe,label:"Trending"},{value:da,label:"All Time"}],{data:g,fetchNextPage:s,hasNextPage:k,isFetchingNextPage:y,isLoading:N,isError:p,error:c}=tt(t,ua),r=Q(()=>g?.pages.flatMap(u=>u)||[],[g]),w=x(()=>{k&&!y&&!N&&s()},[k,y,N,s]),{emblaRef:C,stepBy:S,canScrollPrev:d,canScrollNext:m}=ve({onReachThreshold:w,slideCount:r.length});return e("section",{className:v.sectionWrapper,children:[e("div",{className:v["section-header"],children:[e("div",{className:v["title-wrapper"],children:e("div",{className:"title-stack",children:[l&&e("div",{className:"section-eyebrow",children:l}),e("div",{className:`section-title ${v.sectionTitleNoMargin}`,children:n})]})}),e("div",{className:v["header-actions"],children:[e(J,{ariaLabel:"Trending sort",width:120,value:t,options:i,onChange:o}),(d||m)&&e("div",{className:v["nav-arrows"],children:[d&&e("button",{className:v["nav-button"],type:"button",onClick:u=>{u.preventDefault(),S("left",h)},"aria-label":"Scroll left",children:e(W,{name:"chevron-left"})}),m&&e("button",{className:v["nav-button"],type:"button",onClick:u=>{u.preventDefault(),S("right",h)},"aria-label":"Scroll right",children:e(W,{name:"chevron-right"})})]})]})]}),N?e("div",{className:v.carouselContainer,children:e("div",{className:v.carousel,children:e("div",{className:v.carouselInner,children:Array.from({length:7}).map((u,b)=>e("div",{className:v.carouselItem,children:[e("div",{className:v.skeletonPoster}),e("div",{className:v.skeletonText})]},b))})})}):p?e(Ae,{message:c instanceof Error?c.message:"An unknown error occurred"}):e("div",{className:v.carouselContainer,children:e("div",{className:v.carousel,ref:C,children:e("div",{className:v.carouselInner,children:[r.map((u,b)=>e("div",{className:v.carouselItem,children:[e("div",{className:v.rankCard,children:e(ce,{anime:u})}),e("div",{className:`${v.rankPill} ${b===0?v.rankGold:b===1?v.rankSilver:b===2?v.rankBronze:""}`,children:b+1})]},u._id)),y&&e("div",{className:v.carouselItem,style:{minWidth:"150px",display:"flex",alignItems:"center",justifyContent:"center"},children:e("div",{className:v.skeletonPoster})})]})})})]})}const pa=[{value:"TV",label:"TV"},{value:"ONA",label:"ONA"},{value:"OVA",label:"OVA"},{value:"MOVIE",label:"Movie"},{value:"ALL",label:"All"},{value:"ADULT",label:"Mature"}],ma=10;function ga({eyebrow:n}){const{lowEndMode:l}=ke(),[h,t]=ie("latest_releases_format","TV"),{data:o,fetchNextPage:i,hasNextPage:g,isFetchingNextPage:s,isLoading:k,isError:y,error:N}=at(h,ma),p=Q(()=>o?.pages.flatMap(d=>d)||[],[o]),c=x(()=>{g&&!s&&!k&&i()},[g,s,k,i]),{emblaRef:r,stepBy:w,canScrollPrev:C,canScrollNext:S}=ve({onReachThreshold:c,slideCount:p.length});return e("section",{className:v.sectionWrapper,children:[e("div",{className:v["section-header"],children:[e("div",{className:v["title-wrapper"],children:e("div",{className:"title-stack",children:[n&&e("div",{className:"section-eyebrow",children:n}),e("div",{className:`section-title ${v.sectionTitleNoMargin}`,children:"Latest Releases"})]})}),e("div",{className:v["header-actions"],children:[e(J,{ariaLabel:"Latest releases format",width:120,value:h,options:pa,onChange:t}),(C||S)&&e("div",{className:v["nav-arrows"],children:[C&&e("button",{className:v["nav-button"],type:"button",onClick:d=>{d.preventDefault(),w("left",l)},"aria-label":"Scroll left",children:e(W,{name:"chevron-left"})}),S&&e("button",{className:v["nav-button"],type:"button",onClick:d=>{d.preventDefault(),w("right",l)},"aria-label":"Scroll right",children:e(W,{name:"chevron-right"})})]})]})]}),k?e("div",{className:v.carouselContainer,children:e("div",{className:v.carousel,children:e("div",{className:v.carouselInner,children:Array.from({length:7}).map((d,m)=>e("div",{className:v.carouselItem,children:[e("div",{className:v.skeletonPoster}),e("div",{className:v.skeletonText})]},m))})})}):y?e(Ae,{message:N instanceof Error?N.message:"An unknown error occurred"}):e("div",{className:v.carouselContainer,children:e("div",{className:v.carousel,ref:r,children:e("div",{className:v.carouselInner,children:[p.map(d=>e("div",{className:v.carouselItem,children:e(ce,{anime:d})},d._id)),s&&e("div",{className:v.carouselItem,style:{minWidth:"150px",display:"flex",alignItems:"center",justifyContent:"center"},children:e("div",{className:v.skeletonPoster})})]})})})]})}const va="_scheduleSection_1o82r_1",_a="_sectionTitleRow_1o82r_5",ya="_sectionTitleNoMargin_1o82r_11",ba="_sectionHeader_1o82r_15",fa="_headerActions_1o82r_25",Ta="_daySelectorContainer_1o82r_33",Na="_daySelector_1o82r_33",wa="_daySelectorInner_1o82r_50",Sa="_dayBtn_1o82r_61",ka="_active_1o82r_84",Ca="_dayMonth_1o82r_92",Ia="_dayNum_1o82r_100",Aa="_dayName_1o82r_106",Ra="_navArrows_1o82r_119",La="_navButton_1o82r_125",$a="_carouselContainer_1o82r_168",Ma="_carousel_1o82r_168",Ba="_carouselInner_1o82r_180",Pa="_carouselCard_1o82r_185",$={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:Aa,navArrows:Ra,navButton:La,carouselContainer:$a,carousel:Ma,carouselInner:Ba,carouselCard:Pa},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}`},xa=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),g=F(!0),{data:s=[],isLoading:k,error:y}=St({queryKey:[Oe.schedule,l,t],queryFn:()=>xa(l,t),staleTime:1e3*60*5}),{emblaRef:N,canScrollPrev:p,canScrollNext:c,stepBy:r,scrollToStart:w}=ve({slideCount:s.length}),C=Q(()=>{const d=[],m=new Date,u=de(m),b=new Date(m);b.setDate(m.getDate()-1);const A=de(b),O=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];for(let R=-6;R<=6;R++){const E=new Date(m);E.setDate(m.getDate()+R),d.push(E)}return d.map(R=>{const E=de(R),z=E===u?"Today":E===A?"Yest":O[R.getDay()],I=R.getDate(),G=new Intl.DateTimeFormat("en-US",{month:"short"}).format(R);return{dateString:E,dayLabel:z,dayNum:I,monthName:G}})},[]);P(()=>{const d=i.current,m=d?.querySelector(`[data-date="${l}"]`);if(!d||!m)return;const u=d.getBoundingClientRect(),b=m.getBoundingClientRect(),A=d.scrollLeft+(b.left-u.left)-(u.width-b.width)/2;d.scrollTo({left:Math.max(0,A),behavior:g.current?"auto":"smooth"}),g.current=!1},[l]),P(()=>{w(!0)},[l,w]);const S=[{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:S,onChange:o}),s.length>0&&(p||c)&&e("div",{className:$.navArrows,children:[p&&e("button",{className:$.navButton,onClick:()=>r("left"),"aria-label":"Scroll left",children:e(W,{name:"chevron-left"})}),c&&e("button",{className:$.navButton,onClick:()=>r("right"),"aria-label":"Scroll right",children:e(W,{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:k?Array.from({length:7}).map((d,m)=>e("div",{className:$.carouselCard,children:e(je,{layout:"vertical"})},m)):y?e("div",{style:{width:"100%"},children:e(Ae,{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,layout:"vertical"},d._id)},d._id))})})})]})},Da="_bannerContainer_1oqya_1",qa="_hero_1oqya_28",Wa="_ambient_1oqya_37",Oa="_ambientShow_1oqya_49",Va="_scrim_1oqya_53",Fa="_progressLine_1oqya_70",za="_paused_1oqya_90",ja="_dots_1oqya_104",Ga="_dot_1oqya_104",Ua="_dotActive_1oqya_127",Qa="_viewport_1oqya_138",Ya="_track_1oqya_145",Ha="_slide_1oqya_151",Xa="_slideInner_1oqya_159",Ka="_poster_1oqya_169",Za="_posterLandscape_1oqya_180",Ja="_info_1oqya_204",en="_kicker_1oqya_209",tn="_featureLabel_1oqya_216",an="_scoreChip_1oqya_228",nn="_rise_1oqya_246",rn="_active_1oqya_250",on="_metaRow_1oqya_306",sn="_metaItem_1oqya_317",ln="_metaDivider_1oqya_323",cn="_title_1oqya_330",dn="_genres_1oqya_346",un="_genreTag_1oqya_354",hn="_summary_1oqya_365",pn="_actions_1oqya_377",mn="_watchBtn_1oqya_384",gn="_detailsBtn_1oqya_413",vn="_navArrow_1oqya_434",_n="_prevArrow_1oqya_467",yn="_nextArrow_1oqya_471",_={bannerContainer:Da,hero:qa,ambient:Wa,ambientShow:Oa,scrim:Va,progressLine:Fa,paused:za,dots:ja,dot:Ga,dotActive:Ua,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:pn,watchBtn:mn,detailsBtn:gn,navArrow:vn,prevArrow:_n,nextArrow:yn},bn=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,g]=B(0),[s,k]=B(!1),[y,N]=B(null),[p,c]=B(0),[r,w]=B({front:"",back:"",flip:!1}),C=F(0),S=F(0),d=F(new Set),m=F(null),u=F(0),b=x(a=>a.bannerSrc,[]),A=x(()=>{g(a=>a+1)},[]),O=x(a=>{m.current!==null&&(window.clearTimeout(m.current),m.current=null),N(null),A();const f=b(n[a]);w(T=>T.flip?{front:f,back:T.back,flip:!1}:{front:T.front,back:f,flip:!0}),o(a)},[A,n,b]),R=x(a=>{if(n.length===0)return;const f=(a%n.length+n.length)%n.length;d.current.has(b(n[f]))?O(f):N(f)},[n,b,O]);P(()=>{let a=!1;return n.forEach(f=>{const T=b(f);if(!T||d.current.has(T))return;const D=new Image;D.src=T;const X=()=>{a||d.current.has(T)||(d.current.add(T),c(j=>j+1))};D.onload=X,D.onerror=X}),()=>{a=!0}},[n,b]),P(()=>{if(n.length!==0&&!r.front){const a=b(n[0]);w({front:a,back:"",flip:!1})}},[n,r.front,b]),P(()=>{if(y!==null){if(y<0||y>=n.length){N(null);return}d.current.has(b(n[y]))&&O(y)}},[y,p,n,b,O]),P(()=>{if(y===null)return;m.current!==null&&window.clearTimeout(m.current);const a=y;return m.current=window.setTimeout(()=>{m.current=null,O(a)},2500),()=>{m.current!==null&&(window.clearTimeout(m.current),m.current=null)}},[y,O]);const E=x(a=>{R(a)},[R]),L=x(()=>{R(u.current+1)},[R]),V=x(()=>{R(u.current-1)},[R]),z=F(null);if(P(()=>{const a=z.current;if(!a)return;const f=T=>{if(Math.abs(T.deltaY)>Math.abs(T.deltaX)&&Math.abs(T.deltaY)>5){T.preventDefault(),T.stopPropagation();const D=Date.now();if(D-C.current<300)return;C.current=D,A(),T.deltaY>0?L():V()}};return a.addEventListener("wheel",f,{passive:!1}),()=>a.removeEventListener("wheel",f)},[n.length,L,V,A]),P(()=>{if(n.length===0||s)return;const a=setTimeout(L,bn);return()=>clearTimeout(a)},[t,L,n.length,i,s]),P(()=>{const a=f=>{const T=f.target;T&&(T.tagName==="INPUT"||T.tagName==="TEXTAREA"||T.tagName==="SELECT"||T.isContentEditable)||(f.key==="ArrowRight"?(f.preventDefault(),L()):f.key==="ArrowLeft"&&(f.preventDefault(),V()))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[L,V]),P(()=>{t>=n.length&&o(0)},[n.length,t]),n.length===0)return null;const I=t>=n.length?0:t;u.current=I;const G=a=>{S.current=a.touches[0].clientX},H=a=>{const T=a.changedTouches[0].clientX-S.current;Math.abs(T)>50&&(A(),T>0?V():L())};return e("div",{className:_.bannerContainer,onMouseEnter:()=>k(!0),onMouseLeave:()=>k(!1),children:e("div",{className:`${_.hero} ${s?_.paused:""}`,onTouchStart:G,onTouchEnd:H,children:[r.front&&e("img",{src:r.front,alt:"","aria-hidden":"true",className:`${_.ambient} ${r.flip?"":_.ambientShow}`}),r.back&&e("img",{src:r.back,alt:"","aria-hidden":"true",className:`${_.ambient} ${r.flip?_.ambientShow:""}`}),e("div",{className:_.scrim,"aria-hidden":"true"}),n.length>1&&e("div",{className:_.progressLine,"aria-hidden":"true"},`progress-${i}-${I}`),n.length>1&&e("div",{className:_.dots,ref:z,role:"tablist","aria-label":"Spotlight slides",children:n.map((a,f)=>e("button",{role:"tab","aria-selected":f===I,"aria-label":`Go to slide ${f+1}: ${a.title}`,className:`${_.dot} ${f===I?_.dotActive:""}`,onClick:()=>E(f),tabIndex:f===I?0:-1},a.key))}),e("div",{className:_.viewport,children:e("div",{className:_.track,style:{transform:`translateX(-${I*100}%)`},children:n.map((a,f)=>e("div",{className:`${_.slide} ${f===I?_.active:""}`,"aria-hidden":f!==I,children:e("div",{className:_.slideInner,children:[e("img",{src:a.posterSrc,alt:a.posterAlt,className:l==="landscape"?_.posterLandscape:_.poster,decoding:"async"}),e("div",{className:_.info,children:[e("div",{className:`${_.kicker} ${_.rise}`,children:[e("span",{className:_.featureLabel,children:h}),a.score!==void 0&&a.score!==null&&a.score!==""&&e("span",{className:_.scoreChip,children:[e(W,{name:"star",size:12}),e("span",{children:a.score})]})]}),e(We,{to:a.detailTo,className:`${_.title} ${_.rise}`,"aria-label":`View details for ${a.title}`,tabIndex:f===I?0:-1,children:a.title}),a.metaItems.length>0&&e("div",{className:`${_.metaRow} ${_.rise}`,children:a.metaItems.map((T,D)=>e(U.Fragment,{children:[e("span",{className:_.metaItem,children:T}),D<a.metaItems.length-1&&e("div",{className:_.metaDivider})]},D))}),a.tags.length>0&&e("div",{className:`${_.genres} ${_.rise}`,children:a.tags.slice(0,3).map(T=>e("span",{className:_.genreTag,children:T},T))}),a.synopsis&&e("p",{className:`${_.summary} ${_.rise}`,children:a.synopsis}),e("div",{className:`${_.actions} ${_.rise}`,children:[e("button",{className:_.watchBtn,onClick:a.onPrimary,tabIndex:f===I?0:-1,children:[e(W,{name:a.primaryIcon,size:14}),e("span",{children:a.primaryLabel})]}),e("button",{className:_.detailsBtn,onClick:a.onDetails,tabIndex:f===I?0:-1,children:[e(W,{name:"info-circle",size:15}),e("span",{children:"Details"})]})]})]})]})},a.key))})}),n.length>1&&e(oe,{children:[e("button",{className:`${_.navArrow} ${_.prevArrow}`,onClick:()=>{A(),V()},"aria-label":"Previous slide",children:e(W,{name:"chevron-left",size:20})}),e("button",{className:`${_.navArrow} ${_.nextArrow}`,onClick:()=>{A(),L()},"aria-label":"Next slide",children:e(W,{name:"chevron-right",size:20})})]})]})})},fn=({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(g=>!!g),tags:(o.genres??[]).slice(0,3).map(g=>typeof g=="string"?g:g?.name).filter(g=>!!g),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})},Tn="_emptyState_19tmt_1",Nn="_emptyStateIcon_19tmt_16",wn="_emptyStateTitle_19tmt_23",Sn="_emptyStateText_19tmt_30",he={emptyState:Tn,emptyStateIcon:Nn,emptyStateTitle:wn,emptyStateText:Sn},ye=({icon:n,text:l,actionLabel:h,onAction:t,title:o="Nothing is here..."})=>e("div",{className:he.emptyState,children:[e(W,{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})]}),kn="_tabBar_1mv4x_1",Cn="_tabIndicator_1mv4x_24",In="_tabButton_1mv4x_38",An="_tabActive_1mv4x_53",pe={tabBar:kn,tabIndicator:Cn,tabButton:In,tabActive:An};function Rn({options:n,value:l,onChange:h,ariaLabel:t},o){const i=F(null),g=F(new Map),s=F(null),[k,y]=B({left:0,width:0}),N=x((p,c)=>{const r=g.current.get(p),w=i.current;if(r&&w){const C=w.getBoundingClientRect(),S=r.getBoundingClientRect();y({left:S.left-C.left+w.scrollLeft,width:S.width}),c&&r.scrollIntoView({block:"nearest",inline:"nearest"})}},[]);return et(()=>{const p=s.current!==null&&s.current!==l;s.current=l,N(l,p)},[l,n.length,N]),P(()=>{if(N(l,!1),typeof ResizeObserver>"u")return;let p=0;const c=i.current;if(!c)return;const r=new ResizeObserver(()=>{cancelAnimationFrame(p),p=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(p),r.disconnect()}},[l,n.length,N]),e("div",{className:pe.tabBar,ref:p=>{i.current=p,typeof o=="function"?o(p):o&&(o.current=p)},"aria-label":t,children:[e("div",{className:pe.tabIndicator,style:{left:k.left,width:k.width}}),n.map(p=>e(Fe,{ref:c=>{c&&g.current.set(p.value,c)},variant:"secondary",size:"sm",className:`${pe.tabButton} ${l===p.value?pe.tabActive:""}`,onClick:()=>h(p.value),children:p.label},p.value))]})}const me=U.forwardRef(Rn),Ln=[{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:g}=Ye(),{popup:s,openPopup:k,scheduleClose:y,cancelClose:N,closePopup:p}=Ue(),{data:c,isLoading:r,fetchNextPage:w,hasNextPage:C,isFetchingNextPage:S}=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]),m=x(()=>{C&&!S&&!r&&w()},[C,S,r,w]);return e(oe,{children:[e(Z,{title:n,eyebrow:l,loading:r,carousel:!0,itemCount:d.length,headerActions:o,onReachThreshold:m,isFetchingNextPage:S,loadingSkeleton:e("div",{className:"skeleton",style:{aspectRatio:"3 / 4"}}),skeletonCount:7,children:d.map(u=>{const b=Se(u.provider,u.id);return e(ge,{item:{id:b,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:A=>k(A,{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:A=>A?N():y(),rawThumbnail:!0},`${u.provider}-${u.id}`)})}),s&&e(Qe,{data:s.data,anchorRect:s.rect,bookmarked:g.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:p})]})},$n=()=>{const{options:n}=Mt(),l=Q(()=>n.some(s=>s.kind==="manga"),[n]),{hasConsent:h}=ot(),[t,o]=ie("manga_discover_tab","latest"),[i,g]=ie("manga_trending_sort","popular");return l?e(oe,{children:[e(me,{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=>g(s.currentTarget.value),"aria-label":"Trending sort",children:Ln.map(s=>e("option",{value:s.value,children:s.label},s.value))})})]}):null},Mn=()=>{const n=ee(),{data:l,isLoading:h}=$t(24),[t,o]=B(null),{popup:i,openPopup:g,scheduleClose:s,cancelClose:k,closePopup:y}=Ue(),{toggle:N,bookmarkedIds:p}=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,S=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(ge,{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:S,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=>g(d,{provider:r.provider||"",mangaId:r.mangaId||"",title:r.title||"",altTitle:r.altTitle,cover:r.cover||"",contentRating:r.contentRating||void 0,readTarget:S}),onPopupHoverIntent:d=>d?k():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:p.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:k,onMouseLeave:s,onRequestClose:y}),e($n,{})]})},Bn="_emptyState_bpz5x_1",De={emptyState:Bn},Pn=[{value:"latest",label:"Latest Releases"},{value:"trending",label:"Trending"}],xn=[{value:"trending_week",label:"Trending Now"},{value:"trending_day",label:"Trending Today"},{value:"popular",label:"Popular All Time"},{value:"top_rated",label:"Top Rated"}],En=()=>{const n=ee(),{data:l,isLoading:h}=xt(24),t=Et(),o=Dt(),[i,g]=B(null),[s,k]=B(()=>ne.getItem("tv_home_activeTab")||"latest"),[y,N]=B("tv"),[p,c]=B("trending_week"),[r,w]=B("multi"),C=l?.data??[];U.useEffect(()=>{ne.setItem("tv_home_activeTab",s)},[s]);const S=p.startsWith("trending_"),d=p==="trending_day"?"day":"week",m={popular:"popularity.desc",top_rated:"vote_average.desc"},{data:u,isLoading:b}=Ke(r==="multi"?"all":r,d,1,S&&s==="trending"),{data:A,isLoading:O}=Be({type:r,sort_by:m[p]||"popularity.desc",page:1}),R=S?u?.results||[]:A?.results||[],E=S?b:O,{data:L,isLoading:V}=Be({type:y,sort_by:"primary_release_date.desc",page:1}),z=L?.results||[],I=a=>{i&&(o.mutate({mediaId:i.libId}),a&&t.mutate(i.libId))},G=x(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:z.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:z.map(G)});case"trending":return e(Z,{title:"Trending",eyebrow:"Discover",loading:E,carousel:!0,itemCount:R.length,headerActions:e(oe,{children:[e(J,{ariaLabel:"Trending sort",value:p,onChange:c,options:xn.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:R.map(G)})}};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 f=a.currentTime??0,T=a.duration??0,D=a.season??1,X=a.episode??1,j=a.mediaType==="movie",K=j?"Movie":`S${D} E${X}`,te=a.completed===1||T>0&&f>=T*.8,ae=te?100:T>0&&f>0?f/T*100:0,be=te?"Watched":T>0?j?`${re(f)} / ${re(T)}`:`${K} · ${re(f)} / ${re(T)}`:K;return e(ge,{item:{id:a.id,title:a.title||"",thumbnail:a.poster||"",typeBadge:j?"Movie":"TV",chapterBadge:K,isAdult:it({adult:a.adult===1})},linkTo:lt(a.mediaType,a.tmdbId??0,j?void 0:D,j?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:()=>g({libId:a.id,title:a.title||""}),renderPopup:(fe,se)=>e(Pt,{item:{id:a.tmdbId??0,title:a.title||"",year:a.year||"",type:a.mediaType||"tv",image:a.poster||""},anchorRect:fe,onMouseEnter:se.onMouseEnter,onMouseLeave:se.onMouseLeave,onRequestClose:se.close})},a.id)})}),e(me,{ariaLabel:"Browse TV",options:Pn,value:s,onChange:k}),e("div",{children:H()}),e(Ge,{isOpen:!!i,itemName:i?.title,progressKind:"watch",listLabel:"my TV watchlist",onClose:()=>{g(null)},onConfirm:I})]})};function qe(n){const l=n.currentTime??0,h=n.duration??0,t=(n.trackIndex??0)+1;return h>0?`Track ${t} · ${re(l)} / ${re(h)}`:n.trackLabel?`Track ${t} · ${n.trackLabel}`:`Track ${t}`}const Dn=({title:n="Continue Listening",limit:l=24,titleLink:h,showEmptyState:t=!0})=>{const o=ee(),{data:i,isLoading:g}=Wt(l),{toggle:s,bookmarkedIds:k}=Ot(),[y,N]=B(null),p=i?.data??[];return e(oe,{children:[e(Z,{title:n,eyebrow:"Pick up where you left off",titleLink:h??"/listening-list/Continue Listening",loading:g,carousel:!0,collapsible:!0,defaultExpanded:p.length>0,highlight:!0,itemCount:p.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:p.map(c=>{const r=c.currentTime??0,w=c.duration??0,C=c.rjCode||c.id;return e(ge,{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:qe(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:(S,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:qe(c)},anchorRect:S,bookmarked:k.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(qt,{workId:y?y.workId:null,title:y?.title,onClose:()=>N(null)})]})},qn=()=>e("div",{style:{paddingBottom:"2rem"},children:e(Dn,{})}),Wn=({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"})},On=({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(g=>!!g),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 Vn(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 Fn=({works:n})=>{const l=ee(),h=Q(()=>n.slice(0,6).map((t,o)=>{const i=ht(t),g=`/asmr/${encodeURIComponent(i)}`,s=Vn(t);return{key:i||t._id||String(o),bannerSrc:t.thumbnail||"",posterSrc:t.thumbnail||"",posterAlt:t.name,title:t.name,detailTo:g,metaItems:[t.rating?t.rating.toUpperCase():void 0,s?`${s} track${s===1?"":"s"}`:void 0].filter(k=>!!k),tags:[],synopsis:Ie(t.description,160,""),primaryLabel:"Listen Now",primaryIcon:"play",onPrimary:()=>l(g),onDetails:()=>l(g)}}),[n,l]);return e(_e,{slides:h,eyebrow:"ASMR Spotlight",posterAspect:"landscape"})},zn="_seasonGrid_168jc_34",le={"section-header":"_section-header_168jc_1","content-type-nav":"_content-type-nav_168jc_8","title-wrapper":"_title-wrapper_168jc_18","pagination-controls":"_pagination-controls_168jc_24",seasonGrid:zn},jn=[{value:"anime",label:"Anime"},{value:"manga",label:"Manga"},{value:"tv",label:"TV & Movies"},{value:"asmr",label:"ASMR"}],yr=()=>{const n=kt(),l=pt(),[h,t]=U.useState(1),[o,i]=B(()=>ne.getItem("home_activeTab")||"latest"),[g,s]=B(()=>ne.getItem("season_format")||"TV"),k=F(null),{data:y}=Me(h+1,g,o==="season"),{titlePreference:N}=Ve(),{contentType:p,setContentType:c}=mt(),[r,w]=U.useState(null),C=gt(),{data:S=[]}=vt(),d=_t(),m=yt(),u=bt();P(()=>{document.title="Home - dango"},[]);const{data:b,isLoading:A}=ft();P(()=>{ne.setItem("home_activeTab",o)},[o]),P(()=>{ne.setItem("season_format",g),t(1)},[g]),P(()=>{b!==void 0&&b.length===0&&o==="week"&&i("latest")},[b,o]);const{data:O,isLoading:R,fetchNextPage:E,hasNextPage:L,isFetchingNextPage:V}=Tt(),z=x(()=>{L&&!V&&!R&&E()},[L,V,R,E]),{data:I,isLoading:G}=Nt(),{data:H,isLoading:a}=Ke("all","week",1,p==="tv"),{data:f,isLoading:T}=zt(p==="asmr"),{data:D,isLoading:X}=wt(),j=Q(()=>O?.pages||[],[O]),{data:K,isLoading:te}=Me(h,g,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:[Oe.continueWatching]}),L&&j.length-1<14&&E()}})),se=x(q=>{const Y=j?.find(Te=>String(Te.id)===String(q));if(Y){const Te=Y[N]||Y.name;w({id:q,name:Te})}},[j,N]),Re=[{key:"latest",label:"Latest Releases"},{key:"season",label:"Current Season"},{key:"popular",label:"Trending"}],Le=b!==void 0&&b.length>0,Ze=Le?[{key:"week",label:"This Week"},...Re]:Re,$e=o==="week"&&!Le?"latest":o,Je=()=>{switch($e){case"latest":return e(ga,{eyebrow:"Fresh episodes"});case"season":return e("section",{style:{marginBottom:"2.5rem"},children:[e("div",{className:le["section-header"],ref:k,children:[e("div",{className:le["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:g,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:le["pagination-controls"],children:e(It,{page:h,canGoNext:be,onChange:q=>{if(t(q),k.current){const Y=k.current.getBoundingClientRect().top+window.scrollY-120;window.scrollTo({top:Y,behavior:"smooth"})}},isLoading:te})})]})]}),e("div",{className:`grid-container ${le.seasonGrid}`,style:{minHeight:"300px",alignContent:"start"},children:te?e(ze,{count:ae}):K?.slice(0,ae).map(q=>e(ce,{anime:q},q._id))})]});case"popular":return e(ha,{title:"Trending",eyebrow:"Discover"});case"week":return e(Pe,{title:"This Week",eyebrow:"Aired this week",animeList:b||[],continueWatching:!1,carousel:!0,loading:A});default:return null}};return e("div",{style:{paddingBottom:"2rem"},children:[p==="anime"&&(G&&!I?.length?e(ue,{}):I&&I.length>0&&e(fn,{animeList:I})),p==="tv"&&(a&&!H?.results?.length?e(ue,{}):H?.results&&H.results.length>0&&e(Wn,{items:H.results})),p==="manga"&&(X&&!D?.length?e(ue,{}):D&&D.length>0&&e(On,{mangaList:D})),p==="asmr"&&(T&&!f?.length?e(ue,{}):f&&f.length>0&&e(Fn,{works:f})),e("div",{className:le["content-type-nav"],children:e(me,{ariaLabel:"Content type",options:jn,value:p,onChange:c})}),p==="manga"?e(Mn,{}):p==="tv"?e(En,{}):p==="asmr"?e(qn,{}):e(oe,{children:[e(Pe,{title:"Continue Watching",eyebrow:"Pick up where you left off",titleLink:"/watchlist/Continue Watching",animeList:j,continueWatching:!0,carousel:!0,collapsible:!0,defaultExpanded:j.length>0,onRemove:se,loading:R,onReachThreshold:z,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(Rt,{title:"Queue",eyebrow:"Up next",items:S,onRemove:q=>d.mutate({showId:q.showId,episodeNumber:q.episodeNumber}),showClearAll:!0,onClear:()=>m.mutate(),onReorder:q=>u.mutate(q.map(Y=>({id:Y.id,showId:Y.showId,episodeNumber:Y.episodeNumber})))}),e(me,{ariaLabel:"Browse anime",options:Ze.map(q=>({value:q.key,label:q.label})),value:$e,onChange:i}),e("div",{children:Je()}),e(Ea,{eyebrow:"Never miss an episode"}),e(Ge,{isOpen:!!r,itemName:r?.name,progressKind:"watch",listLabel:"my watchlist",onClose:()=>{w(null)},onConfirm:q=>{r&&(fe.mutate({showId:r.id}),q&&C.mutate({id:r.id}))}})]})]})};export{yr as default};
|