Skip to content
Branch: master
Find file History
klaude Update npm dependencies
Update npm dependencies to avoid lodash and js-yaml versions with known
security vulnerabilities.
Latest commit a94c1d3 Jul 13, 2019
Permalink
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
assembly Add wasm-assembly-script and wasm-c examples Feb 14, 2019
README.md Rename Edge Engine to "serverless scripting" Jul 9, 2019
index.js Add wasm-assembly-script and wasm-c examples Feb 14, 2019
package.json Add wasm-assembly-script and wasm-c examples Feb 14, 2019
webpack.config.js Add wasm-assembly-script and wasm-c examples Feb 14, 2019
yarn.lock

README.md

AssemblyScript WebAssembly

This script demonstrates how to use AssemblyScript compiled to WebAssembly within a script.

Getting Started

Install Dependencies

Install yarn if it is not already installed and run it from the root of the wasm-assembly-script directory

yarn

AssemblyScript

In our AssemblyScript file, we export a function fib() that returns the nth Fibonacci number

export function fib(n: i32): i32 {
  let t: i32;
  let a: i32 = 0;
  let b: i32 = 1;
  for (let i: i32 = 0; i < n; i++) {
    t = a + b;
    a = b;
    b = t;
  }
  return b;
}

Build WASM

In order to access this function in our JavaScript script, we need to compile it to a .wasm file. To compile the AssemblyScript, run

yarn asbuild

which outputs an optimized.wasm file in the build/ directory.

Importing WASM

Our script imports the WASM file using arraybuffer-loader, setup in our webpack.config.js file. Our script looks like this:

import wasmBuffer from "./build/optimized.wasm";

const binary = new Uint8Array(wasmBuffer);
const memory = new WebAssembly.Memory({ initial: 256, maximum: 256 });
const wasmModule = new WebAssembly.Module(binary);
const instance = new WebAssembly.Instance(wasmModule, { env: { memory } })
  .exports;

addEventListener("fetch", event => {
  event.respondWith(handleRequest());
});

async function handleRequest() {
  return new Response(String(instance.fib(12)));
}

The WASM file is loaded into an ArrayBuffer, used to create a WebAssembly.Module, which is used to create a WebAssembly.Instance. With the instance, we are able to call our function defined in AssemblyScript.

Build js

To build our script, run

yarn build:js

The dist/main.js file will contain the runnable script.

Build project

To build the entire project (combines yarn asbuild and yarn build:js), run

yarn build
You can’t perform that action at this time.