"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.__intercept__fetch = __intercept__fetch;
exports.__intercept__listen = __intercept__listen;
function __intercept__fetch(fetch) {
    return async (input, init, servers) => {
        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 = servers[port || 8080];
            if (!handler) {
                throw new Error('failed to fetch');
            }
            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 = await handler(req);
            return new Response(res.body, {
                status: res.status,
                headers: res.headers,
            });
        }
        return fetch(input, init);
    };
}
function __intercept__listen(listen) {
    return (port, handler, servers) => {
        if (servers[port]) {
            throw new Error(`port ${port} is already in use`);
        }
        servers[port] = handler;
        const unlisten = listen(port, handler);
        return () => {
            delete servers[port];
            unlisten();
        };
    };
}
//# sourceMappingURL=intercept.js.map