UNPKG

@sebastianwessel/quickjs

Version:

A typescript package to execute JavaScript and TypeScript code in a WebAssembly QuickJS sandbox

47 lines (46 loc) 1.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.rejectAndFlushPendingHostPromises = exports.unregisterPendingHostPromise = exports.registerPendingHostPromise = void 0; const pendingHostPromises = new WeakMap(); const registerPendingHostPromise = (ctx, promise) => { const current = pendingHostPromises.get(ctx); if (current) { current.add(promise); return; } pendingHostPromises.set(ctx, new Set([promise])); }; exports.registerPendingHostPromise = registerPendingHostPromise; const unregisterPendingHostPromise = (ctx, promise) => { const current = pendingHostPromises.get(ctx); if (!current) { return; } current.delete(promise); if (current.size === 0) { pendingHostPromises.delete(ctx); } }; exports.unregisterPendingHostPromise = unregisterPendingHostPromise; const rejectAndFlushPendingHostPromises = async (ctx, message = 'Sandbox timed out before async host call finished.', maxWaitMs = 100) => { const current = pendingHostPromises.get(ctx); if (!current || current.size === 0) { return; } const pending = Array.from(current); for (const deferred of pending) { try { const errHandle = ctx.newError(new Error(message)); deferred.reject(errHandle); errHandle.dispose(); } catch { // ignore rejected/dead deferred or context teardown race } } await Promise.race([ Promise.allSettled(pending.map(p => p.settled)), new Promise(resolve => setTimeout(resolve, maxWaitMs)), ]); }; exports.rejectAndFlushPendingHostPromises = rejectAndFlushPendingHostPromises;