"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.intercept = intercept;
exports.defaultPort = defaultPort;
exports.searchToQuery = searchToQuery;
exports.requestToServerRequest = requestToServerRequest;
exports.serverResponseToResponse = serverResponseToResponse;
exports.__intercept__fetch = __intercept__fetch;
function intercept(opt, url) {
    const urls = Array.isArray(opt.urls) ? opt.urls : [opt.urls];
    for (const pattern of urls) {
        const regex = pattern.replace(/\*/g, '[^ ]*');
        if (url.match(new RegExp(regex))) {
            return true;
        }
    }
    return false;
}
function defaultPort(url) {
    let { port, protocol } = new URL(url);
    if (!port) {
        if (protocol === 'http:' || protocol === 'unit:') {
            port = '80';
        }
        else if (protocol === 'https:') {
            port = '443';
        }
    }
    return port;
}
function searchToQuery(search) {
    const query = Object.fromEntries(new URLSearchParams(search).entries());
    return query;
}
function requestToServerRequest(opt, url) {
    const { method = 'GET', headers = {} } = opt;
    const parsedUrl = new URL(url);
    const { pathname: path, protocol, hostname, origin, search } = new URL(url);
    let { port } = parsedUrl;
    if (!port) {
        if (protocol === 'http:' || protocol === 'unit:') {
            port = '80';
        }
        else if (protocol === 'https:') {
            port = '443';
        }
    }
    const query = searchToQuery(search);
    const { body } = new Request('', {
        method: 'POST',
        body: opt.body ?? '',
    });
    const request = {
        url,
        headers,
        body,
        path,
        hostname,
        origin,
        port,
        method,
        query,
        search,
        protocol,
    };
    return request;
}
function serverResponseToResponse(res) {
    if ([204, 304].includes(res.status)) {
        delete res.body;
    }
    const response = new Response(res.body, {
        status: res.status,
        headers: res.headers,
    });
    return response;
}
function __intercept__fetch(fetch) {
    return async (url, init, interceptors) => {
        for (const interceptor of interceptors) {
            if (intercept(interceptor.opt, url)) {
                const request = requestToServerRequest(init, url);
                const serverResponse = await interceptor.handler(request);
                const response = serverResponseToResponse(serverResponse);
                return response;
            }
        }
        return fetch(url, init);
    };
}
//# sourceMappingURL=intercept.js.map