"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * @module fetch
 */
const logger_1 = require("./logger");
const streams_1 = require("./fly/streams");
/**
 * Starts the process of fetching a network request.
 *
 * See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
 * @global
 * @param req - The direct URL or Request for the resource you wish to fetch
 * @param init - Options for the request
 * @return A Promise that resolves to a {@linkcode Response} object
 */
function fetch(req, init) {
    logger_1.logger.debug("fetch called", typeof req, typeof init);
    return new Promise(function fetchPromise(resolve, reject) {
        try {
            if (typeof req === "string") {
                req = new Request(req, init);
            }
            const url = req.url;
            init = {
                method: req.method,
                headers: req.headers && req.headers.toJSON() || {},
                timeout: init && init.timeout,
                readTimeout: init && init.readTimeout || 30 * 1000
            };
            if (!req.bodySource)
                bridge.dispatch("fetch", url, init, null, fetchCb);
            else if (typeof req.bodySource === 'string')
                bridge.dispatch("fetch", url, init, req.bodySource, fetchCb);
            else
                req.arrayBuffer().then(function fetchArrayBufferPromise(body) {
                    bridge.dispatch("fetch", url, init, body, fetchCb);
                }).catch(reject);
        }
        catch (err) {
            logger_1.logger.debug("err applying nativeFetch", err.toString());
            reject(err);
        }
        function fetchCb(err, nodeRes, nodeBody) {
            if (err && typeof err === "string" && err.includes("timeout"))
                return reject(new TimeoutError(err));
            if (err)
                return reject(new Error(err));
            resolve(new Response(streams_1.isFlyStream(nodeBody) ? streams_1.default(nodeBody) : nodeBody, nodeRes));
        }
    });
}
exports.fetch = fetch;
;
class TimeoutError extends Error {
}
exports.TimeoutError = TimeoutError;
//# sourceMappingURL=fetch.js.map