import { yieldToEventLoop } from "../utils/event-loop.js";
let reporter;
let nextActivityId = 0;
export function setCallbackActivityReporter(next) {
    reporter = next;
}
function beginActivity(descriptor) {
    const activeReporter = reporter;
    if (!activeReporter)
        return undefined;
    const activity = {
        ...descriptor,
        id: `callback_${++nextActivityId}`,
        startedAt: performance.now(),
    };
    activeReporter.started(activity);
    return { activity, reporter: activeReporter };
}
export function runSynchronousCallback(descriptor, callback) {
    const active = beginActivity(descriptor);
    if (!active)
        return callback();
    try {
        return callback();
    }
    finally {
        active.reporter.finished(active.activity.id);
    }
}
export async function runCallback(descriptor, callback) {
    const active = beginActivity(descriptor);
    if (!active)
        return callback();
    try {
        // Give the activity frame and the last healthy heartbeat a chance to leave
        // the engine before arbitrary callback code begins.
        await yieldToEventLoop();
        return await callback();
    }
    finally {
        active.reporter.finished(active.activity.id);
    }
}
//# sourceMappingURL=callback-activity.js.map