47 lines
1001 B
JavaScript
47 lines
1001 B
JavaScript
export class CodeRunner {
|
|
constructor(cons) {
|
|
this.console = cons;
|
|
this.isRunning = false;
|
|
}
|
|
|
|
setCode(code) {
|
|
this.code = code;
|
|
}
|
|
|
|
async run() {
|
|
this.isRunning = true;
|
|
|
|
this.console.log("Running code...");
|
|
|
|
// Stored globally so lib.js can access it
|
|
globalThis.libInternalAbortController = new AbortController();
|
|
|
|
// Use RNG to prevent caching
|
|
const encodedText = encodeURIComponent(
|
|
this.code + `/*(tph): ${Math.random()}*/`,
|
|
);
|
|
|
|
try {
|
|
await import(`data:text/javascript;charset=utf-8,${encodedText}`);
|
|
} catch (error) {
|
|
this.console.log(error);
|
|
}
|
|
}
|
|
|
|
stop() {
|
|
this.isRunning = false;
|
|
|
|
globalThis.libInternalAbortController?.abort();
|
|
|
|
this.console.log("Stopping code...");
|
|
}
|
|
|
|
toggle() {
|
|
if (this.isRunning) {
|
|
this.stop();
|
|
} else {
|
|
this.run();
|
|
}
|
|
}
|
|
}
|