notif-wasm-host.mjs raw

   1  // notif-wasm-host.mjs — Worker bootstrap for notif.wasm.
   2  import {
   3    makeCoreHelpers, makeWasi, makeEnv, makeCommonBridge, computeBuildHash,
   4  } from './bridge-common.mjs';
   5  
   6  let mem, xp;
   7  const _sabTable = new Map(), _sabSeqRef = { value: 0 };
   8  const _spawnedWorkerChans = new Map();
   9  const _wasmUrlRef = { value: null }, _buildHashRef = { value: null };
  10  const h = makeCoreHelpers(() => mem, () => xp);
  11  const { readStr, writeStr, writeI32, readBytes, writeBytes, cb0, cbs, cbb, cbdata } = h;
  12  let _workerMsgCBID = 0, _consumerMsgCBID = 0;
  13  const _pending = [];
  14  
  15  function jsonEsc(s) {
  16    return String(s).replace(/\\/g,'\\\\').replace(/"/g,'\"').replace(/\n/g,'\\n').replace(/\r/g,'\\r').replace(/\t/g,'\\t');
  17  }
  18  
  19  const bridge = {
  20    notif_worker_on_message(cbID) { _workerMsgCBID = cbID; },
  21    notif_worker_post(ptr, len) { self.postMessage(readStr(ptr, len)); },
  22    notif_worker_set_timeout(ms, cbID) { return setTimeout(() => cb0(cbID), ms); },
  23    notif_worker_clear_timeout(h) { clearTimeout(h); },
  24    notif_worker_now_seconds() { return BigInt(Math.floor(Date.now() / 1000)); },
  25    notif_send(ptr, len) { self.postMessage({ type: 'notif-send', msg: readStr(ptr, len) }); },
  26    notif_on_message(cbID) { _consumerMsgCBID = cbID; },
  27    ...makeCommonBridge(h, _sabTable, _sabSeqRef, _wasmUrlRef, _buildHashRef, _spawnedWorkerChans),
  28  };
  29  
  30  const wasi = makeWasi(() => mem);
  31  const env = makeEnv(() => mem);
  32  
  33  self.addEventListener('unhandledrejection', function(ev) {
  34    self.postMessage('["__WASM_FATAL","unhandledrejection: ' + jsonEsc(String(ev.reason)) + '"]');
  35  });
  36  
  37  self.onmessage = async function(e) {
  38    const d = e.data;
  39    if (d && d.type === 'init' && d.mode === 'root') {
  40      try {
  41        const wasmBytes = await fetch(d.wasmUrl, { cache: 'no-store' }).then(r => r.arrayBuffer());
  42        _wasmUrlRef.value = d.wasmUrl;
  43        _buildHashRef.value = await computeBuildHash(wasmBytes);
  44        const { instance } = await WebAssembly.instantiate(wasmBytes, { bridge, env, wasi_snapshot_preview1: wasi });
  45        mem = instance.exports.memory; xp = instance.exports;
  46        xp._start();
  47        while (_pending.length > 0) {
  48          const m = _pending.shift();
  49          if (typeof m === 'string' && _workerMsgCBID) cbs(_workerMsgCBID, m);
  50          else if (m && m.type === '__notif_msg' && _consumerMsgCBID) cbs(_consumerMsgCBID, m.msg || '');
  51        }
  52        self.postMessage('["__WASM_BOOTED"]');
  53      } catch (err) {
  54        self.postMessage('["__WASM_FATAL","boot: ' + jsonEsc(String(err)) + '"]');
  55      }
  56      return;
  57    }
  58    if (_workerMsgCBID || _consumerMsgCBID) {
  59      if (typeof d === 'string' && _workerMsgCBID) cbs(_workerMsgCBID, d);
  60      if (d && d.type === '__notif_msg' && _consumerMsgCBID) cbs(_consumerMsgCBID, d.msg || '');
  61    } else {
  62      _pending.push(d);
  63    }
  64  };
  65