module-based literate programming
This commit is contained in:
parent
9ef9d57f13
commit
b9218c8ace
7 changed files with 183 additions and 106 deletions
|
@ -1,26 +1,50 @@
|
|||
console = {
|
||||
let outputIndex = 0;
|
||||
|
||||
let debugLog = console.log;
|
||||
|
||||
globalThis.console = {
|
||||
log(...message) {
|
||||
postMessage({
|
||||
kind: "output",
|
||||
output: {
|
||||
kind: "log",
|
||||
message: [...message],
|
||||
}
|
||||
},
|
||||
outputIndex,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
addEventListener("message", event => {
|
||||
async function withTemporaryGlobalScope(callback) {
|
||||
let state = {
|
||||
oldValues: {},
|
||||
set(key, value) {
|
||||
this.oldValues[key] = globalThis[key];
|
||||
globalThis[key] = value;
|
||||
}
|
||||
};
|
||||
await callback(state);
|
||||
for (let key in state.oldValues) {
|
||||
globalThis[key] = state.oldValues[key];
|
||||
}
|
||||
}
|
||||
|
||||
addEventListener("message", async event => {
|
||||
let message = event.data;
|
||||
if (message.action == "eval") {
|
||||
outputIndex = 0;
|
||||
try {
|
||||
let func = new Function(message.input);
|
||||
let result = func.apply({});
|
||||
postMessage({
|
||||
kind: "output",
|
||||
output: {
|
||||
kind: "result",
|
||||
message: [result],
|
||||
await withTemporaryGlobalScope(async scope => {
|
||||
for (let command of message.input) {
|
||||
if (command.kind == "module") {
|
||||
let blobUrl = URL.createObjectURL(new Blob([command.source], { type: "text/javascript" }));
|
||||
let module = await import(blobUrl);
|
||||
for (let exportedKey in module) {
|
||||
scope.set(exportedKey, module[exportedKey]);
|
||||
}
|
||||
} else if (command.kind == "output") {
|
||||
++outputIndex;
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
|
@ -29,7 +53,8 @@ addEventListener("message", event => {
|
|||
output: {
|
||||
kind: "error",
|
||||
message: [error.toString()],
|
||||
}
|
||||
},
|
||||
outputIndex,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue