sw-host.mjs raw

   1  // sw-host.mjs — the service worker's half of a Moxie wasm bundle.
   2  //
   3  // A service worker is a third execution context: no document, no Worker, its
   4  // own global with the lifecycle events. What it shares with the Worker host is
   5  // everything that matters - the WASI/env import object, the channel and spawn
   6  // bridge, the string and callback marshalling, the IndexedDB imports - so this
   7  // host is that plus the sw_* entries and nothing else. It is copied to
   8  // $sw/wasm-host-sw.mjs by `moxie build -target wasm`, beside $runtime/, which
   9  // is why it imports through ../$runtime/ (the same specifier resolves from
  10  // inside $runtime/ too, where the runtime copy also lands).
  11  //
  12  // There is no DOM relay in this context, so a DOM call from a service worker
  13  // fails by name: a worker has no document to reach, and pretending otherwise
  14  // would be the silent nothing this framework exists to remove.
  15  import * as sw from '../$runtime/sw.mjs';
  16  import {
  17    buildHostImports, buildWorkerBridge, buildIdbBridge, setHostModule,
  18    readStr, splitNull, setOutStr,
  19    cb0, cbs, cbb, cbi, cbii, cbiii,
  20  } from '../$runtime/host.mjs';
  21  import { makeDomProxy } from '../$runtime/relay.mjs';
  22  
  23  let memory;
  24  const wasmUrl = new URL('./sw.wasm', import.meta.url).href;
  25  
  26  const bridge = {
  27    // --- lifecycle ---
  28    sw_on_install(cbID) { sw.OnInstall((id) => cbi(cbID, id)); },
  29    sw_on_activate(cbID) { sw.OnActivate((id) => cbi(cbID, id)); },
  30    sw_on_fetch(cbID) { sw.OnFetch((id) => cbi(cbID, id)); },
  31    sw_on_message(cbID) { sw.OnMessage((id) => cbi(cbID, id)); },
  32    // The module's handler receives a "done" function and the page side waits on
  33    // the promise it resolves: a service worker is killed as soon as its event
  34    // handler settles, so extension is the handler's own decision.
  35    sw_wait_until(event, cbID) { sw.WaitUntil(event, (done) => { cb0(cbID); done(); }); },
  36  
  37    // --- fetch events ---
  38    sw_respond_with(event, resp) { sw.RespondWith(event, resp); },
  39    sw_respond_with_network(event) { sw.RespondWithNetwork(event); },
  40    sw_respond_with_cache_first(event) { sw.RespondWithCacheFirst(event); },
  41    sw_respond_with_network_first(event) { sw.RespondWithNetworkFirst(event); },
  42    sw_respond_with_proxy_cache(event) { sw.RespondWithProxyCache(event); },
  43    sw_prune_proxy_cache(maxAgeMs, cbID) { sw.PruneProxyCache(maxAgeMs, () => cb0(cbID)); },
  44    sw_get_request_url(event, outPtr, outLen) { setOutStr(outPtr, outLen, sw.GetRequestURL(event)); },
  45    sw_get_request_path(event, outPtr, outLen) { setOutStr(outPtr, outLen, sw.GetRequestPath(event)); },
  46    sw_get_message_data(event, outPtr, outLen) { setOutStr(outPtr, outLen, sw.GetMessageData(event)); },
  47    sw_get_message_client_id(event, outPtr, outLen) {
  48      setOutStr(outPtr, outLen, sw.GetMessageClientID(event));
  49    },
  50  
  51    // --- responses and clients ---
  52    sw_response_ok(resp) { return sw.ResponseOK(resp) ? 1 : 0; },
  53    sw_skip_waiting() { sw.SkipWaiting(); },
  54    sw_claim_clients(cbID) { sw.ClaimClients(() => cb0(cbID)); },
  55    sw_match_clients(cbID) { sw.MatchClients((client) => cbi(cbID, client)); },
  56    sw_post_message(client, ptr, len, _c) { sw.PostMessage(client, readStr(ptr, len)); },
  57    sw_post_message_json(client, ptr, len, _c) { sw.PostMessageJSON(client, readStr(ptr, len)); },
  58    sw_get_client_by_id(ptr, len, _c, cbID) {
  59      sw.GetClientByID(readStr(ptr, len), (client, found) => cbii(cbID, client, found ? 1 : 0));
  60    },
  61    sw_navigate(client, ptr, len, _c) { sw.Navigate(client, readStr(ptr, len)); },
  62    sw_origin(outPtr, outLen) { setOutStr(outPtr, outLen, sw.Origin()); },
  63    sw_log(ptr, len, _c) { sw.Log(readStr(ptr, len)); },
  64  
  65    // --- cache ---
  66    sw_cache_open(ptr, len, _c, cbID) { sw.CacheOpen(readStr(ptr, len), (cache) => cbi(cbID, cache)); },
  67    // The url lists arrive NUL-separated with an explicit count, the same shape
  68    // the page-side splitNull helper reads.
  69    sw_cache_add_all(cache, urlsPtr, urlsLen, _uc, count, cbID) {
  70      sw.CacheAddAll(cache, splitNull(urlsPtr, urlsLen, count), () => cb0(cbID));
  71    },
  72    sw_cache_from_manifests(cache, filesPtr, filesLen, _fc, count, cbID) {
  73      sw.CacheFromManifests(cache, splitNull(filesPtr, filesLen, count), () => cb0(cbID));
  74    },
  75    sw_cache_put(cache, urlPtr, urlLen, _uc, resp, cbID) {
  76      sw.CachePut(cache, readStr(urlPtr, urlLen), resp, () => cb0(cbID));
  77    },
  78    sw_cache_match(ptr, len, _c, cbID) { sw.CacheMatch(readStr(ptr, len), (resp) => cbi(cbID, resp)); },
  79    sw_cache_delete(ptr, len, _c, cbID) { sw.CacheDelete(readStr(ptr, len), () => cb0(cbID)); },
  80  
  81    // --- network ---
  82    sw_fetch(ptr, len, _c, cbID) {
  83      sw.Fetch(readStr(ptr, len), (resp, ok) => cbii(cbID, resp, ok ? 1 : 0));
  84    },
  85    sw_fetch_all(urlsPtr, urlsLen, _uc, count, eachID, doneID) {
  86      sw.FetchAll(splitNull(urlsPtr, urlsLen, count),
  87        (idx, resp, ok) => cbiii(eachID, idx, resp, ok ? 1 : 0),
  88        () => cb0(doneID));
  89    },
  90    sw_sse_connect(ptr, len, _c, cbID) {
  91      return sw.SSEConnect(readStr(ptr, len), (data) => cbs(cbID, data));
  92    },
  93    sw_sse_close(id) { sw.SSEClose(id); },
  94  
  95    // --- timers and time ---
  96    sw_set_timeout(ms, cbID) { return sw.SetTimeout(ms, () => cb0(cbID)); },
  97    sw_clear_timeout(timer) { sw.ClearTimeout(timer); },
  98    sw_now_seconds() { return sw.NowSeconds(); },
  99    sw_now_millis() { return sw.NowMillis(); },
 100  
 101    // --- storage: the same IndexedDB imports a page module gets ---
 102    ...buildIdbBridge(),
 103  };
 104  
 105  fetch(wasmUrl)
 106    .then((r) => r.arrayBuffer())
 107    .then((bytes) => WebAssembly.instantiate(bytes, {
 108      ...buildHostImports(() => memory),
 109      bridge: { ...buildWorkerBridge(new Map(), makeDomProxy(null)), ...bridge },
 110    }))
 111    .then(({ instance }) => {
 112      memory = instance.exports.memory;
 113      setHostModule(instance);
 114      // A service worker is the one host with no page: it can instantiate a
 115      // module, but it cannot start a domain Worker and has no hub port to give
 116      // one. A module built with spawn support therefore fails HERE, at boot,
 117      // rather than at the first spawn() with a null route.
 118      if (typeof instance.exports.__spawn_entry === 'function') {
 119        throw new Error('this module was built with spawn support, but a service worker has no page-supervised hub; wasm spawn needs jsruntime/loader.mjs or startBundle');
 120      }
 121      instance.exports._start();
 122      // The module has had its chance to register handlers; anything still queued
 123      // is an event this worker does not serve, and leaving it pending would keep
 124      // the worker in "activating" for good.
 125      sw.ModuleReady();
 126      // This worker is the bundle's worker: there is never a reason to keep the
 127      // previous generation in charge of a page that just loaded the new one, and
 128      // an install that waits for every old client to go away is an upgrade that
 129      // may not happen until the next visit.
 130      self.skipWaiting();
 131    })
 132    .catch((e) => {
 133      // A service worker that fails to boot must say so where a developer can
 134      // see it: there is no page to report to, and silence here would look like
 135      // a worker that simply has nothing to do.
 136      console.error('[sw] wasm boot failed: ' + String((e && e.stack) || e));
 137    });
 138