File size: 5,134 Bytes
7031091 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | // Cbot in a Web Worker: loads cbot.wasm (a wasm32-wasi reactor built from
// the C sources) and provides the few WASI calls it makes. No Emscripten.
//
// Messages in: {type: "init", variant: 0|1|2, context: N, maxMemory: N[, seed, fixedTime]}
// {type: "turn", text} {type: "reset"}
// Messages out: {type: "ready", version} {type: "turn", result} {type: "error", message}
"use strict";
const ENOSYS = 52, EBADF = 8, ESUCCESS = 0;
let inst = null, mem = null, engine = 0, loadedFile = "";
const enc = new TextEncoder(), dec = new TextDecoder();
const view = () => new DataView(mem.buffer);
const bytes = () => new Uint8Array(mem.buffer);
function cstr(ptr) {
const b = bytes();
let end = ptr;
while (b[end]) end++;
return dec.decode(b.subarray(ptr, end));
}
function withCString(s, fn) {
const data = enc.encode(s);
const p = inst.exports.cbw_alloc(data.length + 1);
bytes().set(data, p);
bytes()[p + data.length] = 0;
try { return fn(p); } finally { inst.exports.cbw_free(p); }
}
// UTC offset in minutes of IANA zone `tz` at `secs`; "" = the browser's zone.
function tzOffsetMinutes(tzPtr, secs) {
const tz = cstr(tzPtr);
const d = new Date(secs * 1000);
if (!tz) return -d.getTimezoneOffset();
try {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: tz, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit",
hour: "2-digit", minute: "2-digit", second: "2-digit",
}).formatToParts(d);
const f = Object.fromEntries(parts.map((p) => [p.type, Number(p.value)]));
const asUTC = Date.UTC(f.year, f.month - 1, f.day, f.hour, f.minute, f.second);
return Math.round((asUTC - Math.floor(secs) * 1000) / 60000);
} catch {
return -2147483648; // INT32_MIN: unknown zone
}
}
// The WASI calls a libc reactor actually makes; anything else gets ENOSYS.
function wasiImports() {
const w = {
fd_write(fd, iovs, n, nwritten) {
let out = "", total = 0;
for (let i = 0; i < n; i++) {
const p = view().getUint32(iovs + i * 8, true), len = view().getUint32(iovs + i * 8 + 4, true);
out += dec.decode(bytes().subarray(p, p + len));
total += len;
}
if (fd === 1 || fd === 2) console[fd === 1 ? "log" : "warn"]("[cbot]", out);
view().setUint32(nwritten, total, true);
return ESUCCESS;
},
clock_time_get(id, precision, out) {
const ns = BigInt(Math.round((id === 0 ? Date.now() : performance.now()) * 1e6));
view().setBigUint64(out, ns, true); // id 0 realtime, otherwise monotonic
return ESUCCESS;
},
clock_res_get(id, out) { view().setBigUint64(out, 1000n, true); return ESUCCESS; },
random_get(p, len) { crypto.getRandomValues(bytes().subarray(p, p + len)); return ESUCCESS; },
environ_sizes_get(count, size) { view().setUint32(count, 0, true); view().setUint32(size, 0, true); return ESUCCESS; },
environ_get() { return ESUCCESS; },
args_sizes_get(count, size) { view().setUint32(count, 0, true); view().setUint32(size, 0, true); return ESUCCESS; },
args_get() { return ESUCCESS; },
fd_prestat_get() { return EBADF; },
fd_fdstat_get(fd, out) { view().setUint8(out, fd <= 2 ? 2 : 0); return fd <= 2 ? ESUCCESS : EBADF; },
fd_close() { return ESUCCESS; },
proc_exit(code) { throw new Error("cbot exited with code " + code); },
};
return w;
}
async function load(file) {
const resp = await fetch(file);
if (!resp.ok) throw new Error(`cannot fetch ${file}: ${resp.status}`);
const module = await WebAssembly.compileStreaming(resp);
const wasi = wasiImports();
const imports = { wasi_snapshot_preview1: {}, cbot: { tz_offset_minutes: tzOffsetMinutes } };
for (const imp of WebAssembly.Module.imports(module)) {
if (imp.kind !== "function" || imp.module !== "wasi_snapshot_preview1") continue;
imports.wasi_snapshot_preview1[imp.name] = wasi[imp.name] || (() => ENOSYS);
}
inst = await WebAssembly.instantiate(module, imports);
mem = inst.exports.memory;
inst.exports._initialize();
loadedFile = file;
}
self.onmessage = async (ev) => {
const m = ev.data;
try {
if (m.type === "init") {
// cbot-flash ships a smaller knowledge base, so it's its own module.
const file = m.variant === 2 ? "cbot-flash.wasm" : "cbot.wasm";
if (file !== loadedFile) { engine = 0; await load(file); }
if (engine) inst.exports.cbw_destroy(engine);
const seed = crypto.getRandomValues(new Uint32Array(1))[0] || 1;
engine = inst.exports.cbw_new(m.variant, m.context | 0, m.maxMemory | 0, m.seed || seed, m.fixedTime || 0);
if (!engine) throw new Error(cstr(inst.exports.cbw_error()));
self.postMessage({ type: "ready", version: cstr(inst.exports.cbw_version()) });
} else if (m.type === "turn") {
const json = withCString(m.text, (p) => cstr(inst.exports.cbw_turn(engine, p)));
self.postMessage({ type: "turn", result: JSON.parse(json) });
} else if (m.type === "reset") {
inst.exports.cbw_reset(engine);
}
} catch (e) {
self.postMessage({ type: "error", message: String(e && e.message || e) });
}
};
|