# WebAssembly

The `WebAssembly` object holds the JavaScript interface to WebAssembly in Azion Runtime. A function uses it to validate, compile, and instantiate a module from its binary code, and to create the memory, tables, and tags that a module uses. Azion Runtime provides the interface that MDN Web Docs defines, except that the two streaming methods do not accept a `Response`. For more information, refer to [WebAssembly](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly) and [WebAssembly JavaScript interface](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface) on MDN Web Docs.

The examples declare the binary code of a module inline, so each one runs as written. A function that downloads a `.wasm` file with [`fetch()`](/en/documentation/devtools/runtime/api-reference/fetch/) passes the result of `response.arrayBuffer()` in its place.

---

## Methods

The `WebAssembly` object has these static methods.

### WebAssembly.compile()

`WebAssembly.compile()` compiles WebAssembly binary code into a `WebAssembly.Module` object. Use it when you compile a module before you instantiate it; otherwise, use `WebAssembly.instantiate()`.

```javascript
WebAssembly.compile(bufferSource)
```

| Parameter      | Type                         | Required | Description                                   |
| -------------- | ---------------------------- | -------- | --------------------------------------------- |
| `bufferSource` | Typed array or `ArrayBuffer` | Yes      | Binary code of the `.wasm` module to compile. |

This example compiles a module that exports one function, `add`, and lists the exports of the module:

```javascript
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 3, 2, 1, 0, 7, 7, 1, 3, 97, 100, 100, 0, 0, 10, 9, 1, 7, 0, 32, 0, 32, 1, 106, 11]);

WebAssembly.compile(bytes).then((mod) => {
  console.log(WebAssembly.Module.exports(mod)); // [{ name: "add", kind: "function" }]
});
```

Bytes that do not form a valid module make the promise reject with a `WebAssembly.CompileError`. For example, a module with an unsupported version rejects with `WebAssembly.compile(): expected version 01 00 00 00, found 09 00 00 00 @+4`.

### WebAssembly.compileStreaming()

`WebAssembly.compileStreaming()` compiles a `WebAssembly.Module` from a streamed underlying source. Use it when you compile a module before you instantiate it; otherwise, use `WebAssembly.instantiateStreaming()`.

```javascript
WebAssembly.compileStreaming(source)
```

| Parameter | Type       | Required | Description                                                    |
| --------- | ---------- | -------- | -------------------------------------------------------------- |
| `source`  | `Response` | Yes      | Underlying source of the `.wasm` module to stream and compile. |

Azion Runtime does not accept a `Response` as `source`: the promise rejects with `TypeError: WebAssembly.compile(): Argument 0 must be a buffer source`. To compile a module from a response, read the body with `response.arrayBuffer()` and pass the result to `WebAssembly.compile()`.

### WebAssembly.instantiate()

`WebAssembly.instantiate()` compiles and instantiates WebAssembly code. It has two overloads:

- The primary overload takes the binary code, as a typed array or an `ArrayBuffer`, and compiles and instantiates it in one step. The promise fulfills with an object that holds `module` and `instance`.
- The secondary overload takes a `WebAssembly.Module` that is already compiled. The promise fulfills with an `Instance` of that module.

```javascript
WebAssembly.instantiate(bufferSource, importObject)
WebAssembly.instantiate(module, importObject)
```

The primary overload takes these parameters:

| Parameter      | Type                         | Required | Description                                                                                                                                                                                                                          |
| -------------- | ---------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `bufferSource` | Typed array or `ArrayBuffer` | Yes      | Binary code of the `.wasm` module to compile and instantiate.                                                                                                                                                                        |
| `importObject` | Object                       | No       | Values to import into the new `Instance`, such as functions or `WebAssembly.Memory` objects. It needs one matching property for each import that the module declares; otherwise, the promise rejects with a `WebAssembly.LinkError`. |

The secondary overload takes these parameters:

| Parameter      | Type                 | Required | Description                                                                                                                                                                                                             |
| -------------- | -------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `module`       | `WebAssembly.Module` | Yes      | Module to instantiate.                                                                                                                                                                                                  |
| `importObject` | Object               | No       | Values to import into the new `Instance`, such as functions or `WebAssembly.Memory` objects. It needs one matching property for each import of `module`; otherwise, the promise rejects with a `WebAssembly.LinkError`. |

An import object that lacks the function a module imports makes the promise reject with `WebAssembly.instantiate(): Import #0 "imports" "imported_func": function import requires a callable`.

This example uses the primary overload. The module imports `imports.imported_func` and exports `exported_func`, which calls the imported function with the value `42`:

```javascript
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 8, 2, 96, 1, 127, 0, 96, 0, 0, 2, 25, 1, 7, 105, 109, 112, 111, 114, 116, 115, 13, 105, 109, 112, 111, 114, 116, 101, 100, 95, 102, 117, 110, 99, 0, 0, 3, 2, 1, 1, 7, 17, 1, 13, 101, 120, 112, 111, 114, 116, 101, 100, 95, 102, 117, 110, 99, 0, 1, 10, 8, 1, 6, 0, 65, 42, 16, 0, 11]);

const importObject = {
  imports: {
    imported_func(arg) {
      console.log(arg); // 42
    },
  },
};

WebAssembly.instantiate(bytes, importObject).then((result) => {
  result.instance.exports.exported_func();
});
```

This example uses the secondary overload. It compiles the `add` module first, then instantiates it:

```javascript
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 3, 2, 1, 0, 7, 7, 1, 3, 97, 100, 100, 0, 0, 10, 9, 1, 7, 0, 32, 0, 32, 1, 106, 11]);

WebAssembly.compile(bytes)
  .then((mod) => WebAssembly.instantiate(mod))
  .then((instance) => {
    console.log(instance.exports.add(40, 2)); // 42
  });
```

### WebAssembly.instantiateStreaming()

`WebAssembly.instantiateStreaming()` compiles and instantiates a WebAssembly module directly from a streamed underlying source.

```javascript
WebAssembly.instantiateStreaming(source, importObject)
```

| Parameter      | Type                                            | Required | Description                                                                                                                                                                                                                          |
| -------------- | ----------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `source`       | `Response`, or a promise that fulfills with one | Yes      | Underlying source of the `.wasm` module to stream, compile, and instantiate.                                                                                                                                                         |
| `importObject` | Object                                          | No       | Values to import into the new `Instance`, such as functions or `WebAssembly.Memory` objects. It needs one matching property for each import that the module declares; otherwise, the promise rejects with a `WebAssembly.LinkError`. |

Azion Runtime does not accept a `Response` as `source`: the promise rejects with `TypeError: WebAssembly.compile(): Argument 0 must be a buffer source`. To instantiate a module from a response, read the body with `response.arrayBuffer()` and pass the result to `WebAssembly.instantiate()`.

### WebAssembly.validate()

`WebAssembly.validate()` checks whether a typed array of WebAssembly binary code forms a valid module. It returns `true` when the bytes form a valid module and `false` when they do not.

```javascript
WebAssembly.validate(bufferSource)
```

| Parameter      | Type                         | Required | Description              |
| -------------- | ---------------------------- | -------- | ------------------------ |
| `bufferSource` | Typed array or `ArrayBuffer` | Yes      | Binary code to validate. |

This example validates the `add` module and three bytes that are not a module:

```javascript
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 3, 2, 1, 0, 7, 7, 1, 3, 97, 100, 100, 0, 0, 10, 9, 1, 7, 0, 32, 0, 32, 1, 106, 11]);

console.log(WebAssembly.validate(bytes)); // true
console.log(WebAssembly.validate(new Uint8Array([1, 2, 3]))); // false
```

---

## Constructors

The `WebAssembly` object holds these constructors.

### WebAssembly.CompileError()

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

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

| Parameter    | Type   | Required | Description                                                     |
| ------------ | ------ | -------- | --------------------------------------------------------------- |
| `message`    | String | No       | Human-readable description of the error.                        |
| `fileName`   | String | No       | Name of the file that holds the code that caused the exception. |
| `lineNumber` | Number | No       | Line number of the code that caused the exception.              |

This example throws a `CompileError` and reads it in a `catch` block:

```javascript
try {
  throw new WebAssembly.CompileError('Hello', 'someFile', 10);
} catch (e) {
  console.log(e instanceof WebAssembly.CompileError); // true
  console.log(e.message);                             // "Hello"
  console.log(e.name);                                // "CompileError"
  console.log(e.stack);                               // the location where the code ran
}
```

`CompileError` is a property of the `WebAssembly` object, not a global: test it with `e instanceof WebAssembly.CompileError`.

### WebAssembly.Instance()

`WebAssembly.Instance()` creates an `Instance` object, a stateful, executable instance of a `WebAssembly.Module`.

```javascript
new WebAssembly.Instance(module, importObject)
```

| Parameter      | Type                 | Required | Description                                                                                  |
| -------------- | -------------------- | -------- | -------------------------------------------------------------------------------------------- |
| `module`       | `WebAssembly.Module` | Yes      | Module to instantiate.                                                                       |
| `importObject` | Object               | No       | Values to import into the new `Instance`, such as functions or `WebAssembly.Memory` objects. |

This example compiles the `add` module and instantiates it synchronously:

```javascript
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 3, 2, 1, 0, 7, 7, 1, 3, 97, 100, 100, 0, 0, 10, 9, 1, 7, 0, 32, 0, 32, 1, 106, 11]);

const mod = new WebAssembly.Module(bytes);
const instance = new WebAssembly.Instance(mod, {});
console.log(instance.exports.add(1, 1)); // 2
```

### WebAssembly.LinkError()

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

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

| Parameter    | Type   | Required | Description                                                     |
| ------------ | ------ | -------- | --------------------------------------------------------------- |
| `message`    | String | No       | Human-readable description of the error.                        |
| `fileName`   | String | No       | Name of the file that holds the code that caused the exception. |
| `lineNumber` | Number | No       | Line number of the code that caused the exception.              |

This example throws a `LinkError` and reads it in a `catch` block:

```javascript
try {
  throw new WebAssembly.LinkError('Hello', 'someFile', 10);
} catch (e) {
  console.log(e instanceof WebAssembly.LinkError); // true
  console.log(e.message);                          // "Hello"
  console.log(e.name);                             // "LinkError"
  console.log(e.stack);                            // the location where the code ran
}
```

`LinkError` is a property of the `WebAssembly` object, not a global: test it with `e instanceof WebAssembly.LinkError`.

### WebAssembly.Memory()

`WebAssembly.Memory()` creates a `Memory` object. Its `buffer` property is a resizable `ArrayBuffer` or `SharedArrayBuffer` that holds the raw bytes of memory that a WebAssembly `Instance` accesses. A memory created by JavaScript or by WebAssembly code is accessible and mutable from both JavaScript and WebAssembly.

```javascript
new WebAssembly.Memory(memoryDescriptor)
```

| Parameter                  | Type    | Required | Default | Description                                                                                                                                                                                                                                   |
| -------------------------- | ------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `memoryDescriptor.initial` | Number  | Yes      | —       | Initial size of the memory, in WebAssembly pages.                                                                                                                                                                                             |
| `memoryDescriptor.maximum` | Number  | No       | —       | Maximum size the memory can grow to, in WebAssembly pages. When present, it hints to the engine to reserve memory up front; the engine can ignore or clamp the reservation. An unshared memory does not need a maximum; a shared memory does. |
| `memoryDescriptor.shared`  | Boolean | No       | `false` | Whether the memory is a shared memory. Set it to `true` for a shared memory.                                                                                                                                                                  |

This example creates a memory of 10 pages that can grow to 100 pages:

```javascript
var memory = new WebAssembly.Memory({initial:10, maximum:100});
console.log(memory.buffer.byteLength); // 655360
```

With `initial` set to `10`, the buffer holds 655,360 bytes, so one WebAssembly page holds 65,536 bytes.

This example creates a shared memory. Its `buffer` is a `SharedArrayBuffer`:

```javascript
let memory = new WebAssembly.Memory({initial:10, maximum:100, shared:true});
console.log(memory.buffer.constructor.name); // "SharedArrayBuffer"
```

### WebAssembly.Module()

`WebAssembly.Module()` creates a `Module` object, which holds stateless WebAssembly code that is already compiled and can be instantiated multiple times. The constructor compiles the binary code synchronously. The primary way to get a `Module` is an asynchronous compilation function such as `WebAssembly.compile()`.

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

| Parameter      | Type                         | Required | Description                                   |
| -------------- | ---------------------------- | -------- | --------------------------------------------- |
| `bufferSource` | Typed array or `ArrayBuffer` | Yes      | Binary code of the `.wasm` module to compile. |

This example compiles the `add` module synchronously, then instantiates it with `WebAssembly.instantiate()`:

```javascript
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 3, 2, 1, 0, 7, 7, 1, 3, 97, 100, 100, 0, 0, 10, 9, 1, 7, 0, 32, 0, 32, 1, 106, 11]);

const mod = new WebAssembly.Module(bytes);
WebAssembly.instantiate(mod).then((instance) => {
  console.log(instance.exports.add(40, 2)); // 42
});
```

### WebAssembly.RuntimeError()

`WebAssembly.RuntimeError()` creates a `RuntimeError` object, the type that WebAssembly throws whenever it specifies a trap.

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

| Parameter    | Type   | Required | Description                                                                                          |
| ------------ | ------ | -------- | ---------------------------------------------------------------------------------------------------- |
| `message`    | String | No       | Human-readable description of the error.                                                             |
| `fileName`   | String | No       | Name of the file that holds the code that caused the exception. The error object does not expose it. |
| `lineNumber` | Number | No       | Line number of the code that caused the exception. The error object does not expose it.              |

This example throws a `RuntimeError` and reads it in a `catch` block. The constructor accepts `fileName` and `lineNumber`, but `e.fileName`, `e.lineNumber`, and `e.columnNumber` read as `undefined`:

```javascript
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);                            // undefined
  console.log(e.lineNumber);                          // undefined
  console.log(e.columnNumber);                        // undefined
  console.log(e.stack);                               // "RuntimeError: Hello", then the call stack
}
```

### WebAssembly.Table()

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

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

| Parameter                 | Type   | Required | Description                                                                                     |
| ------------------------- | ------ | -------- | ----------------------------------------------------------------------------------------------- |
| `tableDescriptor.element` | String | Yes      | Type of value the table stores: `"anyfunc"` for functions or `"externref"` for host references. |
| `tableDescriptor.initial` | Number | Yes      | Initial number of elements of the table.                                                        |
| `tableDescriptor.maximum` | Number | No       | Maximum number of elements the table can grow to.                                               |

This example creates a table of two functions, reads its length and elements, and adds the table to an import object:

```javascript
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()

`WebAssembly.Tag()` creates a `WebAssembly.Tag` object.

```javascript
new WebAssembly.Tag(type)
```

| Parameter         | Type             | Required | Description                                                                                                            |
| ----------------- | ---------------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| `type.parameters` | Array of strings | Yes      | Data types of the values the tag carries: `"i32"`, `"i64"`, `"f32"`, `"f64"`, `"v128"`, `"externref"`, or `"anyfunc"`. |

The constructor throws a `TypeError` when `type.parameters` is not supplied, holds no value, or holds an unsupported tag descriptor.

This example creates a tag with two values:

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

### WebAssembly.Exception()

`WebAssembly.Exception()` creates a `WebAssembly.Exception` object. The constructor takes a `Tag` and a payload array of data fields. The data type of each payload element must match the corresponding data type of the `Tag`.

```javascript
new WebAssembly.Exception(tag, payload, options)
```

| Parameter            | Type              | Required | Default | Description                                                                                                                                         |
| -------------------- | ----------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tag`                | `WebAssembly.Tag` | Yes      | —       | Tag that defines the data type of each value in the payload.                                                                                        |
| `payload`            | Array             | Yes      | —       | One or more data fields that make up the payload of the exception. The elements must match the data types of the corresponding elements of the tag. |
| `options.traceStack` | Boolean           | No       | `false` | `true` when WebAssembly code that throws the exception can attach a stack trace to the `stack` property of the exception.                           |

The constructor throws a `TypeError` when the payload and the tag do not have the same number of elements, or when the elements are not of matching types.

This example creates a tag and uses it to create an exception, then reads the exception back:

```javascript
// 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]);
console.log(exception.is(tag)); // true
console.log(exception.getArg(tag, 0)); // 42
console.log(exception.getArg(tag, 1)); // 42.29999923706055
```

The second value reads as `42.29999923706055` because the tag stores it as an `f32`, a 32-bit float.

---

## Related resources

- [fetch](/en/documentation/devtools/runtime/api-reference/fetch.md): How a function downloads a `.wasm` file before it compiles the module.
- [Response](/en/documentation/devtools/runtime/api-reference/response.md): The object that `fetch()` resolves to, which carries the bytes of the module in its body.
- [Web standards](/en/documentation/devtools/runtime/api-reference/web-standards.md): The JavaScript and Web standards that Azion Runtime implements.
- [Web APIs](/en/documentation/devtools/runtime/api-reference/javascript.md): The other Web APIs that Azion Runtime supports.
