| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- /*
- Runs the AGI playground engine (agi.wasm, the real Otto interpreter built
- from scripts/agidocgen/playground) off the page's main thread. The page
- stops a run by terminating this worker and starting a new one.
- page -> worker: {type:"run", req, files} | {type:"ws", text} | {type:"wsclose"}
- worker -> page: {type:"ready"} | {type:"fail", message}
- {type:"event", kind:"log"|"ws", payload}
- {type:"done", json, files}
- */
- "use strict";
- importScripts("wasm_exec.js");
- var ready = (function () {
- var go = new Go();
- var load = WebAssembly.instantiateStreaming
- ? WebAssembly.instantiateStreaming(fetch("agi.wasm"), go.importObject).catch(function () {
- // Served without the application/wasm type: fall back to bytes.
- return fetch("agi.wasm").then(function (r) { return r.arrayBuffer(); })
- .then(function (b) { return WebAssembly.instantiate(b, go.importObject); });
- })
- : fetch("agi.wasm").then(function (r) { return r.arrayBuffer(); })
- .then(function (b) { return WebAssembly.instantiate(b, go.importObject); });
- return load.then(function (result) {
- go.run(result.instance);
- return new Promise(function (resolve) {
- (function wait() {
- if (self.agiPlayground) resolve(self.agiPlayground);
- else setTimeout(wait, 5);
- })();
- });
- });
- })();
- ready.then(function (api) {
- postMessage({ type: "ready", defaults: JSON.parse(api.defaults()) });
- }, function (err) {
- postMessage({ type: "fail", message: String(err && err.message || err) });
- });
- onmessage = function (e) {
- var m = e.data;
- ready.then(function (api) {
- if (m.type === "run") {
- api.run(JSON.stringify(m.req), m.files || [], function (kind, payload) {
- postMessage({ type: "event", kind: kind, payload: payload });
- }).then(function (out) {
- var files = [];
- var transfer = [];
- for (var i = 0; i < out.files.length; i++) {
- var f = out.files[i];
- files.push({ path: f.path, dir: f.dir, mtime: f.mtime, data: f.data });
- if (f.data) transfer.push(f.data.buffer);
- }
- postMessage({ type: "done", json: out.json, files: files }, transfer);
- });
- } else if (m.type === "ws") {
- api.wsPush(m.text);
- } else if (m.type === "wsclose") {
- api.wsClose();
- }
- });
- };
|