Skip to content

Commit

Permalink
Simplify test and example init code
Browse files Browse the repository at this point in the history
  • Loading branch information
kateinoigakukun committed Mar 16, 2022
1 parent 37c33b9 commit c16868b
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 44 deletions.
33 changes: 3 additions & 30 deletions packages/npm-packages/ruby-wasm-wasi/example/index.web.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,13 @@
import { WASI } from "./node_modules/@wasmer/wasi";
import { WasmFs } from "@wasmer/wasmfs";
import { RubyVM } from "ruby-wasm-wasi";
import { DefaultRubyVM } from "ruby-wasm-wasi/dist/default/browser.esm";

const main = async () => {
// Setup WASI emulation
const wasmFs = new WasmFs();
const originalWriteSync = wasmFs.fs.writeSync.bind(wasmFs.fs);
wasmFs.fs.writeSync = (fd, buffer, offset, length, position) => {
const text = new TextDecoder("utf-8").decode(buffer);
const handlers = {
1: (line) => console.log(line),
2: (line) => console.warn(line),
};
if (handlers[fd]) handlers[fd](text);
return originalWriteSync(fd, buffer, offset, length, position);
};
const wasi = new WASI({
bindings: {
...WASI.defaultBindings,
fs: wasmFs.fs,
},
});
// Fetch and instntiate WebAssembly binary
const response = await fetch("./node_modules/ruby-wasm-wasi/dist/ruby.wasm");
const buffer = await response.arrayBuffer();
const vm = new RubyVM();
const imports = {
wasi_snapshot_preview1: wasi.wasiImport,
};
vm.addToImports(imports);

const { instance } = await WebAssembly.instantiate(buffer, imports);
await vm.setInstance(instance);
// Start WASI application
wasi.setMemory(instance.exports.memory);
vm.initialize();
const module = await WebAssembly.compile(buffer);
const vm = await DefaultRubyVM(module);

vm.printVersion();

Expand Down
16 changes: 2 additions & 14 deletions packages/npm-packages/ruby-wasm-wasi/test/init.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,12 @@
import { WASI } from "wasi";
import fs from "fs/promises";
import path from "path";
import { RubyVM } from "../dist/index.umd.js";
import { DefaultRubyVM } from "../dist/default/node.cjs";

const rubyModule = (async () => {
const binary = await fs.readFile(path.join(__dirname, "./../dist/ruby.wasm"));
return await WebAssembly.compile(binary.buffer);
})();

export const initRubyVM = async () => {
const wasi = new WASI();
const vm = new RubyVM();
const imports = {
wasi_snapshot_preview1: wasi.wasiImport,
};
vm.addToImports(imports);

const instance = await WebAssembly.instantiate(await rubyModule, imports);
await vm.setInstance(instance);
wasi.initialize(instance);
vm.initialize();
return vm;
return DefaultRubyVM(await rubyModule);
};

0 comments on commit c16868b

Please sign in to comment.