# JavaScript Runtime APIs - WebAssembly

**Note:** Azion Functions Runtime provides the WebAssembly module interface as defined by MDN. You can review the documentation directly on the MDN website [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly).

## WebAssembly – Static methods

### WebAssembly.compile()

The WebAssembly.compile() function compiles WebAssembly binary code into a `WebAssembly.Module` object. This function is useful if it's necessary to compile a module before it can be instantiated (otherwise, the `WebAssembly.instantiate()` function should be used).

**Syntax**

`WebAssembly.compile(bufferSource)`

**Parameters**

`bufferSource`

A typed array or ArrayBuffer containing the binary code of the .wasm module you want to compile.

**Example**

```
fetch('http://url/simple.wasm').then(response =>
  response.arrayBuffer()
).then(bytes =>
  WebAssembly.compile(bytes)
).then(mod =>
  //your code here
);
```

### WebAssembly.compileStreaming()

The `WebAssembly.compileStreaming()` function compiles a `WebAssembly.Module` from a streamed underlying source. This function can be necessary to compile a module before it can be instantiated (otherwise, the `WebAssembly.instantiateStreaming()` function should be used).

**Syntax**

`WebAssembly.compileStreaming (source)`

**Parameters**

`source`

A Response object, representing the underlying source of a `.wasm module` you want to stream and compile.

**Example**

```js
  var importObject = { imports: { imported_func: arg => console.log(arg) } };

  WebAssembly.compileStreaming(fetch('http://url/simple.wasm'))
  .then(module => WebAssembly.instantiate(module, importObject))
  .then(instance => instance.exports.exported_func());
```

### WebAssembly.instantiate()

The `WebAssembly.instantiate()` function allows you to compile and instantiate WebAssembly code. This function has two overloads:

- The primary overload takes the WebAssembly binary code, in the form of a typed array or ArrayBuffer, and performs both compilation and instantiation in one step;
- The secondary overload takes an already-compiled WebAssembly.Module and returns a Promise that resolves to an Instance of that Module.

**Syntax** (primary overload)

`WebAssembly.instantiate(bufferSource, importObject);`

**Parameters**

`bufferSource`

A typed array or `ArrayBuffer` containing the binary code of the .wasm module you want to compile.

`importObject` (optional)

An object containing the values to be imported into the newly-created Instance, such as functions or WebAssembly.Memory objects. There must be one matching property for each declared import of the compiled module or else a WebAssembly.LinkError is thrown.

**Example**

```js
var importObject = {
  imports: {
    imported_func: function(arg) {
      console.log(arg);
    }
  }
};

fetch('http://url/simple.wasm').then(response =>
  response.arrayBuffer()
).then(bytes =>
  WebAssembly.instantiate(bytes, importObject)
).then(result =>
  result.instance.exports.exported_func()
);
```

**Syntax** (secondary overload)

`WebAssembly.instantiate(module, importObject);`

**Parameters**

`module`

The WebAssembly.Module object to be instantiated.

`importObject` (optional)

An object containing the values to be imported into the newly-created Instance, such as functions or WebAssembly.Memory objects. There must be one matching property for each declared import of module or else a `WebAssembly.LinkError` is thrown.

**Example**

```
WebAssembly.compileStreaming(fetch('http://url/simple.wasm'))
.then(module => WebAssembly.instantiate(module))
.then(instance => instance.exports.exported_func());
```

### WebAssembly.instantiateStreaming()

The `WebAssembly.instantiateStreaming()` function compiles and instantiates a WebAssembly module directly from a streamed underlying source. This is the most efficient, optimized way to load wasm code.

**Syntax**

`WebAssembly.instantiateStreaming(source, importObject)`

**Parameters**

`source`

A Response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream, compile, and instantiate.

`importObject` (Optional)

An object containing the values to be imported into the newly-created Instance, such as functions or WebAssembly.Memory objects. There must be one matching property for each declared import of the compiled module or else a WebAssembly.LinkError is thrown.

**Example**

```
var importObject = { imports: { imported_func: arg => console.log(arg) } };

WebAssembly.instantiateStreaming(fetch('http://url/simple.wasm'), importObject)
.then(obj => obj.instance.exports.exported_func());
```

#### 1.5. WebAssembly.validate()

The `WebAssembly.validate()` function validates a given typed array of WebAssembly binary code, returning whether the bytes form a valid wasm module (true) or not (false).

**Syntax**

`WebAssembly.validate(bufferSource)`

**Parameters**

`bufferSource`

A typed array or ArrayBuffer containing WebAssembly binary code to be validated.

**Example**

```
fetch('http://url/simple.wasm').then(response =>
  response.arrayBuffer()
).then(function(bytes) {
  const valid = WebAssembly.validate(bytes);
  console.log("The given bytes are "
    + (valid ? "" : "not ") + "a valid wasm module");
});
```



## WebAssembly - Constructor properties

### WebAssembly.CompileError() constructor

The `WebAssembly.CompileError()` constructor creates a new WebAssembly CompileError object, which indicates an error during WebAssembly decoding or validation.

**Syntax**

`new WebAssembly.CompileError()`

`new WebAssembly.CompileError(message)`

`new WebAssembly.CompileError(message, fileName)`

`new WebAssembly.CompileError(message, fileName, lineNumber)`

**Parameters**

`message` (optional)

Human-readable description of the error.

`fileName` (optional)

The name of the file containing the code that caused the exception.

`lineNumber` (optional)

The line number of the code that caused the exception.

**Example**

```js
  try {
    throw new WebAssembly.CompileError('Hello', 'someFile', 10);
  } catch (e) {
    console.log(e instanceof CompileError); // true
    console.log(e.message);                 // "Hello"
    console.log(e.name);                    // "CompileError"
    console.log(e.fileName);                // "someFile"
    console.log(e.lineNumber);              // 10
    console.log(e.columnNumber);            // 0
    console.log(e.stack);                   // returns the location where the code was run
  }
```

### WebAssembly.Instance() constructor**

The `WebAssembly.Instance()` constructor creates a new Instance object which is a stateful, executable instance of a WebAssembly.Module.

**Syntax**

`new WebAssembly.Instance(module, importObject)`

**Parameters**

`module`

The WebAssembly.Module object to be instantiated.

`importObject` (optional)

An object containing the values to be imported into the newly-created Instance, such as functions or WebAssembly.Memory objects. 

**Example**

```js
  const importObject = {
    imports: {
      imported_func: function(arg) {
        console.log(arg);
      }
    }
  };
  
  fetch('http://url/simple.wasm').then(response =>
    response.arrayBuffer()
  ).then(bytes => {
    let mod = new WebAssembly.Module(bytes);
    let instance = new WebAssembly.Instance(mod, importObject);
    instance.exports.exported_func();
  })
```

### WebAssembly.LinkError() constructor

The `WebAssembly.LinkError()` constructor creates a new WebAssembly LinkError object, which indicates an error during module instantiation (besides traps from the start function).
**Syntax**

`new WebAssembly.LinkError()`

`new WebAssembly.LinkError(message)`

`new WebAssembly.LinkError(message, fileName)`

`new WebAssembly.LinkError(message, fileName, lineNumber)`

**Parameters**

`message` (optional)

Human-readable description of the error.

`fileName` (optional)

The name of the file containing the code that caused the exception.

`lineNumber` (optional)

The line number of the code that caused the exception.

**Examples**

```js
  try {
    throw new WebAssembly.LinkError('Hello', 'someFile', 10);
  } catch (e) {
    console.log(e instanceof LinkError); // true
    console.log(e.message);                 // "Hello"
    console.log(e.name);                    // "LinkError"
    console.log(e.fileName);                // "someFile"
    console.log(e.lineNumber);              // 10
    console.log(e.columnNumber);            // 0
    console.log(e.stack);                   // returns the location where the code was run
  }
```

### WebAssembly.Memory() constructor

The `WebAssembly.Memory()` constructor creates a new Memory object whose buffer property is a resizable ArrayBuffer or SharedArrayBuffer that holds the raw bytes of memory accessed by a WebAssembly Instance.

A memory created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly.

**Syntax**

`new WebAssembly.Memory(memoryDescriptor)`

**Parameters**

`memoryDescriptor`

An object that can contain the following members:

- `initial`

  The initial size of the WebAssembly Memory, in units of WebAssembly pages.

- `maximum Optional`

  The maximum size the WebAssembly Memory is allowed to grow to, in units of WebAssembly pages. When present, the maximum parameter acts as a hint to the engine to reserve memory up front. However, the engine may ignore or clamp this reservation request. Unshared WebAssembly memories don't need to set a maximum, but shared memories do.

- `shared Optional`

  A boolean value that defines whether the memory is a shared memory or not. If set to true, it is a shared memory. The default is false.

**Examples**

**Creating a new Memory instance**

```
var memory = new WebAssembly.Memory({initial:10, maximum:100});
```

**Creating a shared memory**

```
let memory = new WebAssembly.Memory({initial:10, maximum:100, shared:true});
```

### WebAssembly.Module() constructor

A `WebAssembly.Module()` constructor creates a new Module object containing stateless WebAssembly code that has already been compiled by the browser and can be efficiently shared with Workers, and instantiated multiple times.

The WebAssembly.Module() constructor function can be called to synchronously compile given WebAssembly binary code. However, the primary way to get a Module is through an asynchronous compilation function like WebAssembly.compile().

**Syntax**

```js
  new WebAssembly.Module(bufferSource)
```

**Parameters**

`bufferSource`

A typed array or ArrayBuffer containing the binary code of the .wasm module you want to compile.

**Example**

```js
  const importObject = {
    imports: {
      imported_func: function(arg) {
        console.log(arg);
      }
    }
  };
  
  function createWasmModule(bytes) {
    return new WebAssembly.Module(bytes);
  }
  
  fetch('http://url/simple.wasm').then(response =>
    response.arrayBuffer()
  ).then(bytes => {
    let mod = createWasmModule(bytes);
    WebAssembly.instantiate(mod, importObject)
    .then(result =>
       result.exports.exported_func()
    );
  })
```

### WebAssembly.RuntimeError() constructor

The `WebAssembly.RuntimeError()` constructor creates a new WebAssembly RuntimeError object — the type that is thrown whenever WebAssembly specifies a trap.

**Syntax**
```js
  new WebAssembly.RuntimeError()
```

```js
  new WebAssembly.RuntimeError(message)
```

```js
  new WebAssembly.RuntimeError(message, fileName)
```

```js
  new WebAssembly.RuntimeError(message, fileName, lineNumber)
```

**Parameters**

`message` (Optional)

Human-readable description of the error.

`fileName` (Optional)

The name of the file containing the code that caused the exception.

`lineNumber` (Optional)

The line number of the code that caused the exception.

**Example**

```js
  try {
    throw new WebAssembly.RuntimeError('Hello', 'someFile', 10);
  } catch (e) {
    console.log(e instanceof WebAssembly.RuntimeError); // true
    console.log(e.message);                             // "Hello"
    console.log(e.name);                                // "RuntimeError"
    console.log(e.fileName);                            // "someFile"
    console.log(e.lineNumber);                          // 10
    console.log(e.columnNumber);                        // 0
    console.log(e.stack);                               // returns the location where the code was run
  }
```

### WebAssembly.Table() constructor

The `WebAssembly.Table()` constructor creates a new Table object of the given size and element type.

**Syntax**

```js
  new WebAssembly.Table(tableDescriptor)  
```

**Parameters**

`tableDescriptor`

An object that can contain the following members:

- element

  A string representing the type of value to be stored in the table. This can have a value of "anyfunc" (functions) or "externref" (host references).

- `initial`

  The initial number of elements of the WebAssembly Table.

- `maximum Optional`

  The maximum number of elements the WebAssembly Table is allowed to grow to.

**Example**

```js
  var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"});
  var len = tbl.length;  // "2"
  var v1 = tbl.get(0);  // "null"
  var v2 = tbl.get(1);  // "null"
  
  // Creating an import object that contains the table
  var importObj = {
    js: {
      tbl:tbl
    }
  };
```

### WebAssembly.Tag() constructor

The `WebAssembly.Tag()` constructor creates a new WebAssembly.Tag object.

**Syntax**

```js
  new WebAssembly.Tag(type)
```
**Parameters**

```js
  type
``` 
An object that can contain the following members:

- `parameters`

  An array of data types ("i32", "i64", "f32", "f64", "v128", "externref", "anyfunc").

**Exceptions**

`TypeError`

The type.parameters argument is not supplied, does not contain at least one value, or contains an unsupported tag descriptor.

**Example**

This creates a tag with two values:

```js
  const tag = new WebAssembly.Tag({ parameters: ["i32", "i64"] });
```

### WebAssembly.Exception constructor

The `WebAssembly.Exception()` constructor is used to create a new WebAssembly.Exception.

The constructor accepts a Tag argument and a payload array of data fields. The data types of each of the payload elements must match the corresponding data type specified in the Tag.

The constructor may also take an options object. The options.traceStack property can be set true (by default it is false) to indicate that WebAssembly code that throws the exception may populate the exception's stack property with a stack track.

**Syntax**

```js
new Exception(tag, payload, options)
```

**Parameters**

`tag`

An WebAssembly.Tag defining the data types expected for each of the values in the payload.

`payload`

An array of one or more data fields comprising the payload of the exception. The elements must match the data types of the corresponding elements in the tag. If the number of data fields in the payload and their types don't match, a TypeError exception is thrown.

`options` (optional)

An object with the following optional fields:

`traceStack` (optional)

true if the Exception may have a stack trace attached to its stack property, otherwise false. This is false by default (if options or options.traceStack are not provided).

**Exceptions**

`TypeError`

The payload and tag sequences do not have the same number of elements and/or the elements are not of matching types.

**Example**

```js
  // Create tag and use it to create an exception
  const tag = new WebAssembly.Tag({ parameters: ["i32", "f32"] });
  const exception = new WebAssembly.Exception(tag, [42, 42.3]);
```

For more information on [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface) visit MDN Web Docs.