# bare-wasm

<mark style="{ backgroundColor: '#8484ff', padding: '2px 8px', borderRadius: '4px', fontSize: '0.85em', fontWeight: 500 }">
  experimental
</mark>

[`bare-wasm`](https://github.com/holepunchto/bare-wasm) — WebAssembly JavaScript API for Bare. Each export is the same-named member of the `WebAssembly` global. Where the global is unavailable, 0.1.0 throws a `ReferenceError` when it loads. From 0.1.1, the exports still load, but the constructors, the static methods of `Module` and `validate()` throw an error with the code `WEBASSEMBLY_UNAVAILABLE`, and `compile()` and `instantiate()` reject with it. Before Bare 1.37.0 the global was unavailable on iOS, where V8 runs without a JIT, as the 0.1.1 README still says. From Bare 1.37.0, V8 runs WebAssembly there in its DrumBrake interpreter, more slowly than on platforms that compile it, except on the x64 simulator, whose V8 build still leaves WebAssembly out. Bare 1.36.0 bundles 0.1.0, and Bare 1.36.1 through 1.37.1 bundle 0.1.1.

```sh
npm i bare-wasm
```

## Usage [#usage]

```js
const { Module, Instance } = require('bare-wasm')

const module = new Module(bytes)
const instance = new Instance(module, imports)
```

## API [#api]

### wasm [#wasm]

#### `wasm.BufferSource` [#wasmbuffersource]

```ts
type BufferSource = ArrayBuffer | ArrayBufferView
```

The bytes of a WebAssembly module in its binary format.

#### `wasm.compile(bytes: BufferSource): Promise<Module>` [#wasmcompilebytes-buffersource-promisemodule]

Asynchronously compile a module.

**Parameters**

| Parameter | Type           | Default | Description                      |
| --------- | -------------- | ------- | -------------------------------- |
| `bytes`   | `BufferSource` | —       | The binary format of the module. |

#### `wasm.Exports` [#wasmexports]

```ts
type Exports = Record<string, ExportValue>
```

The exports of an instance, keyed by name.

#### `wasm.ExportValue` [#wasmexportvalue]

```ts
type ExportValue = Function | Global | Memory | Table | Tag
```

A value exported by an instance.

#### `wasm.ImportExportKind` [#wasmimportexportkind]

```ts
type ImportExportKind = 'function' | 'table' | 'memory' | 'global' | 'tag'
```

The kind of an import or export of a module.

#### `wasm.Imports` [#wasmimports]

```ts
type Imports = Record<string, ModuleImports>
```

The imports of a module, keyed by import module name.

#### `wasm.ImportValue` [#wasmimportvalue]

```ts
type ImportValue = ExportValue | number | bigint
```

A value that may be provided to satisfy an import.

#### `wasm.instantiate(bytes: BufferSource, imports?: Imports): Promise<InstantiatedSource>` [#wasminstantiatebytes-buffersource-imports-imports-promiseinstantiatedsource]

Asynchronously compile and instantiate a module.

Overloads:

```ts
wasm.instantiate(bytes: BufferSource, imports?: Imports): Promise<InstantiatedSource>
wasm.instantiate(module: Module, imports?: Imports): Promise<Instance>
```

**Parameters**

| Parameter  | Type           | Default | Description                                           |
| ---------- | -------------- | ------- | ----------------------------------------------------- |
| `bytes`    | `BufferSource` | —       | The binary format of the module.                      |
| `imports?` | `Imports`      | —       | The values to satisfy the imports of the module with. |

#### `wasm.ModuleImports` [#wasmmoduleimports]

```ts
type ModuleImports = Record<string, ImportValue>
```

The imports of a single import module, keyed by name.

#### `wasm.TableKind` [#wasmtablekind]

```ts
type TableKind = 'externref' | 'anyfunc'
```

The type of the elements of a table.

#### `wasm.validate(bytes: BufferSource): boolean` [#wasmvalidatebytes-buffersource-boolean]

Check whether `bytes` is a valid module.

**Parameters**

| Parameter | Type           | Default | Description |
| --------- | -------------- | ------- | ----------- |
| `bytes`   | `BufferSource` | —       | —           |

#### `wasm.ValueType` [#wasmvaluetype]

```ts
type ValueType = 'i32' | 'i64' | 'f32' | 'f64' | 'v128' | 'externref' | 'anyfunc'
```

The type of a WebAssembly value.

### Module [#module]

#### `new Module(bytes: BufferSource)` [#new-modulebytes-buffersource]

Synchronously compile a module.

**Parameters**

| Parameter | Type           | Default | Description                      |
| --------- | -------------- | ------- | -------------------------------- |
| `bytes`   | `BufferSource` | —       | The binary format of the module. |

**Throws**

* `CompileError` — thrown if `bytes` is not a valid module.

#### `Module.customSections(module: Module, sectionName: string): ArrayBuffer[]` [#modulecustomsectionsmodule-module-sectionname-string-arraybuffer]

Get the contents of the custom sections of `module` named `sectionName`.

**Parameters**

| Parameter     | Type     | Default | Description |
| ------------- | -------- | ------- | ----------- |
| `module`      | `Module` | —       | —           |
| `sectionName` | `string` | —       | —           |

#### `Module.exports(module: Module): ModuleExportDescriptor[]` [#moduleexportsmodule-module-moduleexportdescriptor]

Get descriptors of the exports of `module`.

**Parameters**

| Parameter | Type     | Default | Description |
| --------- | -------- | ------- | ----------- |
| `module`  | `Module` | —       | —           |

#### `Module.imports(module: Module): ModuleImportDescriptor[]` [#moduleimportsmodule-module-moduleimportdescriptor]

Get descriptors of the imports of `module`.

**Parameters**

| Parameter | Type     | Default | Description |
| --------- | -------- | ------- | ----------- |
| `module`  | `Module` | —       | —           |

### Instance [#instance]

#### `new Instance(module: Module, imports?: Imports)` [#new-instancemodule-module-imports-imports]

Synchronously instantiate a module.

**Parameters**

| Parameter  | Type      | Default | Description                                           |
| ---------- | --------- | ------- | ----------------------------------------------------- |
| `module`   | `Module`  | —       | The module to instantiate.                            |
| `imports?` | `Imports` | —       | The values to satisfy the imports of the module with. |

**Throws**

* `LinkError` — thrown if the imports of the module cannot be satisfied.
* `RuntimeError` — thrown if the start function of the module traps.

#### `exports: Exports` [#exports-exports]

The exports of the instance.

### Memory [#memory]

#### `new Memory(descriptor: MemoryDescriptor)` [#new-memorydescriptor-memorydescriptor]

Create a memory of `descriptor.initial` pages.

**Parameters**

| Parameter    | Type                                    | Default | Description |
| ------------ | --------------------------------------- | ------- | ----------- |
| `descriptor` | [`MemoryDescriptor`](#memorydescriptor) | —       | —           |

#### `buffer: ArrayBuffer | SharedArrayBuffer` [#buffer-arraybuffer--sharedarraybuffer]

The buffer backing the memory, which is detached and replaced whenever it grows.

#### `grow(delta: number): number` [#growdelta-number-number]

Grow the memory.

**Parameters**

| Parameter | Type     | Default | Description                                          |
| --------- | -------- | ------- | ---------------------------------------------------- |
| `delta`   | `number` | —       | The number of pages of 64 KiB to grow the memory by. |

**Returns** `number` — The previous size of the memory in pages.

**Throws**

* `RangeError` — thrown if the memory cannot grow by `delta` pages.

### Table [#table]

#### `new Table(descriptor: TableDescriptor, value?: any)` [#new-tabledescriptor-tabledescriptor-value-any]

Create a table of `descriptor.initial` elements, each set to `value`.

**Parameters**

| Parameter    | Type                                  | Default | Description                                             |
| ------------ | ------------------------------------- | ------- | ------------------------------------------------------- |
| `descriptor` | [`TableDescriptor`](#tabledescriptor) | —       | The type and limits of the table.                       |
| `value?`     | `any`                                 | —       | The value to initialize the elements of the table with. |

#### `get(index: number): any` [#getindex-number-any]

Get the element at `index`.

**Parameters**

| Parameter | Type     | Default | Description |
| --------- | -------- | ------- | ----------- |
| `index`   | `number` | —       | —           |

#### `grow(delta: number, value?: any): number` [#growdelta-number-value-any-number]

Grow the table.

**Parameters**

| Parameter | Type     | Default | Description                                    |
| --------- | -------- | ------- | ---------------------------------------------- |
| `delta`   | `number` | —       | The number of elements to grow the table by.   |
| `value?`  | `any`    | —       | The value to initialize the new elements with. |

**Returns** `number` — The previous number of elements of the table.

**Throws**

* `RangeError` — thrown if the table cannot grow by `delta` elements.

#### `length: number` [#length-number]

The number of elements of the table.

#### `set(index: number, value?: any): void` [#setindex-number-value-any-void]

Set the element at `index` to `value`.

**Parameters**

| Parameter | Type     | Default | Description |
| --------- | -------- | ------- | ----------- |
| `index`   | `number` | —       | —           |
| `value?`  | `any`    | —       | —           |

### Global [#global]

#### `new Global(descriptor: GlobalDescriptor, value?: T)` [#new-globaldescriptor-globaldescriptor-value-t]

Create a global holding `value`.

**Parameters**

| Parameter    | Type                                    | Default | Description                            |
| ------------ | --------------------------------------- | ------- | -------------------------------------- |
| `descriptor` | [`GlobalDescriptor`](#globaldescriptor) | —       | The type and mutability of the global. |
| `value?`     | `T`                                     | —       | The initial value of the global.       |

#### `value: T` [#value-t]

The value of the global.

#### `valueOf(): T` [#valueof-t]

Get the value of the global.

### Tag [#tag]

#### `new Tag(type: TagType)` [#new-tagtype-tagtype]

Create an exception tag.

**Parameters**

| Parameter | Type                  | Default | Description |
| --------- | --------------------- | ------- | ----------- |
| `type`    | [`TagType`](#tagtype) | —       | —           |

### Exception [#exception]

#### `new Exception(tag: Tag, payload: any[], options?: ExceptionOptions)` [#new-exceptiontag-tag-payload-any-options-exceptionoptions]

Create an exception of `tag` carrying `payload`.

**Parameters**

| Parameter  | Type                                    | Default | Description                                                            |
| ---------- | --------------------------------------- | ------- | ---------------------------------------------------------------------- |
| `tag`      | `Tag`                                   | —       | The tag identifying the type of the exception.                         |
| `payload`  | `any[]`                                 | —       | The values carried by the exception, matching the parameters of `tag`. |
| `options?` | [`ExceptionOptions`](#exceptionoptions) | —       | Options for the exception.                                             |

#### `getArg(tag: Tag, index: number): any` [#getargtag-tag-index-number-any]

Get a value carried by the exception.

**Parameters**

| Parameter | Type     | Default | Description                            |
| --------- | -------- | ------- | -------------------------------------- |
| `tag`     | `Tag`    | —       | The tag the exception must have.       |
| `index`   | `number` | —       | The index of the value in the payload. |

**Throws**

* `TypeError` — thrown if the exception does not have `tag`.

#### `is(tag: Tag): boolean` [#istag-tag-boolean]

Check whether the exception has `tag`.

**Parameters**

| Parameter | Type  | Default | Description |
| --------- | ----- | ------- | ----------- |
| `tag`     | `Tag` | —       | —           |

#### `stack: string` [#stack-string]

The stack trace of the exception, if requested with `traceStack`.

### Types [#types]

#### `ModuleExportDescriptor` [#moduleexportdescriptor]

```ts
interface ModuleExportDescriptor {
  name: string
  kind: ImportExportKind
}
```

An export of a module, as listed by `Module.exports()`.

#### `ModuleImportDescriptor` [#moduleimportdescriptor]

```ts
interface ModuleImportDescriptor {
  module: string
  name: string
  kind: ImportExportKind
}
```

An import of a module, as listed by `Module.imports()`.

#### `MemoryDescriptor` [#memorydescriptor]

```ts
interface MemoryDescriptor {
  initial: number
  maximum?: number
  shared?: boolean
}
```

The size, in 64 KiB pages, and sharing of a memory.

#### `TableDescriptor` [#tabledescriptor]

```ts
interface TableDescriptor {
  element: TableKind
  initial: number
  maximum?: number
}
```

The element type and size of a table.

#### `GlobalDescriptor` [#globaldescriptor]

```ts
interface GlobalDescriptor {
  value: ValueType
  mutable?: boolean
}
```

The value type and mutability of a global.

#### `TagType` [#tagtype]

```ts
interface TagType {
  parameters: ValueType[]
}
```

The parameter types of an exception tag.

#### `ExceptionOptions` [#exceptionoptions]

```ts
interface ExceptionOptions {
  traceStack?: boolean
}
```

Options for an `Exception`.

#### `InstantiatedSource` [#instantiatedsource]

```ts
interface InstantiatedSource {
  module: Module
  instance: Instance
}
```

The result of instantiating the bytes of a module: the compiled `module` and its `instance`.

### Classes [#classes]

#### `CompileError` [#compileerror]

```ts
class CompileError {
}
```

An error thrown when a module fails to decode or validate.

#### `LinkError` [#linkerror]

```ts
class LinkError {
}
```

An error thrown when the imports of a module cannot be satisfied.

#### `RuntimeError` [#runtimeerror]

```ts
class RuntimeError {
}
```

An error thrown when WebAssembly code traps.

## See also [#see-also]

* [`bare-wasi`](/bare/reference/bare/modules/bare-wasi) — WASI preview 1 imports for an instance.
* [`bare-wasm-abi`](/bare/reference/bare/modules/bare-wasm-abi) — runs Bare addons compiled to WebAssembly on top of this API.
* [Bare modules](/bare/reference/bare/modules) — the full `bare-*` catalog.
* [Bare runtime API](/bare/reference/bare/runtime) — the runtime these modules extend.