import { fromRequestResponse } from "../../data/index.js";
import { createRespondWith, isDurableFetchEventData } from "../../fetch/index.js";
import { dispatchEvent } from "../../events/index.js";
import { ok } from "../../is.js";
import { dispatchScheduledDurableEvents } from "../../events/schedule/dispatch-scheduled.js";
import { listTransferable } from "./transferrable.js";
export async function dispatchWorkerEvent(event, context) {
    if (isDurableFetchEventData(event)) {
        return dispatchWorkerFetchEvent(event, context);
    }
    else {
        return dispatchScheduledDurableEvents({
            event
        });
    }
}
export async function dispatchWorkerFetchEvent(event, context) {
    let trackingIndex = -1;
    const { port } = context;
    if (!port) {
        // Dispatch as normal if no port
        return dispatchEvent(event);
    }
    const { promise, handled, respondWith } = createRespondWith();
    ok(promise);
    const dispatch = {
        ...event,
        handled,
        respondWith
    };
    // console.log("dispatching service worker event");
    const eventPromise = dispatchEvent(dispatch);
    const response = await Promise.any([
        promise,
        // Non resolving promise
        // But will reject if thrown
        eventPromise.then(() => new Promise(() => { }))
    ]);
    // console.log("Emit response");
    const { response: output } = await fromRequestResponse(event.request, response);
    emit({
        response: output
    });
    // const reader = response.body.getReader();
    //
    // let chunk;
    // do {
    //     chunk = await reader.read();
    //     if (!chunk.done) {
    //         emit({
    //             data: chunk.value
    //         });
    //     }
    // } while (chunk.done);
    await eventPromise;
    function emit(message) {
        const index = trackingIndex += 1;
        const complete = {
            ...message,
            index,
            type: "fetch:response"
        };
        try {
            port.postMessage(complete, listTransferable(complete));
        }
        catch (error) {
            console.error("Failed to emit", error);
            throw error;
        }
    }
}
//# sourceMappingURL=dispatch.js.map