var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
export const recursiveFetch = (url, depth = 0) => __awaiter(void 0, void 0, void 0, function* () {
    if (depth > 5) {
        return { final: true, url };
    }
    const res = yield fetch(url, {
        headers: {
            'User-Agent': 'Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)'
        },
        redirect: 'manual'
    });
    let location = res.headers.get('Location');
    if (location && location.startsWith('/')) {
        location = new URL(location, url).toString();
    }
    if (res.status > 300 && res.status < 400 && location) {
        const recurse = yield recursiveFetch(location, depth + 1);
        if (recurse.final) {
            return recurse;
        }
    }
    return { final: true, url };
});
