"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.crawlPage = exports.loadJson = exports.loadPage = exports.formatMagnet = void 0;
const node_fetch_1 = __importDefault(require("node-fetch"));
const cheerio_1 = __importDefault(require("cheerio"));
function formatMagnet(infoHash, name, trackers) {
    const trackersQueryString = trackers.length
        ? `&tr=${trackers.map(encodeURIComponent).join('&tr=')}`
        : '';
    return `magnet:?xt=urn:btih:${infoHash}&dn=${encodeURIComponent(name)}${trackersQueryString}`;
}
exports.formatMagnet = formatMagnet;
const defaultHeaders = {
    'User-Agent': `torrent-stream-server (+https://github.com/KiraLT/torrent-stream-server)`,
};
async function loadPage(url) {
    const response = await node_fetch_1.default(url, {
        headers: defaultHeaders,
        timeout: 5000,
    });
    if (!response.ok) {
        throw new Error('Failed to load results');
    }
    return response;
}
exports.loadPage = loadPage;
async function loadJson(url) {
    return loadPage(url).then((v) => v.json());
}
exports.loadJson = loadJson;
async function crawlPage(url) {
    const response = await loadPage(url);
    return {
        $: cheerio_1.default.load(await response.text()),
    };
}
exports.crawlPage = crawlPage;
