type CanvasCapabilityQueueState = { tails: Map>; }; declare global { var __canvasCapabilityQueueState: CanvasCapabilityQueueState | undefined; } function getQueueState() { if (!globalThis.__canvasCapabilityQueueState) { globalThis.__canvasCapabilityQueueState = { tails: new Map() }; } return globalThis.__canvasCapabilityQueueState; } export async function enqueueCanvasCapabilityExecution(params: { projectId: string; execute: () => Promise; }): Promise { const state = getQueueState(); const previous = state.tails.get(params.projectId) || Promise.resolve(); const execution = previous.catch(() => undefined).then(params.execute); const settledExecution = execution.then( () => undefined, () => undefined ); const tail = settledExecution.finally(() => { if (state.tails.get(params.projectId) === tail) { state.tails.delete(params.projectId); } }); state.tails.set(params.projectId, tail); return execution; } export function getCanvasCapabilityQueueDepth(projectId: string) { return getQueueState().tails.has(projectId) ? 1 : 0; }