store-bridge.mjs raw

   1  // The store worker's application bridge.
   2  //
   3  // The host is the framework's; this is the app's half - the five imports the
   4  // store protocol declares and nothing else. The page's end of the port arrives
   5  // from startBundle, so a page message becomes a module callback and the module's
   6  // replies go back over the same port. Everything else the module imports (idb_*)
   7  // is answered by the stdlib host it runs on.
   8  //
   9  // Ordering note: the port is live from the moment this factory is called, which
  10  // is BEFORE the module registers its handler. Messages that arrive in that
  11  // window are queued and delivered on registration rather than dropped, because
  12  // a page that posts on startup is not doing anything wrong.
  13  import { readStr, cbs, cb0 } from './$runtime/host.mjs';
  14  
  15  export default function storeBridge({ port }) {
  16    if (!port) throw new Error('the store bridge needs the page port from startBundle');
  17    let onMessage = 0;
  18    const pending = [];
  19    port.onmessage = (e) => {
  20      const msg = String(e.data);
  21      if (onMessage) cbs(onMessage, msg);
  22      else pending.push(msg);
  23    };
  24    return {
  25      store_worker_on_message(cbID) {
  26        onMessage = cbID;
  27        while (pending.length > 0) cbs(onMessage, pending.shift());
  28      },
  29      store_worker_post(ptr, len) { port.postMessage(readStr(ptr, len)); },
  30      store_worker_set_timeout(ms, cbID) { return setTimeout(() => cb0(cbID), ms); },
  31      store_worker_clear_timeout(handle) { clearTimeout(handle); },
  32      store_worker_now_seconds() { return BigInt(Math.floor(Date.now() / 1000)); },
  33    };
  34  }
  35