import { dispatchDurableServiceWorkerRegistrationUpdate, getDurableServiceWorkerRegistration, getDurableServiceWorkerRegistrationData, setServiceWorkerRegistrationState } from "./container.js";
import { caches } from "../../fetch/index.js";
import { index } from "../../content-index/index.js";
import { sync } from "../../sync/index.js";
import { periodicSync } from "../../periodic-sync/index.js";
import { serviceWorker } from "./container.js";
import { getOrigin } from "../../listen/index.js";
import { addEventListener, removeEventListener } from "../../events/schedule/schedule.js";
import { dispatchEvent } from "../../events/index.js";
import "../../fetch/dispatch.js";
import { dispatchWorkerEvent } from "./dispatch.js";
import { getInternalStorageBucket } from "../../storage-buckets/internal.js";
import { globalFetch } from "./global-fetch.js";
import { createServiceWorkerWorkerFetch } from "./worker-fetch.js";
import { importWorkerExtensions } from "./worker-extensions.js";
export async function onServiceWorkerWorkerData(data, internalBucket = getInternalStorageBucket()) {
    const registration = await getDurableServiceWorkerRegistration(internalBucket, data.serviceWorkerId, {
        isCurrentGlobalScope: true
    });
    const { protocol, origin } = new URL(registration.durable.baseURL || registration.durable.url);
    let imported = undefined;
    function getServiceWorkerModuleExports() {
        return imported;
    }
    Object.assign(globalThis, {
        _ORIGINAL_GLOBAL_FETCH: globalFetch,
        _GLOBAL_getServiceWorkerModuleExports: getServiceWorkerModuleExports,
        registration,
        caches,
        index,
        sync,
        periodicSync,
        serviceWorker,
        self: globalThis,
        isSecureContext: protocol === "https:",
        origin: origin || getOrigin(),
        addEventListener,
        removeEventListener,
        fetch: createServiceWorkerWorkerFetch(data, registration)
    });
    await import("./dispatchers/index.js");
    if (data.config?.extensions) {
        await importWorkerExtensions(data.config);
    }
    const url = new URL(registration.durable.url, registration.durable.baseURL);
    url.searchParams.set("importCacheBust", Date.now().toString());
    imported = await import(url.toString());
    if (registration.durable.registrationState === "pending" || registration.durable.registrationState === "installing") {
        try {
            // console.log("Installing service worker");
            await setRegistrationStatus("installing");
            await dispatchEvent({
                type: "install",
                virtual: true
            });
            // console.log("Installed service worker");
            await setRegistrationStatus("installed");
        }
        catch (error) {
            console.error("Error installing service worker", error);
            await setRegistrationStatus("pending");
        }
    }
    if (registration.durable.registrationState === "installed" || registration.durable.registrationState === "activating") {
        try {
            await setRegistrationStatus("activating");
            await dispatchEvent({
                type: "activate",
                virtual: true
            });
            await setRegistrationStatus("activated");
        }
        catch {
            await setRegistrationStatus("installed");
        }
    }
    // console.log(registration.durable.registrationState);
    if (registration.durable.registrationState === "activated") {
        await dispatchEvent({
            type: "activated",
            virtual: true
        });
        if (data.event) {
            await dispatchWorkerEvent(data.event, data);
        }
    }
    return registration;
    async function setRegistrationStatus(status) {
        const next = await setServiceWorkerRegistrationState(internalBucket, registration.durable.serviceWorkerId, status);
        // TODO change to an event
        await registration.update();
        return dispatchRegistrationUpdate(next);
    }
    async function dispatchRegistrationUpdate(update) {
        await dispatchDurableServiceWorkerRegistrationUpdate(update ?? await getDurableServiceWorkerRegistrationData(internalBucket, registration.durable.serviceWorkerId), {
            virtual: true
        });
    }
}
//# sourceMappingURL=worker.js.map