import { core, primordials } from "ext:core/mod.js";
import { op_defer } from "ext:core/ops";
const {
PromisePrototypeThen,
TypeError,
indirectEval,
ReflectApply,
} = primordials;
const {
getAsyncContext,
setAsyncContext,
} = core;
import * as webidl from "ext:deno_webidl/00_webidl.js";
function checkThis(thisArg) {
if (thisArg !== null && thisArg !== undefined && thisArg !== globalThis) {
throw new TypeError("Illegal invocation");
}
}
function setImmediate(callback, ...args) {
const asyncContext = getAsyncContext();
return core.queueImmediate(() => {
const oldContext = getAsyncContext();
try {
setAsyncContext(asyncContext);
return ReflectApply(callback, globalThis, args);
} finally {
setAsyncContext(oldContext);
}
});
}
function setTimeout(callback, timeout = 0, ...args) {
checkThis(this);
if (typeof callback !== "function") {
const unboundCallback = webidl.converters.DOMString(callback);
callback = () => indirectEval(unboundCallback);
}
const unboundCallback = callback;
const asyncContext = getAsyncContext();
callback = () => {
const oldContext = getAsyncContext();
try {
setAsyncContext(asyncContext);
ReflectApply(unboundCallback, globalThis, args);
} finally {
setAsyncContext(oldContext);
}
};
timeout = webidl.converters.long(timeout);
return core.queueUserTimer(
core.getTimerDepth() + 1,
false,
timeout,
callback,
);
}
function setInterval(callback, timeout = 0, ...args) {
checkThis(this);
if (typeof callback !== "function") {
const unboundCallback = webidl.converters.DOMString(callback);
callback = () => indirectEval(unboundCallback);
}
const unboundCallback = callback;
const asyncContext = getAsyncContext();
callback = () => {
const oldContext = getAsyncContext(asyncContext);
try {
setAsyncContext(asyncContext);
ReflectApply(unboundCallback, globalThis, args);
} finally {
setAsyncContext(oldContext);
}
};
timeout = webidl.converters.long(timeout);
return core.queueUserTimer(
core.getTimerDepth() + 1,
true,
timeout,
callback,
);
}
function clearTimeout(id = 0) {
checkThis(this);
id = webidl.converters.long(id);
core.cancelTimer(id);
}
function clearInterval(id = 0) {
checkThis(this);
id = webidl.converters.long(id);
core.cancelTimer(id);
}
function unrefTimer(id) {
core.unrefTimer(id);
}
function refTimer(id) {
core.refTimer(id);
}
function defer(go) {
PromisePrototypeThen(op_defer(), () => go());
}
export {
clearInterval,
clearTimeout,
defer,
refTimer,
setImmediate,
setInterval,
setTimeout,
unrefTimer,
};