Skip to content

@rollup/plugin-wasm does not support Web Workers (window is undefined) #333

@vedantroy

Description

@vedantroy
  • Rollup Plugin Name: @rollup/plugin-wasm
  • Rollup Plugin Version: 3.0.0
  • Rollup Version: 2.7.2
  • Operating System (or Browser): Chrome
  • Node Version: Not relevant, but here it is: 13.9.0

How Do We Reproduce?

I cannot provide a minimal reproduction (not because I don't know how to reproduce the error), but because the issue requires running the code outputted by rollup in a Service Worker, which I don't know how to do in repl.it. However, I will point out the line of code where the error is occurring.

Fake minimal repro so this isn't automatically closed (sorry!): https://repl.it/@VedantRoy/rollup-plugin-repro

Expected Behavior

No errors when running the code outputted by rollup in a Service Worker.

Actual Behavior

Get "window" is not defined error.

The error occurs because @rollup/plugin-wasm places this function in the code outputted by rollup. However, this function uses window.atob, which breaks when the code is run in a service worker because service workers don't have a window.

A possible fix is to replace window.atob with just atob, or maybe (window || self).atob.

function _loadWasmModule(sync, src, imports) {
  var buf = null;
  var isNode =
    typeof process !== "undefined" &&
    process.versions != null &&
    process.versions.node != null;
  if (isNode) {
    buf = Buffer.from(src, "base64");
  } else {
    // window is not defined in a service worker
    var raw = window.atob(src);
    var rawLength = raw.length;
    buf = new Uint8Array(new ArrayBuffer(rawLength));
    for (var i = 0; i < rawLength; i++) {
      buf[i] = raw.charCodeAt(i);
    }
  }

  if (imports && !sync) {
    return WebAssembly.instantiate(buf, imports);
  } else if (!imports && !sync) {
    return WebAssembly.compile(buf);
  } else {
    var mod = new WebAssembly.Module(buf);
    return imports ? new WebAssembly.Instance(mod, imports) : mod;
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions