class HiAnime { constructor() { this.type = "anime-streaming"; this.version = "1.0.2"; this.baseUrl = "https://hianime.to"; } getSettings() { return { episodeServers: ["HD-1", "HD-2", "HD-3"], supportsSub: true, supportsDub: true, supportsHls: true }; } async _fetch(url, opts) { if (typeof fetch === "function") return fetch(String(url), opts || {}); const raw = Native.fetch( String(url), (opts && opts.method) ? String(opts.method) : "GET", JSON.stringify((opts && opts.headers) || {}), (opts && opts.body != null) ? String(opts.body) : "" ); try { return JSON.parse(raw || "{}"); } catch (e) { return { ok: false, status: 0, headers: {}, body: "" }; } } async _getText(url, headers) { const res = await this._fetch(String(url), { method: "GET", headers: headers || {} }); if (res && typeof res.text === "function") return String(await res.text()); return String(res.body || ""); } async _getJson(url, headers) { const res = await this._fetch(String(url), { method: "GET", headers: headers || {} }); if (res && typeof res.json === "function") { try { return await res.json(); } catch (e) { return {}; } } try { return JSON.parse(String(res.body || "{}")); } catch (e) { return {}; } } _decodeHtml(str) { return String(str || "") .replace(/\\u0026/g, "&") .replace(/&#(\d+);?/g, (m, dec) => { const n = parseInt(dec, 10); if (!isFinite(n)) return m; return String.fromCharCode(n); }) .replace(/"/g, '"') .replace(/'/g, "'") .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">"); } _norm(s) { return String(s || "") .toLowerCase() .replace(/(season|cour|part|uncensored|movie|ova|ona|special)/g, " ") .replace(/\d+(st|nd|rd|th)\b/g, (m) => m.replace(/st|nd|rd|th/g, "")) .replace(/[^a-z0-9\s]+/g, " ") .replace(/\s+/g, " ") .trim(); } _levSim(a, b) { a = String(a || ""); b = String(b || ""); if (!a || !b) return 0; const la = a.length, lb = b.length; const dp = Array.from({ length: la + 1 }, () => new Array(lb + 1).fill(0)); for (let i = 0; i <= la; i++) dp[i][0] = i; for (let j = 0; j <= lb; j++) dp[0][j] = j; for (let i = 1; i <= la; i++) { for (let j = 1; j <= lb; j++) { if (a[i - 1] === b[j - 1]) dp[i][j] = dp[i - 1][j - 1]; else dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]); } } const dist = dp[la][lb]; const maxLen = Math.max(la, lb) || 1; return 1 - dist / maxLen; } _parseDate(dateStr) { const s = String(dateStr || "").trim(); const m = s.match(/([A-Za-z]+)\s+(\d{1,2}),\s*(\d{4})/); if (!m) return { year: 0, month: 0, day: 0 }; const monthMap = { Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5, Jun: 6, Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12 }; const month = monthMap[m[1]] || 0; const day = parseInt(m[2], 10) || 0; const year = parseInt(m[3], 10) || 0; return { year, month, day }; } async _fetchSuggestMatches(queryStr) { const url = `${this.baseUrl}/ajax/search/suggest?keyword=${encodeURIComponent(queryStr)}`; const reply = await this._getJson(url, { "X-Requested-With": "XMLHttpRequest" }); const html = String((reply && reply.html) || ""); const regex = /[\s\S]*?

]*data-jname="([^"]+)"[^>]*>([^<]+)<\/h3>[\s\S]*?
\s*([^<]+)<\/span>/g; const matches = []; const all = [...html.matchAll(regex)]; for (let i = 0; i < all.length; i++) { const pageUrl = String(all[i][1] || "").trim(); if (!pageUrl || pageUrl.startsWith("search?")) continue; const jname = this._decodeHtml(String(all[i][2] || "").trim()); const title = this._decodeHtml(String(all[i][3] || "").trim()); const dateStr = String(all[i][4] || "").trim(); const startDate = this._parseDate(dateStr); const idMatch = pageUrl.match(/-(\d+)$/); const id = idMatch ? idMatch[1] : pageUrl; matches.push({ id, pageUrl, title, jname, normTitle: this._norm(title), normTitleJP: this._norm(jname), startDate }); } return matches; } async _fallbackSearchPageMatches(queryStr) { const url = `${this.baseUrl}/search?keyword=${encodeURIComponent(queryStr)}`; const html = await this._getText(url, {}); const regex = /]+title="([^"]+)"[^>]+data-id="(\d+)"/g; const matches = []; const all = [...html.matchAll(regex)]; for (let i = 0; i < all.length; i++) { const pageUrl = all[i][1]; const title = this._decodeHtml(all[i][2]); const id = all[i][3]; matches.push({ id, pageUrl: "watch/" + pageUrl, title, jname: "", normTitle: this._norm(title), normTitleJP: "", startDate: { year: 0, month: 0, day: 0 } }); } return matches; } _titleOk(m, targetNorm, targetNormJP) { if (!m) return false; const a = m.normTitle || ""; const b = m.normTitleJP || ""; if (!a && !b) return false; if (a === targetNorm || b === targetNormJP) return true; const inc = a.includes(targetNorm) || b.includes(targetNormJP) || targetNorm.includes(a) || targetNormJP.includes(b); if (inc) return true; const simA = this._levSim(a, targetNorm); const simB = this._levSim(b, targetNormJP); return (simA >= 0.72) || (simB >= 0.72); } _dateOk(m, start, strictMonth) { if (!start || !start.year) return true; const y = (m.startDate && m.startDate.year) || 0; const mo = (m.startDate && m.startDate.month) || 0; if (!y) return false; if (y !== start.year) return false; if (strictMonth) { if (!start.month) return true; return mo === start.month; } return true; } async search(query) { if (typeof query === "string") { query = { query, media: { startDate: { year: 0, month: 0, day: 0 } } }; } const q = String((query && query.query) || "").trim(); if (!q) return []; const media = (query && query.media) || {}; const start = (media && media.startDate) || { year: 0, month: 0, day: 0 }; const targetEn = media.englishTitle || media.english || media.titleEnglish || ""; const targetRo = media.romajiTitle || media.romaji || media.titleRomaji || ""; const targetNormJP = this._norm(this._decodeHtml(targetRo)); const targetNorm = this._norm(this._decodeHtml(targetEn || targetRo || q)); const subOrDub = query && query.dub ? "dub" : "sub"; let matches = await this._fetchSuggestMatches(q); if (!matches.length) return []; if (start && start.year) { let filtered = matches.filter(m => this._titleOk(m, targetNorm, targetNormJP) && this._dateOk(m, start, true)); if (!filtered.length) filtered = matches.filter(m => this._titleOk(m, targetNorm, targetNormJP) && this._dateOk(m, start, false)); if (!filtered.length) return []; filtered.sort((a, b) => { const sa = Math.max(this._levSim(a.normTitle, targetNorm), this._levSim(a.normTitleJP, targetNormJP)); const sb = Math.max(this._levSim(b.normTitle, targetNorm), this._levSim(b.normTitleJP, targetNormJP)); if (sb !== sa) return sb - sa; const am = (a.startDate && a.startDate.month) || 0; const bm = (b.startDate && b.startDate.month) || 0; const tm = start.month || 0; const da = tm ? Math.abs(am - tm) : 0; const db = tm ? Math.abs(bm - tm) : 0; return da - db; }); return filtered.map(m => ({ id: `${m.id}/${subOrDub}`, title: m.title, url: `${this.baseUrl}/${m.pageUrl}`, subOrDub })); } const queryNorm = this._norm(q); let filtered = matches.filter(m => this._titleOk(m, queryNorm, queryNorm)); if (!filtered.length) { const pageMatches = await this._fallbackSearchPageMatches(q); if (!pageMatches.length) return []; filtered = pageMatches.filter(m => { const a = m.normTitle || ""; if (!a) return false; if (a === queryNorm) return true; if (a.includes(queryNorm) || queryNorm.includes(a)) return true; return this._levSim(a, queryNorm) >= 0.72; }); if (!filtered.length) return []; filtered.sort((a, b) => { const la = (a.normTitle || "").length; const lb = (b.normTitle || "").length; if (la !== lb) return la - lb; return String(a.title || "").localeCompare(String(b.title || "")); }); } else { filtered.sort((a, b) => { const sa = Math.max(this._levSim(a.normTitle, queryNorm), this._levSim(a.normTitleJP, queryNorm)); const sb = Math.max(this._levSim(b.normTitle, queryNorm), this._levSim(b.normTitleJP, queryNorm)); return sb - sa; }); } return filtered.map(m => ({ id: `${m.id}/${subOrDub}`, title: m.title, url: `${this.baseUrl}/${m.pageUrl}`, subOrDub })); } async findEpisodes(animeId) { const parts = String(animeId || "").split("/"); const id = parts[0]; const subOrDub = parts[1] || "sub"; const json = await this._getJson( `${this.baseUrl}/ajax/v2/episode/list/${encodeURIComponent(id)}`, { "X-Requested-With": "XMLHttpRequest" } ); const html = String((json && json.html) || ""); const episodes = []; const regex = /]*class="[^"]*\bep-item\b[^"]*"[^>]*data-number="(\d+)"[^>]*data-id="(\d+)"[^>]*href="([^"]+)"[\s\S]*?
]*title="([^"]+)"/g; let m; while ((m = regex.exec(html)) !== null) { episodes.push({ id: `${m[2]}/${subOrDub}`, number: parseInt(m[1], 10), url: this.baseUrl + m[3], title: this._decodeHtml(m[4] || "") }); } return episodes; } async findEpisodeServer(episode, _server) { if (typeof episode === "string") { try { episode = JSON.parse(episode); } catch (e) {} } const parts = String((episode && episode.id) || "").split("/"); const id = parts[0]; const subOrDub = parts[1] || "sub"; const serverName = _server && _server !== "default" ? String(_server) : "HD-1"; if (serverName === "HD-4") return null; const serverJson = await this._getJson( `${this.baseUrl}/ajax/v2/episode/servers?episodeId=${encodeURIComponent(id)}`, { "X-Requested-With": "XMLHttpRequest" } ); const serverHtml = String((serverJson && serverJson.html) || ""); const regex = new RegExp( `]*class="item server-item"[^>]*data-type="${subOrDub}"[^>]*data-id="(\\\\d+)"[^>]*>\\\\s*]*>\\\\s*${serverName}\\\\s*`, "i" ); const mm = regex.exec(serverHtml); if (!mm) throw new Error(`Server "${serverName}" (${subOrDub}) not found`); const serverId = mm[1]; const sourcesJson = await this._getJson( `${this.baseUrl}/ajax/v2/episode/sources?id=${encodeURIComponent(serverId)}`, { "X-Requested-With": "XMLHttpRequest" } ); const embed = (sourcesJson && sourcesJson.link) ? String(sourcesJson.link) : ""; if (!embed) throw new Error("No embed link returned"); let decryptData = null; let requiredHeaders = {}; try { decryptData = await this.extractMegaCloud(embed); requiredHeaders = (decryptData && decryptData.headersProvided) ? decryptData.headersProvided : {}; } catch (e) { decryptData = null; } if (!decryptData) { decryptData = await this._getJson( `https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(embed)}`, {} ); requiredHeaders = { Referer: "https://megacloud.club/", Origin: "https://megacloud.club", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36", "X-Requested-With": "XMLHttpRequest" }; } const sources = (decryptData && decryptData.sources) ? decryptData.sources : []; const streamSource = sources.find((s) => s && s.type === "hls" && s.file) || sources.find((s) => s && s.type === "mp4" && s.file) || sources.find((s) => s && s.file); if (!streamSource || !streamSource.file) throw new Error("No valid stream file found"); const tracks = (decryptData && decryptData.tracks) ? decryptData.tracks : []; const subtitles = (tracks || []) .filter((t) => t && String(t.kind || "").toLowerCase() === "captions" && t.file) .map((track, index) => ({ id: `sub-${index}`, language: String(track.label || "Unknown"), url: String(track.file), isDefault: !!track.default })); return { server: serverName, headers: requiredHeaders || {}, videoSources: [ { url: String(streamSource.file), type: String(streamSource.type || "").toLowerCase() === "hls" ? "m3u8" : "mp4", quality: "auto", subtitles } ] }; } async extractMegaCloud(embedUrl) { const u = new URL(String(embedUrl)); const protocol = String(u.protocol || "https:").replace(":", ""); const host = String(u.host || ""); const baseDomain = `${protocol}://${host}/`; const headers = { Accept: "*/*", "X-Requested-With": "XMLHttpRequest", Referer: baseDomain, Origin: `${protocol}://${host}`, "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36" }; const html = await this._getText(embedUrl, headers); const fileIdMatch = html.match(/\s*File\s+#([a-zA-Z0-9]+)\s*-/i); if (!fileIdMatch) throw new Error("file_id not found in embed page"); const fileId = fileIdMatch[1]; let nonce = null; const match48 = html.match(/\b[a-zA-Z0-9]{48}\b/); if (match48) nonce = match48[0]; if (!nonce) { const match3x16 = [...html.matchAll(/["']([A-Za-z0-9]{16})["']/g)]; if (match3x16.length >= 3) nonce = match3x16[0][1] + match3x16[1][1] + match3x16[2][1]; } if (!nonce) throw new Error("nonce not found"); const sourcesJson = await this._getJson( `${baseDomain}embed-2/v3/e-1/getSources?id=${encodeURIComponent(fileId)}&_k=${encodeURIComponent(nonce)}`, headers ); return { sources: sourcesJson.sources || [], tracks: sourcesJson.tracks || [], intro: sourcesJson.intro || null, outro: sourcesJson.outro || null, server: sourcesJson.server || null, headersProvided: headers }; } } module.exports = new HiAnime();