"use strict";
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.webHTTP = void 0;
const NOOP_1 = require("../../../../NOOP");
function webHTTP(window, opt) {
    const { fetch } = window;
    const serverMap = {};
    const http = {
        fetch: (input, init) => __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c, _d;
            if (input.startsWith('unit://')) {
                let _input = input.replace('unit://', 'http://');
                const url = new URL(_input);
                const { port, search } = url;
                const handler = serverMap[port || 8080];
                const req = {
                    headers: (_a = init.headers) !== null && _a !== void 0 ? _a : {},
                    search: search !== null && search !== void 0 ? search : '',
                    query: Object.fromEntries(new URLSearchParams(search)),
                    method: (_b = init.method) !== null && _b !== void 0 ? _b : 'GET',
                    path: (_c = url.pathname) !== null && _c !== void 0 ? _c : '/',
                    body: (_d = init.body) !== null && _d !== void 0 ? _d : '',
                };
                const res = yield handler(req);
                return new Response(res.body, {
                    status: res.status,
                    headers: res.headers,
                });
            }
            return fetch(input, init);
        }),
        listen: (port, handler) => {
            if (serverMap[port]) {
                throw new Error(`Port ${port} is already in use`);
            }
            serverMap[port] = handler;
            return NOOP_1.NOOP;
        },
        // @ts-ignore
        EventSource: window.EventSource,
    };
    return http;
}
exports.webHTTP = webHTTP;
//# sourceMappingURL=http.js.map