wasmedge-quickjs icon indicating copy to clipboard operation
wasmedge-quickjs copied to clipboard

Nested Buffer dependency fails

Open mraszyk opened this issue 3 years ago • 1 comments

I want to run wasmedge-quickjs on the following JS code:

var std = require('std');
import {Buffer} from 'buffer';
var WebAssembly = require('webassemblyjs');

let f = std.open('./add.wasm', 'r');
f.seek(0, std.SEEK_END);
let sz = f.tell();
f.seek(0, std.SEEK_SET);
let wasmBuffer = new ArrayBuffer(sz);
f.read(wasmBuffer, 0, sz);

WebAssembly.instantiate(wasmBuffer).then(wasmModule => {
  const { add } = wasmModule.instance.exports;
  const sum = add(5, 6);
  console.log(sum); 
});

Now the issue is that the dependency WebAssembly uses Buffer internally and this nested dependency is not handled properly. To make the code work, I had to perform a manual adjustment of the dist/index.js file produced by ncc as follows:

sed -i "s/ Buffer/ external_buffer_namespaceObject.Buffer/g" dist/index.js
sed -i "1s;^;const external_buffer_namespaceObject = require(\"buffer\")\;;" dist/index.js

I wonder if there is a canonical approach to deal with this issue. You can fully reproduce my issue by running:

git clone https://github.com/mraszyk/wasmedge-quickjs.git
cd wasmedge-quickjs
git checkout mraszyk/import-buffer
bash -x ./import-buffer.sh

mraszyk avatar Jun 25 '22 11:06 mraszyk

I found it because in node.js Buffer is default export in global. Manually set Buffer to global can fix this.

var std = require('std');
import {Buffer} from 'buffer';
var WebAssembly = require('webassemblyjs');

globalThis.Buffer = Buffer;

let f = std.open('./add.wasm', 'r');
f.seek(0, std.SEEK_END);
let sz = f.tell();
f.seek(0, std.SEEK_SET);
let wasmBuffer = new ArrayBuffer(sz);
f.read(wasmBuffer, 0, sz);

WebAssembly.instantiate(wasmBuffer).then(wasmModule => {
  const { add } = wasmModule.instance.exports;
  const sum = add(5, 6);
  console.log(sum);
});

Puellaquae avatar Jul 07 '22 07:07 Puellaquae