Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@thi.ng/wasm-api

Package Overview
Dependencies
Maintainers
1
Versions
132
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@thi.ng/wasm-api - npm Package Compare versions

Comparing version 0.18.1 to 1.0.0

include/wasmapi_types.h

353

api.d.ts

@@ -1,7 +0,24 @@

import type { BigType, FloatType, Fn, Fn2, IDeref, ILength, IObjectOf, NumOrString } from "@thi.ng/api";
import type { Pow2 } from "@thi.ng/binary";
import type { Fn, IDeref, ILength } from "@thi.ng/api";
import type { WasmBridge } from "./bridge.js";
export declare const PKG_NAME = "@thi.ng/wasm-api";
export declare const EVENT_MEMORY_CHANGED = "memory-changed";
export declare type BigIntArray = bigint[] | BigInt64Array | BigUint64Array;
export declare type ReadonlyWasmString = IDeref<string> & ILength & {
readonly addr: number;
};
export interface WasmTypeBase {
/**
* Base address in linear WASM memory.
*/
readonly __base: number;
/**
* Obtain as byte buffer
*/
readonly __bytes: Uint8Array;
}
export interface WasmType<T> {
readonly align: number;
readonly size: number;
instance: Fn<number, T>;
}
export declare type WasmTypeConstructor<T> = Fn<IWasmMemoryAccess, WasmType<T>>;
/**

@@ -160,3 +177,4 @@ * Common interface for WASM/JS child APIs which will be used in combination

* `addr`. By default the string will be zero-terminated and only `maxBytes`
* will be written. Returns the number of bytes written.
* will be written. Returns the number of bytes written (excluding final
* sentinel, if any).
*

@@ -209,4 +227,5 @@ * @remarks

_printF64Array: (addr: number, len: number) => void;
_printStr0: (addr: number) => void;
printStrZ: (addr: number) => void;
_printStr: (addr: number, len: number) => void;
printHexdump: (addr: number, len: number) => void;
debug: () => void;

@@ -217,326 +236,2 @@ _panic: (addr: number, len: number) => void;

}
export interface WasmTypeBase {
/**
* Base address in linear WASM memory.
*/
readonly __base: number;
/**
* Obtain as byte buffer
*/
readonly __bytes: Uint8Array;
}
export interface WasmType<T> {
readonly align: number;
readonly size: number;
instance: Fn<number, T>;
}
export declare type WasmTypeConstructor<T> = Fn<IWasmMemoryAccess, WasmType<T>>;
export declare type WasmInt = "i8" | "i16" | "i32" | "i64";
export declare type WasmUint = "u8" | "u16" | "u32" | "u64";
export declare type WasmFloat = FloatType;
export declare type WasmPrim = WasmInt | WasmUint | WasmFloat;
export declare type WasmPrim32 = Exclude<WasmPrim, BigType>;
export declare type ReadonlyWasmString = IDeref<string> & ILength & {
readonly addr: number;
};
export declare type TypeColl = IObjectOf<TopLevelType>;
export interface TypeInfo {
/**
* Auto-computed size (in bytes)
*
* @internal
*/
__size?: number;
/**
* Auto-computed offset (in bytes) in parent struct.
*
* @internal
*/
__offset?: number;
/**
* Auto-computed alignment (in bytes) actually used.
*
* @internal
*/
__align?: Pow2;
}
export interface TopLevelType extends TypeInfo {
/**
* Type name
*/
name: string;
/**
* Optional (multi-line) docstring for this type
*/
doc?: string | string[];
/**
* Type / kind
*/
type: "enum" | "struct" | "union";
/**
* Optional object of user provided source codes to be injected into the
* generated type (after generated fields). Keys of this object are language
* IDs (`ts` for {@link TYPESCRIPT}, `zig` for {@link ZIG}).
*
* @remarks
* Currently only supported by the code gens mentioned, ignored otherwise.
*/
body?: IObjectOf<string | string[] | InjectedBody>;
}
export interface InjectedBody {
decl?: string | string[];
impl?: string | string[];
}
export interface Struct extends TopLevelType {
type: "struct";
/**
* Array of struct fields (might be re-ordered if {@link Struct.auto} is
* enabled).
*/
fields: Field[];
/**
* If true, struct fields will be re-ordered in descending order based on
* their {@link TypeInfo.__align} size. This might result in overall smaller
* structs due to minimizing implicit inter-field padding caused by
* alignment requirements. **If this option is enabled, then the struct MUST
* NOT contain any padding fields!**
*
* @defaultValue false
*/
auto?: boolean;
/**
* Optional qualifier for the kind of struct to be emitted (codegen specific
* interpretation, currently only used by {@link ZIG}).
*/
tag?: "extern" | "packed";
/**
* Optional user supplied {@link AlignStrategy}. By default uses
* {@link ALIGN_C} or {@link ALIGN_PACKED} (if using "packed" structs).
*/
align?: AlignStrategy;
}
export interface Union extends TopLevelType {
type: "union";
/**
* Array of union fields.
*/
fields: Field[];
/**
* Optional qualifier for the kind of struct to be emitted (codegen specific
* interpretation, currently only used by {@link ZIG}).
*/
tag?: "extern" | "packed";
/**
* Optional user supplied {@link AlignStrategy}. By default uses
* {@link ALIGN_C} or {@link ALIGN_PACKED} (if using "packed" union).
*/
align?: AlignStrategy;
}
export declare type FieldTag = "scalar" | "array" | "ptr" | "slice" | "vec";
export interface Field extends TypeInfo {
/**
* Field name (prefix: "__" is reserved)
*/
name: string;
/**
* Field docstring (can be multiline, will be formatted)
*/
doc?: string | string[];
/**
* Field type tag/qualifier (note: `slice` & `vec` are only supported by Zig
* & TS).
*
* @remarks
* - Array & vector fields are statically sized (using
* {@link Field.len})
* - Pointers are emitted as single-value pointers (where this distinction
* exist), i.e. even if they're pointing to multiple values, there's no
* explicit length encoded/available
* - Zig slices are essentially a pointer w/ associated length
* - Zig vectors will be processed using SIMD (if enabled in WASM target)
* and therefore will have stricter (larger) alignment requirements.
*
* @defaultValue "scalar"
*/
tag?: FieldTag;
/**
* Field base type. If not a {@link WasmPrim}, `string` or `opaque`, the
* value is interpreted as another type name in the {@link TypeColl}.
*
* @remarks
* Please see {@link CodeGenOpts.stringType} and consult package readme for
* further details re: string handling.
*
* TODO `opaque` currently unsupported.
*/
type: WasmPrim | "string" | "opaque" | string;
/**
* Const qualifier (default is true for `string`, false for all other
* types). Only used for pointers or slices.
*/
const?: boolean;
/**
* Currently only supported for {@link ZIG} arrays & slices, otherwise
* ignored!
*/
sentinel?: number;
/**
* Array or vector length (see {@link Field.tag})
*/
len?: number;
/**
* Currently only supported for {@link ZIG}, otherwise ignored!
*
* @remarks
* The object form allows for different default values per language (in
* theory). So if given as object, the keys refer to the lang ID and the
* values as the defaults for those languages.
*/
default?: NumOrString | IObjectOf<NumOrString>;
/**
* If defined and > 0, the field will be considered for padding purposes
* only and the value provided is the number of bytes used. All other config
* for this field will be ignored!
*/
pad?: number;
}
export interface Enum extends TopLevelType {
type: "enum";
/**
* No i64/u64 support, due to Typescript not supporting bigint enum values.
* For C compatibility only i32 or u32 is allowed.
*
* @defaultValue "i32"
*/
tag: Exclude<WasmPrim32, FloatType>;
/**
* List of possible values/IDs. Use {@link EnumValue}s for more detailed
* config.
*/
values: (string | EnumValue)[];
}
export interface EnumValue {
/**
* Enum value name/ID
*/
name: string;
/**
* Optional associated numeric value
*/
value?: number;
/**
* Optional docstring for this value
*/
doc?: string;
}
export interface AlignStrategy {
/**
* Returns implementation specific alignment for given struct field.
*/
align: Fn<Field, Pow2>;
/**
* Returns possibly rounded value for given base size & alignment.
*/
size: Fn2<number, Pow2, number>;
/**
* Returns possibly rounded value for given base offset & alignment.
*/
offset: Fn2<number, Pow2, number>;
}
export interface CodeGenOptsBase {
/**
* Optional string to be injected before generated type defs (but after
* codegen's own prelude, if any)
*/
pre?: string;
/**
* Optional string to be injected after generated type defs (but before
* codegen's own epilogue, if any)
*/
post?: string;
}
/**
* Global/shared code generator options.
*/
export interface CodeGenOpts extends CodeGenOptsBase {
/**
* WASM target specification.
*
* @defaultValue {@link WASM32}
*/
target: WasmTarget;
/**
* Identifier how strings are stored on WASM side, e.g. in Zig string
* literals are slices (8 bytes), in C just plain pointers (4 bytes).
*
* @defaultValue "slice"
*/
stringType: "slice" | "ptr";
/**
* If true (default), forces uppercase enum identifiers.
*
* @remarks
* This option is ignored in {@link ZIG} since it's idiomatic for that
* language to only use lowercase/camelCase enum IDs.
*
* @defaultValue true
*/
uppercaseEnums: boolean;
/**
* Unless set to false, the generated output will be prefixed with a header
* line comment of generator meta data
*/
header: boolean;
/**
* If true, codegens MAY generate various additional struct & struct field
* analysis functions (sizes, alignment, offsets etc.).
*
* @defaultValue false
*/
debug: boolean;
/**
* Target line width for word wrapping doc strings
*
* @defaultValue 80
*/
lineWidth: number;
}
export interface ICodeGen {
/**
* Optional prelude source, to be prepended before any generated type defs.
*/
pre?: Fn<CodeGenOpts, string>;
/**
* Optional source code to be appended after any generated type defs.
*/
post?: Fn<CodeGenOpts, string>;
/**
* Docstring codegen
*/
doc: (doc: string | string[], acc: string[], opts: CodeGenOpts, topLevel?: boolean) => void;
/**
* Codegen for enum types.
*/
enum: (type: Enum, types: TypeColl, acc: string[], opts: CodeGenOpts) => void;
/**
* Codegen for struct types.
*/
struct: (type: Struct, types: TypeColl, acc: string[], opts: CodeGenOpts) => void;
/**
* Codegen for union types.
*/
union: (type: Union, types: TypeColl, acc: string[], opts: CodeGenOpts) => void;
}
export interface WasmTarget {
usize: "u32" | "u64";
usizeBytes: number;
}
/**
* WASM32 target spec
*/
export declare const WASM32: WasmTarget;
/**
* WASM64 target spec
*/
export declare const WASM64: WasmTarget;
//# sourceMappingURL=api.d.ts.map

@@ -1,16 +0,1 @@

export const PKG_NAME = "@thi.ng/wasm-api";
export const EVENT_MEMORY_CHANGED = "memory-changed";
/**
* WASM32 target spec
*/
export const WASM32 = {
usize: "u32",
usizeBytes: 4,
};
/**
* WASM64 target spec
*/
export const WASM64 = {
usize: "u64",
usizeBytes: 8,
};

@@ -133,9 +133,2 @@ /// <reference types="node" />

getImports(): WebAssembly.Imports;
/**
* Attempts to grow the WASM memory by an additional `numPages` (64KB/page)
* and if successful updates all typed memory views to use the new
* underlying buffer.
*
* @param numPages
*/
growMemory(numPages: number): void;

@@ -184,27 +177,3 @@ allocate(numBytes: number, clear?: boolean): MemorySlice;

setF64Array(addr: number, buf: NumericArray): this;
/**
* Reads UTF-8 encoded string from given address and optional byte length.
* The default length is 0, which will be interpreted as a zero-terminated
* string. Returns string.
*
* @param addr
* @param len
*/
getString(addr: number, len?: number): string;
/**
* Encodes given string as UTF-8 and writes it to WASM memory starting at
* `addr`. By default the string will be zero-terminated and only `maxBytes`
* will be written. Returns the number of bytes written (excluding final
* sentinel, if any).
*
* @remarks
* An error will be thrown if the encoded string doesn't fully fit into the
* designated memory region (also note that there might need to be space for
* the additional sentinel/termination byte).
*
* @param str
* @param addr
* @param maxBytes
* @param terminate
*/
setString(str: string, addr: number, maxBytes: number, terminate?: boolean): number;

@@ -211,0 +180,0 @@ getElementById(addr: number, len?: number): HTMLElement;

@@ -6,3 +6,3 @@ import { __decorate } from "tslib";

import { defError } from "@thi.ng/errors/deferror";
import { U16, U32, U64BIG, U8 } from "@thi.ng/hex";
import { hexdumpLines, U16, U32, U64BIG, U8 } from "@thi.ng/hex";
import { ConsoleLogger } from "@thi.ng/logger/console";

@@ -51,2 +51,8 @@ import { EVENT_MEMORY_CHANGED, } from "./api.js";

printU64Hex: (x) => this.logger.debug(() => `0x${U64BIG(x)}`),
printHexdump: (addr, len) => {
this.ensureMemory();
for (let line of hexdumpLines(this.u8, addr, len)) {
this.logger.debug(line);
}
},
_printI8Array: logA(this.getI8Array.bind(this)),

@@ -62,3 +68,3 @@ _printU8Array: logA(this.getU8Array.bind(this)),

_printF64Array: logA(this.getF64Array.bind(this)),
_printStr0: (addr) => this.logger.debug(() => this.getString(addr, 0)),
printStrZ: (addr) => this.logger.debug(() => this.getString(addr, 0)),
_printStr: (addr, len) => this.logger.debug(() => this.getString(addr, len)),

@@ -198,9 +204,2 @@ debug: () => {

}
/**
* Attempts to grow the WASM memory by an additional `numPages` (64KB/page)
* and if successful updates all typed memory views to use the new
* underlying buffer.
*
* @param numPages
*/
growMemory(numPages) {

@@ -371,10 +370,2 @@ this.exports.memory.grow(numPages);

}
/**
* Reads UTF-8 encoded string from given address and optional byte length.
* The default length is 0, which will be interpreted as a zero-terminated
* string. Returns string.
*
* @param addr
* @param len
*/
getString(addr, len = 0) {

@@ -384,18 +375,2 @@ this.ensureMemory();

}
/**
* Encodes given string as UTF-8 and writes it to WASM memory starting at
* `addr`. By default the string will be zero-terminated and only `maxBytes`
* will be written. Returns the number of bytes written (excluding final
* sentinel, if any).
*
* @remarks
* An error will be thrown if the encoded string doesn't fully fit into the
* designated memory region (also note that there might need to be space for
* the additional sentinel/termination byte).
*
* @param str
* @param addr
* @param maxBytes
* @param terminate
*/
setString(str, addr, maxBytes, terminate = true) {

@@ -402,0 +377,0 @@ this.ensureMemory();

# Change Log
- **Last updated**: 2022-11-01T12:32:51Z
- **Last updated**: 2022-11-23T22:46:54Z
- **Generator**: [thi.ng/monopub](https://thi.ng/monopub)

@@ -12,2 +12,82 @@

# [1.0.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/wasm-api@1.0.0) (2022-11-23)
#### 🛑 Breaking changes
- remove codegen parts ([188f56b](https://github.com/thi-ng/umbrella/commit/188f56b))
- BREAKING CHANGE: all codegen parts migrated to new pkg: [@thi.ng/wasm-api-bindgen](https://github.com/thi-ng/umbrella/tree/main/packages/wasm-api-bindgen)
- remove all obsolete types, deps & files
- see [2c02dc674](https://github.com/thi-ng/umbrella/commit/2c02dc674) for start of new pkg
#### 🚀 Features
- add hexdump methods ([95c91ed](https://github.com/thi-ng/umbrella/commit/95c91ed))
- add printHexdump()/hexdump()
- add/update printHexdump() ([65efaf4](https://github.com/thi-ng/umbrella/commit/65efaf4))
- migrate printHexdump() to WASM core API
- add WasmStringSlice.setAlloc() ([b0f6f9d](https://github.com/thi-ng/umbrella/commit/b0f6f9d))
- add function pointer & i/usize codegen support ([2e67bc5](https://github.com/thi-ng/umbrella/commit/2e67bc5))
- add FuncPointer top-level type for codegen
- add isize/usize type aliases
- extend/refactor all codegens
- update WasmTarget & presets
- add opaque pointer support ([83d4b94](https://github.com/thi-ng/umbrella/commit/83d4b94))
- add optional pointer support ([92a28e7](https://github.com/thi-ng/umbrella/commit/92a28e7))
- update ZIG codegen
- add codegen IDs, conditionally skip code generation ([7146cae](https://github.com/thi-ng/umbrella/commit/7146cae))
- add ICodeGen.id & update codegens
- add TopLevelType.skip option to suppress generation for some langs
- update generateTypes()
- update & rename pkg (formerly wasm-api-timer) ([668f3dd](https://github.com/thi-ng/umbrella/commit/668f3dd))
- rename types form `TimerXXX` => `ScheduleXXX`
- add WASM auto-initializer hook
- update readmes
- update string handling & default string type ([86dee41](https://github.com/thi-ng/umbrella/commit/86dee41))
- update WasmStringSlice & WasmStringPtr
- update .setAlloc() impls
- update Zig code gen to use `[:0]const u8` as default string format
for easier interop and compatibility w/ `extern struct`s
- update generated types & string handling ([686f867](https://github.com/thi-ng/umbrella/commit/686f867))
- switch to extern structs for generated types
- switch to zero-terminated pointers for string values
- update/rename/simplify API methods, remove obsolete
- fix string attrib handling/alloc sizes
- add JSON schema for codegen typedefs ([1291c5c](https://github.com/thi-ng/umbrella/commit/1291c5c))
- switch to `extern struct/union` only, add slice polyfills ([ca65edc](https://github.com/thi-ng/umbrella/commit/ca65edc))
- [zig] emit only `extern` structs/unions
- [zig] remove (somewhat obsolete) support for packed structs/unions (KISS)
- remove `.tag` option from `Struct`/`Union`
- [zig/c] update codegens preludes
- add declarations of `XXSlice`/`XXMutSlice` type aliases
- rename `Field.tag`: `scalar` => `single`
- [ts] add `Field.skip` to suppress codegen for individual fields
- update JSON schema
- set default `string` impl to `ptr` (previously `slice`)
- add internal `clasifyField()` helper to simplify conditionals in codegens
- add/update various internal type predicates
- update CodeGenOpts.pre/post to support string arrays
- use new backend in all codegens ([33fc814](https://github.com/thi-ng/umbrella/commit/33fc814))
- update slice handling using auto-generated wrapper structs
- add support for multi-item pointers
- add support for enum pointers/arrays/slices
- add slice types to wasmapi.h & types.zig
- add more cases to FieldClass
- update classifyField()
- update all codegens to use new classifier based code templates
- add/update codegen tests/fixtures
- add Pointer64 (still unused) ([f1eef25](https://github.com/thi-ng/umbrella/commit/f1eef25))
#### 🩹 Bug fixes
- update CLI type checks ([1d4cc59](https://github.com/thi-ng/umbrella/commit/1d4cc59))
- re-add missing optional type `?` prefix [zig] ([3e3b4cd](https://github.com/thi-ng/umbrella/commit/3e3b4cd))
- fix user code handling in TS codegen prelude ([c435caa](https://github.com/thi-ng/umbrella/commit/c435caa))
#### ♻️ Refactoring
- update WasmStringSlice.setSlice() ([f278cfd](https://github.com/thi-ng/umbrella/commit/f278cfd))
- rename _printStr0() => printStrZ() ([666546c](https://github.com/thi-ng/umbrella/commit/666546c))
- update/extract C types & core API ([9eb827e](https://github.com/thi-ng/umbrella/commit/9eb827e))
- migrate JSON schema, update readme & pkg ([a6d9c3a](https://github.com/thi-ng/umbrella/commit/a6d9c3a))
### [0.18.1](https://github.com/thi-ng/umbrella/tree/@thi.ng/wasm-api@0.18.1) (2022-11-01)

@@ -67,11 +147,2 @@

- update TS docstring generator ([5a060b6](https://github.com/thi-ng/umbrella/commit/5a060b6))
- include native/WASM type in docstring (use Zig type sigs)
- update ensureLines() helper
- update test fixtures
- update IWasmMemoryAccess & impls ([bb8a3ca](https://github.com/thi-ng/umbrella/commit/bb8a3ca))
- add MemorySlice tuple to describe a memory region
- update allocate() & free() to use MemorySlice, migrate to IWasmMemoryAccess
- migrate growMemory() to IWasmMemoryAccess
- add MemorySlice to default imports in TS codegen
- update docstring & user code codegen config ([68694ba](https://github.com/thi-ng/umbrella/commit/68694ba))

@@ -83,2 +154,11 @@ - allow doc strings & user codes to be given as string array (lines)

- add internal ensureLines() helper
- update IWasmMemoryAccess & impls ([bb8a3ca](https://github.com/thi-ng/umbrella/commit/bb8a3ca))
- add MemorySlice tuple to describe a memory region
- update allocate() & free() to use MemorySlice, migrate to IWasmMemoryAccess
- migrate growMemory() to IWasmMemoryAccess
- add MemorySlice to default imports in TS codegen
- update TS docstring generator ([5a060b6](https://github.com/thi-ng/umbrella/commit/5a060b6))
- include native/WASM type in docstring (use Zig type sigs)
- update ensureLines() helper
- update test fixtures

@@ -93,6 +173,8 @@ #### 🩹 Bug fixes

- import ManagedIndex, migrate Zig API ([d8bb3ee](https://github.com/thi-ng/umbrella/commit/d8bb3ee))
- migrate ManagedIndex from [@thi.ng/wasm-api-dom](https://github.com/thi-ng/umbrella/tree/main/packages/wasm-api-dom)
- move all Zig sources from /include => /zig
- update pkg
- add WasmTarget codegen opt & usize support ([62c049b](https://github.com/thi-ng/umbrella/commit/62c049b))
- add/update codegen alignment logic ([9c19ad9](https://github.com/thi-ng/umbrella/commit/9c19ad9))
- add AlignmentStrategy & impls
- update alignOf(), sizeOf(), prepareType()
- extract DEFAULT_CODEGEN_OPTS
- add Struct.align config option
- add codegen support for union types ([bbc1f98](https://github.com/thi-ng/umbrella/commit/bbc1f98))

@@ -103,23 +185,21 @@ - add Union type, update TopLevelType

- update selectAlignment()
- add/update codegen alignment logic ([9c19ad9](https://github.com/thi-ng/umbrella/commit/9c19ad9))
- add AlignmentStrategy & impls
- update alignOf(), sizeOf(), prepareType()
- extract DEFAULT_CODEGEN_OPTS
- add Struct.align config option
- add WasmTarget codegen opt & usize support ([62c049b](https://github.com/thi-ng/umbrella/commit/62c049b))
- import ManagedIndex, migrate Zig API ([d8bb3ee](https://github.com/thi-ng/umbrella/commit/d8bb3ee))
- migrate ManagedIndex from [@thi.ng/wasm-api-dom](https://github.com/thi-ng/umbrella/tree/main/packages/wasm-api-dom)
- move all Zig sources from /include => /zig
- update pkg
#### 🩹 Bug fixes
- update CLI wrapper to allow unions ([904716c](https://github.com/thi-ng/umbrella/commit/904716c))
- fix i64/u64 handling in sizeof() ([825add3](https://github.com/thi-ng/umbrella/commit/825add3))
- fix padding in Zig packed structs ([8d70cf6](https://github.com/thi-ng/umbrella/commit/8d70cf6))
- since packed structs can't contain `[n]u8` types,
generate padding as potentially multiple `uXXX` fields
- fix i64/u64 handling in sizeof() ([825add3](https://github.com/thi-ng/umbrella/commit/825add3))
- update CLI wrapper to allow unions ([904716c](https://github.com/thi-ng/umbrella/commit/904716c))
#### ♻️ Refactoring
- minor updates C & Zig codegens ([a94e1cc](https://github.com/thi-ng/umbrella/commit/a94e1cc))
- rename types, use predicates ([4148e1e](https://github.com/thi-ng/umbrella/commit/4148e1e))
- rename StructField => Field
- update codegens to use more predicates instead of inline checks
- minor updates C & Zig codegens ([a94e1cc](https://github.com/thi-ng/umbrella/commit/a94e1cc))

@@ -130,9 +210,9 @@ ## [0.14.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/wasm-api@0.14.0) (2022-10-17)

- add ptrCast() zig helper ([72a9406](https://github.com/thi-ng/umbrella/commit/72a9406))
- add Zig Slice & String wrappers ([28d057e](https://github.com/thi-ng/umbrella/commit/28d057e))
- allows expressing & converting slices for `extern struct`s
- ensure memory in WasmStringSlice/Ptr ([c55c6f0](https://github.com/thi-ng/umbrella/commit/c55c6f0))
- update IWasmMemoryAccess ([28bfff6](https://github.com/thi-ng/umbrella/commit/28bfff6))
- add IWasmMemoryAccess.ensureMemory()
- update WasmBridge.setString() to ensure memory
- ensure memory in WasmStringSlice/Ptr ([c55c6f0](https://github.com/thi-ng/umbrella/commit/c55c6f0))
- add Zig Slice & String wrappers ([28d057e](https://github.com/thi-ng/umbrella/commit/28d057e))
- allows expressing & converting slices for `extern struct`s
- add ptrCast() zig helper ([72a9406](https://github.com/thi-ng/umbrella/commit/72a9406))

@@ -143,5 +223,5 @@ ## [0.13.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/wasm-api@0.13.0) (2022-10-04)

- add WasmStringSlice.setSlice() ([50cc798](https://github.com/thi-ng/umbrella/commit/50cc798))
- update C11 code gen ([ff8037f](https://github.com/thi-ng/umbrella/commit/ff8037f))
- add `#ifdef __cplusplus` guards to pre/post
- add WasmStringSlice.setSlice() ([50cc798](https://github.com/thi-ng/umbrella/commit/50cc798))

@@ -156,6 +236,9 @@ #### ⏱ Performance improvements

- update CLI ([98d2414](https://github.com/thi-ng/umbrella/commit/98d2414))
- add optional type analytics JSON output
- add support for including user code via `@`-file references
- update config `@`-file refs to resolve relative to config file
- add doc string word wrapping ([c0b8e15](https://github.com/thi-ng/umbrella/commit/c0b8e15))
- update prefixLines(), add target line width arg
- update ICodeGen & CodeGenOpts
- update all codegens
- update deps
- add default value support for Zig codegen ([3c37ae7](https://github.com/thi-ng/umbrella/commit/3c37ae7))
- add ReadonlyWasmString, update impls ([240a148](https://github.com/thi-ng/umbrella/commit/240a148))
- add support for sentinels & user type body injection ([d240046](https://github.com/thi-ng/umbrella/commit/d240046))

@@ -168,15 +251,12 @@ - update sizeOf() to include sentinels

- add `std` import header
- add ReadonlyWasmString, update impls ([240a148](https://github.com/thi-ng/umbrella/commit/240a148))
- add default value support for Zig codegen ([3c37ae7](https://github.com/thi-ng/umbrella/commit/3c37ae7))
- add doc string word wrapping ([c0b8e15](https://github.com/thi-ng/umbrella/commit/c0b8e15))
- update prefixLines(), add target line width arg
- update ICodeGen & CodeGenOpts
- update all codegens
- update deps
- update CLI ([98d2414](https://github.com/thi-ng/umbrella/commit/98d2414))
- add optional type analytics JSON output
- add support for including user code via `@`-file references
- update config `@`-file refs to resolve relative to config file
#### 🩹 Bug fixes
- minor fix word wrap line width ([053ba0f](https://github.com/thi-ng/umbrella/commit/053ba0f))
- update zig panic handler sig for latest zig master version ([cb51bf6](https://github.com/thi-ng/umbrella/commit/cb51bf6))
- see https://github.com/ziglang/zig/commit/694fab484805088030fa36efe3e6b6e7ee385852
- minor fix word wrap line width ([053ba0f](https://github.com/thi-ng/umbrella/commit/053ba0f))

@@ -187,6 +267,33 @@ ## [0.11.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/wasm-api@0.11.0) (2022-09-21)

- refactor CodeGenOpts, update CLI config handling ([fa2e30f](https://github.com/thi-ng/umbrella/commit/fa2e30f))
- extract CodeGenOptsBase interface for common pre/post config
- update CLI config loading to support loading pre/post contents
from separate files (if value given as `@path/to-file.ext`)
- update core API & bindings ([b185ea5](https://github.com/thi-ng/umbrella/commit/b185ea5))
- add _panic(), timer(), epoch() core API fns
- update printI/U64() fns to accept bigint
- update C & Zig bindings
- update tests
- add clang-format
- add WasmString wrappers ([18d8fcb](https://github.com/thi-ng/umbrella/commit/18d8fcb))
- still unused (to be added to TS codegen)
- WasmString codegen integration ([97fc318](https://github.com/thi-ng/umbrella/commit/97fc318))
- update TS codegen to wrap strings using new `WasmString` or `WasmStringPtr`
- update global codegen options handling, now passed to each codegen
- update TSOpts & ZigOpts to include custom pre/post
- major update codegens, string & pointer handling ([4f02295](https://github.com/thi-ng/umbrella/commit/4f02295))
- update/fix string wrappers (`WasmStringSlice/Ptr`)
- add generic `Pointer` wrapper
- add `const` field type support
- add applyIndents() formatter fn, simplify all codegens
- major update TS & Zig codegens
- update CodeGenOpts ([b9fd7ff](https://github.com/thi-ng/umbrella/commit/b9fd7ff))
- update TS codegen (array pointers) ([30360f2](https://github.com/thi-ng/umbrella/commit/30360f2))
- add C11 support, update codegens & config ([590311e](https://github.com/thi-ng/umbrella/commit/590311e))
- add preliminary C11 codegen
- add optional `tag` field for structs (extern/packed)
- add support for auto-labeled padding fields
- i.e. defined via unnamed fields with `pad` value
- move debug config option to global `CodeGenOpts`
- update codegen CLI ([435ad2b](https://github.com/thi-ng/umbrella/commit/435ad2b))
- add C11 support
- add support for padding fields (in `validateTypeRefs()`)
- add CLI arg for forcing string type impl
- update deps
- update/fix codegens & config ([87def23](https://github.com/thi-ng/umbrella/commit/87def23))

@@ -199,33 +306,6 @@ - add global `CodeGenOpts.uppercaseEnums` option (migrate from TSOpts)

- minor updates Zig codegen
- update codegen CLI ([435ad2b](https://github.com/thi-ng/umbrella/commit/435ad2b))
- add C11 support
- add support for padding fields (in `validateTypeRefs()`)
- add CLI arg for forcing string type impl
- update deps
- add C11 support, update codegens & config ([590311e](https://github.com/thi-ng/umbrella/commit/590311e))
- add preliminary C11 codegen
- add optional `tag` field for structs (extern/packed)
- add support for auto-labeled padding fields
- i.e. defined via unnamed fields with `pad` value
- move debug config option to global `CodeGenOpts`
- update TS codegen (array pointers) ([30360f2](https://github.com/thi-ng/umbrella/commit/30360f2))
- update CodeGenOpts ([b9fd7ff](https://github.com/thi-ng/umbrella/commit/b9fd7ff))
- major update codegens, string & pointer handling ([4f02295](https://github.com/thi-ng/umbrella/commit/4f02295))
- update/fix string wrappers (`WasmStringSlice/Ptr`)
- add generic `Pointer` wrapper
- add `const` field type support
- add applyIndents() formatter fn, simplify all codegens
- major update TS & Zig codegens
- WasmString codegen integration ([97fc318](https://github.com/thi-ng/umbrella/commit/97fc318))
- update TS codegen to wrap strings using new `WasmString` or `WasmStringPtr`
- update global codegen options handling, now passed to each codegen
- update TSOpts & ZigOpts to include custom pre/post
- add WasmString wrappers ([18d8fcb](https://github.com/thi-ng/umbrella/commit/18d8fcb))
- still unused (to be added to TS codegen)
- update core API & bindings ([b185ea5](https://github.com/thi-ng/umbrella/commit/b185ea5))
- add _panic(), timer(), epoch() core API fns
- update printI/U64() fns to accept bigint
- update C & Zig bindings
- update tests
- add clang-format
- refactor CodeGenOpts, update CLI config handling ([fa2e30f](https://github.com/thi-ng/umbrella/commit/fa2e30f))
- extract CodeGenOptsBase interface for common pre/post config
- update CLI config loading to support loading pre/post contents
from separate files (if value given as `@path/to-file.ext`)

@@ -270,11 +350,11 @@ ## [0.10.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/wasm-api@0.10.0) (2022-08-24)

- add CLI wrapper for codegens ([683a560](https://github.com/thi-ng/umbrella/commit/683a560))
- update helper predicates ([65b23d4](https://github.com/thi-ng/umbrella/commit/65b23d4))
- update TSOpts & TS codegen ([4f6bbbf](https://github.com/thi-ng/umbrella/commit/4f6bbbf))
- add `uppercaseEnum` option to force UC enum IDs
- update helper predicates ([65b23d4](https://github.com/thi-ng/umbrella/commit/65b23d4))
- add CLI wrapper for codegens ([683a560](https://github.com/thi-ng/umbrella/commit/683a560))
#### 🩹 Bug fixes
- correct TS __mapArray codegen ([289b137](https://github.com/thi-ng/umbrella/commit/289b137))
- allow signed ints for enum tags ([78d0822](https://github.com/thi-ng/umbrella/commit/78d0822))
- correct TS __mapArray codegen ([289b137](https://github.com/thi-ng/umbrella/commit/289b137))

@@ -285,7 +365,14 @@ ## [0.6.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/wasm-api@0.6.0) (2022-08-15)

- add C11 header/include file, update WasmBridge ([a67dc00](https://github.com/thi-ng/umbrella/commit/a67dc00))
- migrate headers/includes to /include
- rename "core" import section => "wasmapi"
- rename WasmBridge.core => WasmBridge.api
- update pkg file
- update allocate/free() fns, update Zig core API ([8a55989](https://github.com/thi-ng/umbrella/commit/8a55989))
- add _wasm_free() Zig impl
- add printFmt() Zig fn
- update WasmBridge.allocate() (add clear option)
- update WasmBridge.free()
- ensure memory in WasmBridge.getString()
- add/update docstrings
- add bindings code generator framework ([17ee06f](https://github.com/thi-ng/umbrella/commit/17ee06f))
- add/update deps
- add preliminary codegens for Zig & TS
- add supporting types & utils
- add generateTypes() codegen facade fn
- update codegens, add opts, fix alignments ([5c1fec5](https://github.com/thi-ng/umbrella/commit/5c1fec5))

@@ -299,14 +386,7 @@ - add global CodeGenOpts

- make prepareType() idempotent
- add bindings code generator framework ([17ee06f](https://github.com/thi-ng/umbrella/commit/17ee06f))
- add/update deps
- add preliminary codegens for Zig & TS
- add supporting types & utils
- add generateTypes() codegen facade fn
- update allocate/free() fns, update Zig core API ([8a55989](https://github.com/thi-ng/umbrella/commit/8a55989))
- add _wasm_free() Zig impl
- add printFmt() Zig fn
- update WasmBridge.allocate() (add clear option)
- update WasmBridge.free()
- ensure memory in WasmBridge.getString()
- add/update docstrings
- add C11 header/include file, update WasmBridge ([a67dc00](https://github.com/thi-ng/umbrella/commit/a67dc00))
- migrate headers/includes to /include
- rename "core" import section => "wasmapi"
- rename WasmBridge.core => WasmBridge.api
- update pkg file

@@ -341,8 +421,2 @@ #### ♻️ Refactoring

- add i64/u64 support/accessors ([768c8bd](https://github.com/thi-ng/umbrella/commit/768c8bd))
- add WasmBridge.instantiate, add/update accessors ([0698bae](https://github.com/thi-ng/umbrella/commit/0698bae))
- add WasmBridge.instantiate() boilerplate
- add setters for typed scalars & arrays
- rename derefXX() => getXX() getters
- update tests
- major update WasmBridge, add types ([47aa222](https://github.com/thi-ng/umbrella/commit/47aa222))

@@ -354,2 +428,8 @@ - add WasmExports base interface

- add naming conflict check in WasmBridge.getImports()
- add WasmBridge.instantiate, add/update accessors ([0698bae](https://github.com/thi-ng/umbrella/commit/0698bae))
- add WasmBridge.instantiate() boilerplate
- add setters for typed scalars & arrays
- rename derefXX() => getXX() getters
- update tests
- add i64/u64 support/accessors ([768c8bd](https://github.com/thi-ng/umbrella/commit/768c8bd))

@@ -360,2 +440,3 @@ ## [0.2.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/wasm-api@0.2.0) (2022-08-01)

- fix zig slice pointer handling, use named child modules ([bd7905a](https://github.com/thi-ng/umbrella/commit/bd7905a))
- major update ObjectIndex ([4547f1f](https://github.com/thi-ng/umbrella/commit/4547f1f))

@@ -366,3 +447,2 @@ - add ObjectIndexOpts ctor options

- rename existing methods
- fix zig slice pointer handling, use named child modules ([bd7905a](https://github.com/thi-ng/umbrella/commit/bd7905a))

@@ -369,0 +449,0 @@ ## [0.1.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/wasm-api@0.1.0) (2022-08-01)

export * from "./api.js";
export * from "./bridge.js";
export * from "./codegen.js";
export * from "./codegen/c11.js";
export * from "./codegen/typescript.js";
export * from "./codegen/utils.js";
export * from "./codegen/zig.js";
export * from "./object-index.js";

@@ -9,0 +4,0 @@ export * from "./pointer.js";

export * from "./api.js";
export * from "./bridge.js";
export * from "./codegen.js";
export * from "./codegen/c11.js";
export * from "./codegen/typescript.js";
export * from "./codegen/utils.js";
export * from "./codegen/zig.js";
export * from "./object-index.js";
export * from "./pointer.js";
export * from "./string.js";
{
"name": "@thi.ng/wasm-api",
"version": "0.18.1",
"description": "Generic, modular, extensible API bridge, polyglot glue code and bindings code generators for hybrid JS & WebAssembly projects",
"version": "1.0.0",
"description": "Generic, modular, extensible API bridge and infrastructure for hybrid JS & WebAssembly projects",
"type": "module",
"module": "./index.js",
"typings": "./index.d.ts",
"bin": "bin/wasm-api",
"sideEffects": false,

@@ -36,26 +35,19 @@ "repository": {

"test": "testament test",
"test:build-zig": "zig build-lib -O ReleaseSmall -target wasm32-freestanding -dynamic --strip --pkg-begin wasmapi zig/wasmapi.zig --pkg-end test/custom.zig && wasm-dis -o custom.wast custom.wasm && cp custom.wasm test"
"test:build-zig": "zig build-lib -O ReleaseSmall -target wasm32-freestanding -dynamic --strip --pkg-begin wasmapi zig/lib.zig --pkg-end test/custom.zig && wasm-dis -o custom.wast custom.wasm && cp custom.wasm test"
},
"dependencies": {
"@thi.ng/api": "^8.4.5",
"@thi.ng/args": "^2.2.8",
"@thi.ng/arrays": "^2.4.1",
"@thi.ng/binary": "^3.3.9",
"@thi.ng/checks": "^3.3.2",
"@thi.ng/compare": "^2.1.15",
"@thi.ng/defmulti": "^2.1.20",
"@thi.ng/errors": "^2.2.3",
"@thi.ng/file-io": "^0.3.18",
"@thi.ng/hex": "^2.2.2",
"@thi.ng/idgen": "^2.1.17",
"@thi.ng/logger": "^1.4.2",
"@thi.ng/paths": "^5.1.21",
"@thi.ng/strings": "^3.3.16"
"@thi.ng/api": "^8.4.6",
"@thi.ng/arrays": "^2.4.2",
"@thi.ng/checks": "^3.3.3",
"@thi.ng/errors": "^2.2.4",
"@thi.ng/hex": "^2.3.0",
"@thi.ng/idgen": "^2.1.18",
"@thi.ng/logger": "^1.4.3"
},
"devDependencies": {
"@microsoft/api-extractor": "^7.33.5",
"@thi.ng/testament": "^0.3.4",
"@thi.ng/testament": "^0.3.5",
"rimraf": "^3.0.2",
"tools": "^0.0.1",
"typedoc": "^0.23.18",
"typedoc": "^0.23.20",
"typescript": "^4.8.4"

@@ -69,4 +61,2 @@ },

"c",
"codegen",
"enum",
"event",

@@ -77,5 +67,3 @@ "interop",

"modular",
"polyglot",
"string",
"struct",
"typedarray",

@@ -99,6 +87,4 @@ "typescript",

"files": [
"*.js",
"*.d.ts",
"bin",
"codegen",
"./*.js",
"./*.d.ts",
"include",

@@ -117,20 +103,2 @@ "zig"

},
"./codegen/align": {
"default": "./codegen/align.js"
},
"./codegen/c11": {
"default": "./codegen/c11.js"
},
"./codegen/typescript": {
"default": "./codegen/typescript.js"
},
"./codegen/utils": {
"default": "./codegen/utils.js"
},
"./codegen/zig": {
"default": "./codegen/zig.js"
},
"./codegen": {
"default": "./codegen.js"
},
"./object-index": {

@@ -150,3 +118,3 @@ "default": "./object-index.js"

},
"gitHead": "a4b60163a8caddceed5ec1b6b3584d164f61e7b6\n"
"gitHead": "044ee6a3895720fc78e115032d4d831b63510929\n"
}

@@ -23,2 +23,22 @@ import type { Fn, IDeref } from "@thi.ng/api";

}
/**
* Generic pointer facility for {@link WASM64} target, which on
* {@link Pointer64.deref()} calls wrapper function (provided as ctor arg) to
* realise the pointer's target value. The pointer's target address can be
* accessed via {@link Pointer.addr} (read/write).
*
* @remarks
* The pointer always behaves like `volatile`, i.e. memoization of target values
* is purposfully avoided and the wrapper function is executed anew _each_ time
* the pointer is deref'd.
*/
export declare class Pointer64<T> implements IDeref<T> {
readonly mem: IWasmMemoryAccess;
readonly base: bigint;
readonly fn: Fn<bigint, T>;
constructor(mem: IWasmMemoryAccess, base: bigint, fn: Fn<bigint, T>);
get addr(): bigint;
set addr(addr: bigint);
deref(): T;
}
//# sourceMappingURL=pointer.d.ts.map

@@ -28,1 +28,28 @@ /**

}
/**
* Generic pointer facility for {@link WASM64} target, which on
* {@link Pointer64.deref()} calls wrapper function (provided as ctor arg) to
* realise the pointer's target value. The pointer's target address can be
* accessed via {@link Pointer.addr} (read/write).
*
* @remarks
* The pointer always behaves like `volatile`, i.e. memoization of target values
* is purposfully avoided and the wrapper function is executed anew _each_ time
* the pointer is deref'd.
*/
export class Pointer64 {
constructor(mem, base, fn) {
this.mem = mem;
this.base = base;
this.fn = fn;
}
get addr() {
return this.mem.u64[Number(this.base >> BigInt(3))];
}
set addr(addr) {
this.mem.u64[Number(this.base >> BigInt(3))] = addr;
}
deref() {
return this.fn(this.addr);
}
}

@@ -13,10 +13,6 @@ <!-- This file is generated - DO NOT EDIT! -->

- [About](#about)
- [Data bindings & code generators](#data-bindings--code-generators)
- [CLI generator](#cli-generator)
- [Data type definitions](#data-type-definitions)
- [Example usage](#example-usage)
- [Custom API modules](#custom-api-modules)
- [Building Zig projects with these hybrid API modules](#building-zig-projects-with-these-hybrid-api-modules)
- [String handling](#string-handling)
- [Memory allocations](#memory-allocations)
- [Custom API modules](#custom-api-modules)
- [Building Zig projects with these hybrid API modules](#building-zig-projects-with-these-hybrid-api-modules)
- [Object indices & handles](#object-indices--handles)

@@ -31,3 +27,3 @@ - [Status](#status)

- [Zig version](#zig-version)
- [C11 version](#c11-version)
- [C version](#c-version)
- [Authors](#authors)

@@ -38,456 +34,38 @@ - [License](#license)

Generic, modular, extensible API bridge, polyglot glue code and bindings code generators for hybrid JS & WebAssembly projects.
Generic, modular, extensible API bridge and infrastructure for hybrid JS & WebAssembly projects.
This package provides a the following:
This package provides the following:
1. A small, generic and modular
1. A small
[`WasmBridge`](https://docs.thi.ng/umbrella/wasm-api/classes/WasmBridge.html)
class as interop basis and much reduced boilerplate for hybrid JS/WebAssembly
class as generic interop basis and much reduced boilerplate for hybrid JS/WebAssembly
applications.
2. A minimal core API for debug output, string/pointer/typedarray accessors for
8/16/32/64 bit (u)ints and 32/64 bit floats, memory allocation (optional).
Additionally, a number of support modules for [DOM
8/16/32/64 bit (u)ints and 32/64 bit floats. Additionally, a number of support
modules for [DOM
manipulation](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api-dom/),
[scheduled function
execution](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api-schedule/),
WebGL, WebGPU, WebAudio etc. is being actively worked on.
3. Include files for
[C11/C++](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api/include)
3. Different types of memory-mapped (UTF-8) string abstractions (slice or pointer based)
5. Shared (opt-in) memory allocation mechanism, also accessible from JS/TS side
4. Simple registration & dependency-order initialization for child WASM API modules
6. Include files for
[Zig](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api/zig),
and
[Zig](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api/zig),
defining glue code for the JS [core
[C/C++](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api/include)
defining glue code for the TypeScript [core
API](https://docs.thi.ng/umbrella/wasm-api/interfaces/CoreAPI.html) defined
by this package
4. Extensible shared datatype code generators for (currently) C11, Zig &
TypeScript. The latter also generates fully type checked memory-mapped
(zero-copy) accessors of WASM-side data. In general, all languages with a
WebAssembly target are supported, however currently only bindings for these
mentioned langs are included. Other languages require custom bindings, e.g.
based on the flexible primitives provided here.
5. [CLI frontend/utility](#cli-generator) to invoke the code generator(s)
7. Extensible shared [datatype code generator
infrastructure](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api-bindgen/)
for (currently) Zig & TypeScript and C11. For TS fully type checked and
memory-mapped (zero-copy) accessors of WASM-side data are generated. In
principle, all languages with a WASM target are supported, however currently
only bindings for these mentioned langs are included. Other languages require
custom bindings, e.g. based on the flexible primitives provided here.
8. [CLI
frontend/utility](https://github.com/thi-ng/umbrella/blob/develop/packages/wasm-api-bindgen/README.md#cli-generator)
for the code generator(s)
### Data bindings & code generators
The package provides an extensible codegeneration framework to simplify the
bilateral design & exchange of data structures shared between the WASM & JS host
env. Currently, code generators for TypeScript, Zig and C11 are supplied. A CLI
wrapper is available too. See the
[@thi.ng/wasm-api-dom](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api-dom/)
support package for a more thorough realworld example...
#### CLI generator
The package includes a [small CLI
wrapper](https://github.com/thi-ng/umbrella/blob/develop/packages/wasm-api/src/cli.ts)
to invoke the code generator(s) from JSON type definitions and to write the
generated source code(s) to different files:
```text
$ npx @thi.ng/wasm-api
█ █ █ │
██ █ │
█ █ █ █ █ █ █ █ │ @thi.ng/wasm-api 0.15.0
█ █ █ █ █ █ █ █ █ │ Multi-language data bindings code generator
█ │
█ █ │
usage: wasm-api [OPTS] JSON-INPUT-FILE(S) ...
wasm-api --help
Flags:
-d, --debug enable debug output & functions
--dry-run enable dry run (don't overwrite files)
Main:
-a FILE, --analytics FILE output file path for raw codegen analytics
-c FILE, --config FILE JSON config file with codegen options
-l ID[,..], --lang ID[,..] [multiple] target language: "c11", "ts", "zig" (default: ["ts","zig"])
-o FILE, --out FILE [multiple] output file path
-s TYPE, --string TYPE Force string type implementation: "slice", "ptr"
```
By default, the CLI generates sources for TypeScript and Zig (in this order!).
Order is important, since the output file paths must be given in the same order
as the target languages. It's recommended to be explicit with this. An example
invocation looks like:
```bash
wasm-api \
--config codegen-opts.json \
--lang ts -o src/generated.ts \
--lang zig -o src.zig/generated.zig \
typedefs.json
```
The structure of the config file is as follows (all optional):
```json
{
"global": { ... },
"c11": { ... },
"ts": { ... },
"zig": { ... },
}
```
More details about possible
[`global`](https://docs.thi.ng/umbrella/wasm-api/interfaces/CodeGenOpts.html),
[`c`](https://docs.thi.ng/umbrella/wasm-api/interfaces/C11Opts.html) and
[`ts`](https://docs.thi.ng/umbrella/wasm-api/interfaces/TSOpts.html) and
[`zig`](https://docs.thi.ng/umbrella/wasm-api/interfaces/ZigOpts.html) config
options & values.
All code generators have support for custom code prologues & epilogues which can
be specified via the above options. These config options exist for both non-CLI
& CLI usage. For the latter, these custom code sections can also be loaded from
external files by specifying their file paths using `@` as prefix, e.g.
```json
{
"ts": { "pre": "@tpl/prelude.ts" },
"zig": { "pre": "@tpl/prelude.zig", "post": "@tpl/epilogue.zig" },
}
```
#### Data type definitions
Currently, the code generator supports enums, structs and unions. See API docs for
further details:
- [`Enum`](https://docs.thi.ng/umbrella/wasm-api/interfaces/Enum.html)
- [`EnumValue`](https://docs.thi.ng/umbrella/wasm-api/interfaces/EnumValue.html) (individual enum value spec)
- [`Field`](https://docs.thi.ng/umbrella/wasm-api/interfaces/Field.html) (individual spec for values contained in structs/unions)
- [`Struct`](https://docs.thi.ng/umbrella/wasm-api/interfaces/Struct.html)
- [`Union`](https://docs.thi.ng/umbrella/wasm-api/interfaces/Union.html)
- [`TopLevelType`](https://docs.thi.ng/umbrella/wasm-api/interfaces/TopLevelType.html)
#### Example usage
The following example defines 1x enum, 2x structs and 1x union. Shown here are
the JSON type definitions and the resulting source codes:
**⬇︎ CLICK TO EXPAND EACH CODE BLOCK ⬇︎**
<details><summary>types.json (Type definitions)</summary>
```json tangle:export/readme-types.json
[
{
"name": "EventType",
"type": "enum",
"tag": "u8",
"values": [
"unknown",
{ "name": "mouse", "value": 16 },
{ "name": "key", "value": 32 }
]
},
{
"name": "MouseEvent",
"type": "struct",
"doc": "Example struct",
"fields": [
{ "name": "type", "type": "EventType" },
{ "name": "pos", "type": "u16", "tag": "vec", "len": 2 }
]
},
{
"name": "KeyEvent",
"type": "struct",
"doc": "Example struct",
"fields": [
{ "name": "type", "type": "EventType" },
{ "name": "key", "type": "string" },
{ "name": "modifiers", "type": "u8", "doc": "Bitmask of modifier keys" }
]
},
{
"name": "Event",
"type": "union",
"fields": [
{ "name": "mouse", "type": "MouseEvent" },
{ "name": "key", "type": "KeyEvent" }
]
}
]
```
</details>
<details><summary>generated.ts (generated TypeScript source)</summary>
```ts
/**
* Generated by @thi.ng/wasm-api at 2022-10-26T08:36:16.825Z - DO NOT EDIT!
*/
// @ts-ignore possibly includes unused imports
import { Pointer, WasmStringSlice, WasmTypeBase, WasmTypeConstructor } from "@thi.ng/wasm-api";
export enum EventType {
UNKNOWN,
MOUSE = 16,
KEY = 32,
}
/**
* Example struct
*/
export interface MouseEvent extends WasmTypeBase {
type: EventType;
pos: Uint16Array;
}
export const $MouseEvent: WasmTypeConstructor<MouseEvent> = (mem) => ({
get align() {
return 4;
},
get size() {
return 8;
},
instance: (base) => {
return {
get __base() {
return base;
},
get __bytes() {
return mem.u8.subarray(base, base + 8);
},
get type(): EventType {
return mem.u8[base];
},
set type(x: EventType) {
mem.u8[base] = x;
},
get pos(): Uint16Array {
const addr = (base + 4) >>> 1;
return mem.u16.subarray(addr, addr + 2);
},
};
}
});
/**
* Example struct
*/
export interface KeyEvent extends WasmTypeBase {
type: EventType;
key: WasmStringSlice;
/**
* Bitmask of modifier keys
*/
modifiers: number;
}
export const $KeyEvent: WasmTypeConstructor<KeyEvent> = (mem) => ({
get align() {
return 4;
},
get size() {
return 16;
},
instance: (base) => {
let $key: WasmStringSlice | null = null;
return {
get __base() {
return base;
},
get __bytes() {
return mem.u8.subarray(base, base + 16);
},
get type(): EventType {
return mem.u8[base];
},
set type(x: EventType) {
mem.u8[base] = x;
},
get key(): WasmStringSlice {
return $key || ($key = new WasmStringSlice(mem, (base + 4), true));
},
get modifiers(): number {
return mem.u8[(base + 12)];
},
set modifiers(x: number) {
mem.u8[(base + 12)] = x;
},
};
}
});
export interface Event extends WasmTypeBase {
mouse: MouseEvent;
key: KeyEvent;
}
export const $Event: WasmTypeConstructor<Event> = (mem) => ({
get align() {
return 4;
},
get size() {
return 16;
},
instance: (base) => {
return {
get __base() {
return base;
},
get __bytes() {
return mem.u8.subarray(base, base + 16);
},
get mouse(): MouseEvent {
return $MouseEvent(mem).instance(base);
},
set mouse(x: MouseEvent) {
mem.u8.set(x.__bytes, base);
},
get key(): KeyEvent {
return $KeyEvent(mem).instance(base);
},
set key(x: KeyEvent) {
mem.u8.set(x.__bytes, base);
},
};
}
});
```
</details>
<details><summary>generated.zig (generated Zig source)</summary>
```zig
//! Generated by @thi.ng/wasm-api at 2022-10-26T08:36:16.827Z - DO NOT EDIT!
const std = @import("std");
pub const EventType = enum(u8) {
UNKNOWN,
MOUSE = 16,
KEY = 32,
};
/// Example struct
pub const MouseEvent = struct {
type: EventType,
pos: @Vector(2, u16),
};
/// Example struct
pub const KeyEvent = struct {
type: EventType,
key: []const u8,
/// Bitmask of modifier keys
modifiers: u8,
};
pub const Event = union {
mouse: MouseEvent,
key: KeyEvent,
};
```
</details>
On the TypeScript/JS side, the memory-mapped wrappers (e.g. `$Event`)
can be used in combination with the `WasmBridge` to obtain fully typed views
(according to the generated types) of the underlying WASM memory. Basic usage is
like:
```ts
import { WasmBridge } from "@thi.ng/wasm-api";
import { $Event, EventType } from "./generated.ts";
const bridge = new WasmBridge();
// bridge initialization omitted here (see other examples below)
// ...
// Create an instance using the bridge's memory views
// and mapping a `Event` union from given address
// (e.g. obtained from an exported WASM function/value)
const event = $Event(bridge).instance(0x10000);
// then use like normal JS object
event.mouse.pos
// Uint16Array(2) [100, 200]
// IMPORTANT: any modifications like this are directly
// applied to the underlying WASM memory...
event.mouse.pos[0] = 300;
event.mouse.type === EventType.MOUSE
// true
```
**IMPORTANT:** Field setters are currently only supported for single values,
incl. enums, strings, structs, unions. The latter 2 will always be copied by
value (mem copy). Arrays or slices of strings do not currently provide write
access...
### String handling
Most low-level languages deal with strings very differently and alas there's no
general standard. Some have UTF-8/16 support, others don't. In some languages
(incl. C & Zig), strings are stored as zero terminated, in others they aren't...
It's outside the scope of this package to provide an allround out-of-the-box
solution. The `WasmBridge` provides read & write accessors to obtain JS strings
from UTF-8 encoded WASM memory. See
[`getString()`](https://docs.thi.ng/umbrella/wasm-api/classes/WasmBridge.html#getString)
and
[`setString()`](https://docs.thi.ng/umbrella/wasm-api/classes/WasmBridge.html#setString)
for details.
The code generators too provide a global `stringType` option to
interpret the `string` type of a struct field in different ways:
- `slice` (default): Considers strings as Zig-style slices (i.e. pointer + length)
- `ptr`: Considers strings as C-style raw `*char` pointer (without any length)
Note: If setting this global option to `ptr`, it also has to be repeated for the
TypeScript code generator explicitly.
### Memory allocations
If explicitly enabled on the WASM side, the `WasmBridge` includes support for
malloc/free-style allocations (within the linear WASM memory) from the JS side
(Note: This is a breaking change in v0.10.0, now using a more flexible approach
& reverse logic of earlier alpha versions).
The actual allocator is implementation specific and suitable generic mechanisms
are defined for both the included Zig & C bindings. Please see for further
reference:
- [`/zig/lib.zig`](https://github.com/thi-ng/umbrella/blob/develop/packages/wasm-api/zig/lib.zig#L64):
comments about WASM-side allocator handling in Zig
- [`/include/wasmapi.h`](https://github.com/thi-ng/umbrella/blob/develop/packages/wasm-api/include/wasmapi.h#L18):
comments about WASM-side allocator handling in C/C++
- [`WasmBridge.allocate()`](https://docs.thi.ng/umbrella/wasm-api/classes/WasmBridge.html#allocate):
allocating memory from JS side
- [`WasmBridge.free()`](https://docs.thi.ng/umbrella/wasm-api/classes/WasmBridge.html#free):
freeing previously allocated memory from JS side
Note: The provided Zig mechanism supports the idiomatic (Zig) pattern of working
with multiple allocators in different parts of the application and supports
dynamic assignments/swapping of the exposed allocator. See comments in source
file and
[tests](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api/test)
for more details...
```ts
try {
// allocate 1KB of memory for passing a string to WASM side
const addr = bridge.allocate(256);
// write string to reserved memory
// max. 256 bytes, zero terminated
const num = bridge.setString("hello WASM world!", addr, 256, true);
// call WASM function doing something w/ the string
bridge.exports.doSomethingWithString(addr, num);
// cleanup
bridge.free(addr, 256);
} catch(e) {
// deal with allocation error
// ...
}
```
### Custom API modules

@@ -605,2 +183,61 @@

### String handling
Most low-level languages deal with strings very differently and alas there's no
general standard. Some have UTF-8/16 support, others don't. In some languages
(incl. C & Zig), strings are stored as zero terminated, in others they aren't...
It's outside the scope of this package to provide an allround out-of-the-box
solution. The `WasmBridge` provides read & write accessors to obtain JS strings
from UTF-8 encoded WASM memory. See
[`getString()`](https://docs.thi.ng/umbrella/wasm-api/classes/WasmBridge.html#getString)
and
[`setString()`](https://docs.thi.ng/umbrella/wasm-api/classes/WasmBridge.html#setString)
for details.
### Memory allocations
If explicitly enabled on the WASM side, the `WasmBridge` includes support for
malloc/free-style allocations (within the linear WASM memory) from the JS side.
The actual allocator is implementation specific and suitable generic mechanisms
are defined for both the included Zig & C bindings. Please see for further
reference:
- [`/zig/lib.zig`](https://github.com/thi-ng/umbrella/blob/develop/packages/wasm-api/zig/lib.zig#L37-L71):
comments about WASM-side allocator handling in Zig
- [`/include/wasmapi.h`](https://github.com/thi-ng/umbrella/blob/develop/packages/wasm-api/include/wasmapi.h#L20-L30):
comments about WASM-side allocator handling in C/C++
- [`WasmBridge.allocate()`](https://docs.thi.ng/umbrella/wasm-api/classes/WasmBridge.html#allocate):
allocating memory from JS side
- [`WasmBridge.free()`](https://docs.thi.ng/umbrella/wasm-api/classes/WasmBridge.html#free):
freeing previously allocated memory from JS side
Note: The provided Zig library supports the idiomatic (Zig) pattern of working
with multiple allocators in different parts of the application and supports
dynamic assignments/swapping of the exposed allocator. See comments in source
file and
[tests](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api/test)
for more details...
```ts
try {
// allocate 256 bytes of memory for passing a string to WASM side
// the function returns a tuple of `[address, len]`
const [addr, len] = bridge.allocate(256);
// write zero terminated string to reserved memory (max. `len` bytes)
// function returns number of bytes written (excl. sentinel)
const num = bridge.setString("hello WASM world!", addr, len, true);
// call WASM function doing something w/ the string
bridge.exports.doSomethingWithString(addr, num);
// cleanup
bridge.free([addr, len]);
} catch(e) {
// deal with allocation error
// ...
}
```
### Object indices & handles

@@ -669,4 +306,5 @@

- [@thi.ng/wasm-api-bindgen](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api-bindgen) - Polyglot bindings code generators for hybrid JS & WebAssembly projects
- [@thi.ng/wasm-api-dom](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api-dom) - Browser DOM bridge API for hybrid TypeScript & WASM (Zig) applications
- [@thi.ng/wasm-api-timer](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api-timer) - Delayed & scheduled function execution (via setTimeout() etc.) for hybrid WASM apps
- [@thi.ng/wasm-api-schedule](https://github.com/thi-ng/umbrella/tree/develop/packages/wasm-api-schedule) - Delayed & scheduled function execution (via setTimeout() etc.) for hybrid WASM apps

@@ -696,24 +334,13 @@ ## Installation

Package sizes (gzipped, pre-treeshake): ESM: 7.14 KB
Package sizes (gzipped, pre-treeshake): ESM: 2.70 KB
**IMPORTANT:** The package includes multiple language code generators which are
**not** required for normal use of the API bridge. Hence, the actual package
size in production will be MUCH smaller than what's stated here!
## Dependencies
- [@thi.ng/api](https://github.com/thi-ng/umbrella/tree/develop/packages/api)
- [@thi.ng/args](https://github.com/thi-ng/umbrella/tree/develop/packages/args)
- [@thi.ng/arrays](https://github.com/thi-ng/umbrella/tree/develop/packages/arrays)
- [@thi.ng/binary](https://github.com/thi-ng/umbrella/tree/develop/packages/binary)
- [@thi.ng/checks](https://github.com/thi-ng/umbrella/tree/develop/packages/checks)
- [@thi.ng/compare](https://github.com/thi-ng/umbrella/tree/develop/packages/compare)
- [@thi.ng/defmulti](https://github.com/thi-ng/umbrella/tree/develop/packages/defmulti)
- [@thi.ng/errors](https://github.com/thi-ng/umbrella/tree/develop/packages/errors)
- [@thi.ng/file-io](https://github.com/thi-ng/umbrella/tree/develop/packages/file-io)
- [@thi.ng/hex](https://github.com/thi-ng/umbrella/tree/develop/packages/hex)
- [@thi.ng/idgen](https://github.com/thi-ng/umbrella/tree/develop/packages/idgen)
- [@thi.ng/logger](https://github.com/thi-ng/umbrella/tree/develop/packages/logger)
- [@thi.ng/paths](https://github.com/thi-ng/umbrella/tree/develop/packages/paths)
- [@thi.ng/strings](https://github.com/thi-ng/umbrella/tree/develop/packages/strings)

@@ -728,6 +355,7 @@ ## Usage examples

| Screenshot | Description | Live demo | Source |
|:-------------------------------------------------------------------------------------------------------------------|:--------------------------------------------|:--------------------------------------------------|:-------------------------------------------------------------------------------|
| <img src="https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/examples/zig-canvas.png" width="240"/> | Zig-based DOM creation & canvas drawing app | [Demo](https://demo.thi.ng/umbrella/zig-canvas/) | [Source](https://github.com/thi-ng/umbrella/tree/develop/examples/zig-canvas) |
| <img src="https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/examples/zig-counter.png" width="240"/> | Simple Zig/WASM click counter DOM component | [Demo](https://demo.thi.ng/umbrella/zig-counter/) | [Source](https://github.com/thi-ng/umbrella/tree/develop/examples/zig-counter) |
| Screenshot | Description | Live demo | Source |
|:---------------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------------------|:----------------------------------------------------|:---------------------------------------------------------------------------------|
| <img src="https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/examples/zig-canvas.png" width="240"/> | Zig-based DOM creation & canvas drawing app | [Demo](https://demo.thi.ng/umbrella/zig-canvas/) | [Source](https://github.com/thi-ng/umbrella/tree/develop/examples/zig-canvas) |
| <img src="https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/examples/zig-counter.png" width="240"/> | Simple Zig/WASM click counter DOM component | [Demo](https://demo.thi.ng/umbrella/zig-counter/) | [Source](https://github.com/thi-ng/umbrella/tree/develop/examples/zig-counter) |
| <img src="https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/examples/zig-todo-list.png" width="240"/> | Zig-based To-Do list, DOM creation, local storage task persistence | [Demo](https://demo.thi.ng/umbrella/zig-todo-list/) | [Source](https://github.com/thi-ng/umbrella/tree/develop/examples/zig-todo-list) |

@@ -829,3 +457,3 @@ ## API

### C11 version
### C version

@@ -832,0 +460,0 @@ Requires [Emscripten](https://emscripten.org/) to be installed:

@@ -1,6 +0,7 @@

import type { IWasmMemoryAccess, ReadonlyWasmString } from "./api.js";
import type { IWasmMemoryAccess, MemorySlice, ReadonlyWasmString } from "./api.js";
/**
* Memory mapped string wrapper for Zig-style UTF-8 encoded byte slices (aka
* pointer & length pair). The actual JS string can be obtained via
* {@link WasmStringSlice.deref} and mutated via {@link WasmStringSlice.set}.
* {@link WasmStringSlice.deref} and possibly mutated via
* {@link WasmStringSlice.set}.
*

@@ -14,5 +15,6 @@ * @remarks

readonly base: number;
readonly isConst: boolean;
readonly max: number;
constructor(mem: IWasmMemoryAccess, base: number, isConst?: boolean);
protected isConst: boolean;
protected terminated: boolean;
protected maxLen: number;
constructor(mem: IWasmMemoryAccess, base: number, isConst?: boolean, terminated?: boolean);
/**

@@ -52,6 +54,25 @@ * Returns string start address (deref'd pointer).

*
* @param addr
* @param len
* @param slice
* @param terminated
*/
setSlice(addr: number, len: number): void;
setSlice(slice: MemorySlice, terminated: boolean): MemorySlice;
setSlice(addr: number, len: number, terminated: boolean): MemorySlice;
/**
* Encodes given string to UTF-8 (by default zero terminated), allocates
* memory for it, updates this slice and returns a {@link MemorySlice} of
* the allocated region.
*
* @remarks
* If `terminated` is true, the stored slice length will **NOT** include the
* sentinel! E.g. the slice length of zero-terminated string `"abc"` is 3,
* but the number of allocated bytes is 4. This is done for compatibility
* with Zig's sentinel-terminated slice handling (e.g. `[:0]u8` slices).
*
* Regardless of `terminated` setting, the returned `MemorySlice` **always**
* covers the entire allocated region!
*
* @param str
* @param terminate
*/
setAlloc(str: string, terminate?: boolean): MemorySlice;
toJSON(): string;

@@ -62,4 +83,4 @@ toString(): string;

/**
* Memory mapped string wrapper for C-style UTF-8 encoded and zero-terminated
* char pointers. The actual JS string can be obtained via
* Memory mapped string wrapper for C-style UTF-8 encoded and **always**
* zero-terminated char pointers. The actual JS string can be obtained via
* {@link WasmStringSlice.deref} and mutated via {@link WasmStringSlice.set}.

@@ -70,3 +91,3 @@ */

readonly base: number;
readonly isConst: boolean;
protected isConst: boolean;
constructor(mem: IWasmMemoryAccess, base: number, isConst?: boolean);

@@ -88,6 +109,7 @@ /**

/**
* If given a JS string as arg (and if not a const pointer), attempts to
* overwrite this wrapped string's memory with bytes from given string. If
* given another {@link WasmStringPtr}, it merely overrides the pointer to
* the new one (always succeeds).
* If given a JS string as arg (and if this `WasmStringPtr` instance itself
* is not a `const` pointer), attempts to overwrite this wrapped string's
* memory with bytes from given string. If given another
* {@link WasmStringPtr}, it merely overrides the pointer to the new one
* (always succeeds).
*

@@ -108,2 +130,13 @@ * @remarks

set(str: string | WasmStringPtr): void;
/**
* Encodes given string to UTF-8 (by default zero terminated), allocates
* memory for it, updates this pointer to new address and returns allocated
* {@link MemorySlice}.
*
* @remarks
* See {@link WasmStringSlice.setAlloc} for important details.
*
* @param str
*/
setAlloc(str: string): MemorySlice;
toJSON(): string;

@@ -110,0 +143,0 @@ toString(): string;

@@ -0,1 +1,2 @@

import { isNumber } from "@thi.ng/checks/is-number";
import { unsupported } from "@thi.ng/errors/unsupported";

@@ -5,3 +6,4 @@ /**

* pointer & length pair). The actual JS string can be obtained via
* {@link WasmStringSlice.deref} and mutated via {@link WasmStringSlice.set}.
* {@link WasmStringSlice.deref} and possibly mutated via
* {@link WasmStringSlice.set}.
*

@@ -13,7 +15,8 @@ * @remarks

export class WasmStringSlice {
constructor(mem, base, isConst = true) {
constructor(mem, base, isConst = true, terminated = true) {
this.mem = mem;
this.base = base;
this.isConst = isConst;
this.max = this.length;
this.terminated = terminated;
this.maxLen = this.length;
}

@@ -63,3 +66,3 @@ /**

unsupported("can't mutate const string");
this.mem.u32[(this.base + 4) >>> 2] = this.mem.setString(str, this.addr, this.max + 1, true);
this.mem.u32[(this.base + 4) >>> 2] = this.mem.setString(str, this.addr, this.maxLen + ~~this.terminated, this.terminated);
}

@@ -71,12 +74,33 @@ else {

}
setSlice(...args) {
this.mem.ensureMemory();
const [slice, terminated] = ((isNumber(args[0])
? [[args[0], args[1]], args[2]]
: [args[0], args[1]]));
this.mem.u32[this.base >>> 2] = slice[0];
this.mem.u32[(this.base + 4) >>> 2] = slice[1];
this.terminated = terminated;
return slice;
}
/**
* Sets the slice itself to the new values provided.
* Encodes given string to UTF-8 (by default zero terminated), allocates
* memory for it, updates this slice and returns a {@link MemorySlice} of
* the allocated region.
*
* @param addr
* @param len
* @remarks
* If `terminated` is true, the stored slice length will **NOT** include the
* sentinel! E.g. the slice length of zero-terminated string `"abc"` is 3,
* but the number of allocated bytes is 4. This is done for compatibility
* with Zig's sentinel-terminated slice handling (e.g. `[:0]u8` slices).
*
* Regardless of `terminated` setting, the returned `MemorySlice` **always**
* covers the entire allocated region!
*
* @param str
* @param terminate
*/
setSlice(addr, len) {
this.mem.ensureMemory();
this.mem.u32[this.base >>> 2] = addr;
this.mem.u32[(this.base + 4) >>> 2] = len;
setAlloc(str, terminate = true) {
const slice = __alloc(this.mem, str, terminate);
this.setSlice(terminate ? [slice[0], slice[1] - 1] : slice, terminate);
return slice;
}

@@ -94,4 +118,4 @@ toJSON() {

/**
* Memory mapped string wrapper for C-style UTF-8 encoded and zero-terminated
* char pointers. The actual JS string can be obtained via
* Memory mapped string wrapper for C-style UTF-8 encoded and **always**
* zero-terminated char pointers. The actual JS string can be obtained via
* {@link WasmStringSlice.deref} and mutated via {@link WasmStringSlice.set}.

@@ -132,6 +156,7 @@ */

/**
* If given a JS string as arg (and if not a const pointer), attempts to
* overwrite this wrapped string's memory with bytes from given string. If
* given another {@link WasmStringPtr}, it merely overrides the pointer to
* the new one (always succeeds).
* If given a JS string as arg (and if this `WasmStringPtr` instance itself
* is not a `const` pointer), attempts to overwrite this wrapped string's
* memory with bytes from given string. If given another
* {@link WasmStringPtr}, it merely overrides the pointer to the new one
* (always succeeds).
*

@@ -161,4 +186,20 @@ * @remarks

this.addr = str.addr;
this.isConst = str.isConst;
}
}
/**
* Encodes given string to UTF-8 (by default zero terminated), allocates
* memory for it, updates this pointer to new address and returns allocated
* {@link MemorySlice}.
*
* @remarks
* See {@link WasmStringSlice.setAlloc} for important details.
*
* @param str
*/
setAlloc(str) {
const slice = __alloc(this.mem, str, true);
this.mem.u32[this.base >>> 2] = slice[0];
return slice;
}
toJSON() {

@@ -174,1 +215,10 @@ return this.deref();

}
const __alloc = (mem, str, terminate) => {
const buf = new TextEncoder().encode(str);
const slice = mem.allocate(buf.length + ~~terminate);
if (slice[1] > 0) {
mem.u8.set(buf, slice[0]);
terminate && (mem.u8[slice[0] + buf.length] = 0);
}
return slice;
};

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc