# Bindings: WebAssembly (JavaScript)

138 public names in `bindings/wasm/sona-core.mjs`.

## Functions and constants

| Declaration | What it does |
|---|---|
| `const RESULT = Object.freeze({` | The result codes by name: OK, PENDING and the errors, the values of sona_result. |
| `const STATES = Object.freeze(['queued', 'loading', 'ready', 'failed', 'removed'])` | The avatar states by number: queued, loading, ready, failed, removed. |
| `const EVENTS = Object.freeze(['none', 'ready', 'failed', 'error', 'licence-ok'])` | The event kinds by number: none, ready, failed, error, licence-ok. |
| `const READ_KINDS = Object.freeze(['asset', 'data'])` | What a source read is for: an asset or a data file. |
| `const SOURCE_KINDS = Object.freeze({ custom: 0, gate: 1, dir: 2, console: 3 })` | The source kinds: custom, gate, dir, console. |
| `const PASSES = Object.freeze(['opaque', 'transparent'])` | The draw passes: opaque and transparent. |
| `const MAT = Object.freeze({ SKIN: 1, REFLECTIVE: 2, FACE: 4, TRANSPARENT: 8, CARRYABLE: 16 })` | Material flags: skin, reflective, face, transparent, carryable. |
| `const CFG = Object.freeze({ STILL_FACES: 1, APP_BEHAVIOUR: 2, NO_CPU_SKIN: 4 })` | Config flags: still faces, the app's behaviour, no CPU skinning. |
| `const DRAW = Object.freeze({ SHADOW: 1, NO_BLOOM: 2, EDITOR_AO: 8, NO_CREDIT: 16 })` | Draw flags: SHADOW, NO_BLOOM, EDITOR_AO, NO_CREDIT, the values of SONA_DRAW_*. |
| `const PRESETS = Object.freeze({ full: 0, upper: 1, bust: 2, face: 3 })` | The camera presets: full, upper, bust, face. |
| `const JOINT_COUNT = 72` | The number of palette slots, 72: the value of SONA_JOINTS. |
| `const QUEUE_MAX = 8` | How many clips an avatar's queue holds, 8: the value of SONA_QUEUE_MAX. |
| `const OVERRIDE = Object.freeze({ replace: 0, add: 1 })` | How a joint override applies: replace or add. |
| `const ROOT_MOTION = Object.freeze({ off: 0, extract: 1, apply: 2 })` | What happens to a clip's root motion: off, extract, apply. |
| `const LOD_STEPS = Object.freeze(['full', 'sampled', 'quarter', 'sprite'])` | The levels of detail by number: full, sampled, quarter, sprite. |
| `const CLIP_EVENTS = Object.freeze([null, 'started', 'looped', 'ended', 'foot-left', 'foot-right', 'mark'])` | Clip events by number: started, looped, ended, a foot down, a mark. |
| `const MOUTH = Object.freeze({ NEUTRAL: 0, O: 7, AI: 8, EE: 9, FV: 10, W: 11, L: 12, DTH: 13 })` | The mouth shapes lip sync uses, by number. |
| `const PREVIEW = Object.freeze({ PLAY: 1, COLOURS: 2 })` | Item preview flags: play its clip, show its colours. |
| `const QUALITY = Object.freeze({ MSAA_AUTO: 0, MIPS: 1, CUTOUT_MIPS: 2 })` | Quality values: MSAA_AUTO, and the flags MIPS and CUTOUT_MIPS. |
| `const ITEM = Object.freeze({ OFFERED: 1, NAMED: 2, STOCK: 4, AWARD: 8, MARKETPLACE: 16, HIDDEN: 32,` | Item flags: offered, named, stock, award, marketplace, hidden and the rest. |
| `const ITEM_KINDS = Object.freeze(['unknown', 'model', 'texture', 'shape-override', 'animation'])` | What an item's file holds: a model, a texture, a shape override, an animation. |
| `const ROUTES = Object.freeze(['rejected', 'worn', 'bare', 'face'])` | How an outfit check placed an item: rejected, worn, bare, face. |
| `async function loadSonaCore(moduleArgs = {})` | Loads the WebAssembly module and returns a SonaCore on it. |

## SonaCore

`class SonaCore`: The loaded WASM core: opens contexts and reads and writes the core's memory.

| Declaration | What it does |
|---|---|
| `get u8()` | Reads an unsigned byte from the core's memory. |
| `u32(p)` | Reads an unsigned 32-bit number from the core's memory. |
| `i32(p)` | Reads a signed 32-bit number from the core's memory. |
| `f32(p)` | Reads a 32-bit float from the core's memory. |
| `f64(p)` | Reads a 64-bit float from the core's memory. |
| `setU32(p, v)` | Writes an unsigned 32-bit number into the core's memory. |
| `setI32(p, v)` | Writes a signed 32-bit number into the core's memory. |
| `setF32(p, v)` | Writes a 32-bit float into the core's memory. |
| `setF64(p, v)` | Writes a 64-bit float into the core's memory. |
| `str(p)` | Reads a UTF-8 string from the core's memory (null for a NULL pointer). |
| `view(Type, p, n)` | A typed array of n elements over the core's memory at p, not copied: valid until the memory next grows. |
| `copy(Type, p, n)` | Copies bytes out of the core's memory into a new typed array. |
| `alloc(n)` | Allocates core memory; throws SonaCoreError when it cannot. |
| `free(p)` | Frees memory the library handed out (sona_png_encode), through the ctx's allocator. |
| `cstr(s)` | Copies a string into core memory as UTF-8 with its zero. |
| `bytes(b)` | Copies bytes into core memory. |
| `off(name)` | sona_struct_offset, cached; throws when the core does not know the field (an ABI mismatch).<br>Calls [`sona_struct_offset`](../c/the-context.md#sona_struct_offset). |
| `size(name)` | sizeof a public struct of the core, by its name ("sona_config",...); 0 if unknown.<br>Calls [`sona_struct_size`](../c/the-context.md#sona_struct_size). |
| `resultName(r)` | The name of a code ("licence", "gate",...): the same words as the web SDK's SonaError.code.<br>Calls [`sona_result_name`](../c/results-and-errors.md#sona_result_name). |
| `error(r, message, fix)` | A SonaCoreError for a sona_result. |
| `httpPlatform()` | NULL in this build: gate reads go through the web bridge (bridge-source.mjs).<br>Calls [`sona_http_platform`](../c/http.md#sona_http_platform). |
| `complete(req, v)` | Completes a request: bytes (OK), null (not found), or { status: 'ok' \| 'not_found' \| 'io', bytes }.<br>Calls [`sona_complete`](../c/asset-sources.md#sona_complete). |
| `open(cfg = {})` | cfg: { sources: { read(kind, name) } \| { kind: 'gate' \| 'dir' \| 'console', location }, appId, seed, maxAvatars, buildBudgetMs, faceSize, flags, budget: { total, assets, clips, faces, sourceCache, gpuIdle }, log(level, me<br>Calls [`sona_open`](../c/the-context.md#sona_open). |
| `viewDefaults()` | The default view as an object: the full-body framing of sona_view_defaults.<br>Calls [`sona_view_defaults`](../c/the-frame.md#sona_view_defaults). |
| `readView(p)` | Reads a sona_view from core memory. |
| `writeView(p, v)` | Writes a sona_view into core memory. |
| `viewMatrices(v)` | Row-vector view and projection (D3D depth), as sona_view_matrices.<br>Calls [`sona_view_matrices`](../c/camera-helpers.md#sona_view_matrices). |
| `cameraOrbit(v, target, yawDeg, pitchDeg, distance)` | Places the eye on an orbit around target.<br>Calls [`sona_camera_orbit`](../c/camera-helpers.md#sona_camera_orbit). |
| `readFields(p, struct, rows)` | Reads a struct into { jsName: value } by jsName, cField, 'u' \| 'i' \| 'f' rows. |
| `writeFields(p, struct, rows, v)` | Writes an options struct's fields into core memory, by the core's own field offsets. |
| `jointFind(name)` | A joint by name ("Hips", "Head", "PropRight", "shape_04", "joint_33"); -1 when unknown.<br>Calls [`sona_joint_find`](../c/game-features.md#sona_joint_find). |
| `jointName(joint)` | null past the last joint.<br>Calls [`sona_joint_name`](../c/game-features.md#sona_joint_name). |
| `lodDefaults()` | The level-of-detail defaults, with sprites on at 48 px.<br>Calls [`sona_lod_defaults`](../c/crowds-level-of-detail-and-sprites.md#sona_lod_defaults). |
| `previewDefaults()` | Fills the defaults above.<br>Calls [`sona_preview_defaults`](../c/item-previews.md#sona_preview_defaults). |
| `writePreview(p, opts)` | Fills the defaults above.<br>Calls [`sona_preview_defaults`](../c/item-previews.md#sona_preview_defaults). |
| `qualityDefaults()` | The web SDK's: { msaa: 0 (auto), flags: MIPS \| CUTOUT_MIPS }.<br>Calls [`sona_quality_defaults`](../c/rendering-quality.md#sona_quality_defaults). |
| `sectionName(section)` | "shirt", "facialHair",...; null past the last section.<br>Calls [`sona_catalogue_section_name`](../c/the-offline-catalogue.md#sona_catalogue_section_name). |
| `loadCatalogue(bytes)` | sona-catalogue.bin as bytes; the catalogue keeps its own copy.<br>Calls [`sona_catalogue_load_memory`](../c/the-offline-catalogue.md#sona_catalogue_load_memory). |
| `checkItem(bytes)` | The shallow check (rules 1 to 11), no network: { ok, rule, why, info }.<br>Calls [`sona_custom_item_check`](../c/custom-items.md#sona_custom_item_check). |
| `isCustomId(id)` | 1 when the id is a custom item's id, 0 for a stock item's.<br>Calls [`sona_guid_is_custom`](../c/custom-items.md#sona_guid_is_custom). |
| `pairOf(id)` | The other body's id, or null for body 3 and for real ids.<br>Calls [`sona_guid_pair`](../c/custom-items.md#sona_guid_pair). |
| `newItemId(templateId)` | A fresh id for a template (a real worn id of a 1.0 slot, body 1, 2 or 3).<br>Calls [`sona_custom_item_new_id`](../c/custom-items.md#sona_custom_item_new_id). |
| `get debug()` | Decoded assets and clips as plain objects, for comparing against another implementation. |

## SonaCtx

`class SonaCtx`: The C type sona_ctx.

| Declaration | What it does |
|---|---|
| `get appId()` | The app id this context runs as.<br>Calls [`sona_app_id`](../c/the-context.md#sona_app_id). |
| `lastError()` | The last error on a ctx.<br>Calls [`sona_last_error`](../c/results-and-errors.md#sona_last_error). |
| `close()` | Closes a context.<br>Calls [`sona_close`](../c/the-context.md#sona_close). |
| `update(dt, view = null)` | Advances by dt seconds; view (or null) culls and picks LOD.<br>Calls [`sona_update`](../c/the-frame.md#sona_update). |
| `add(manifest, opts = {})` | manifest: 1000 bytes or base64 text.<br>Calls [`sona_add_defaults`](../c/avatars.md#sona_add_defaults), [`sona_avatar_add_base64`](../c/avatars.md#sona_avatar_add_base64), [`sona_avatar_add`](../c/avatars.md#sona_avatar_add). |
| `pose(avatar)` | The data API for one avatar (avatar.pose): views valid until the next update; null before READY. |
| `events()` | Every pending event: { type, avatar, code, codeName, message, fix }.<br>Calls [`sona_poll_event`](../c/events.md#sona_poll_event). |
| `stats()` | The scene statistics.<br>Calls [`sona_stats`](../c/the-frame.md#sona_stats). |
| `clips()` | How many clips the context knows.<br>Calls [`sona_clip_count`](../c/clips.md#sona_clip_count), [`sona_clip_get`](../c/clips.md#sona_clip_get). |
| `shading()` | The fixed shading inputs (PENDING until the data files load: returns null then).<br>Calls [`sona_shading_get`](../c/the-data-api.md#sona_shading_get). |
| `credit(scale = 1)` | The credit text, link and badge.<br>Calls [`sona_credit_get`](../c/credit.md#sona_credit_get). |
| `pngEncode(rgba, width, height)` | PNG bytes (a copy) with the web's credit tEXt chunks.<br>Calls [`sona_png_encode`](../c/drawing-with-the-sdks-backends.md#sona_png_encode), [`sona_free`](../c/drawing-with-the-sdks-backends.md#sona_free). |
| `get items()` | Custom items in this ctx: add(bytes) -> info, remove(id), get(id), list, pack(spec).<br>Calls [`sona_custom_item_add`](../c/custom-items.md#sona_custom_item_add), [`sona_custom_item_find`](../c/custom-items.md#sona_custom_item_find), [`sona_custom_item_remove`](../c/custom-items.md#sona_custom_item_remove), [`sona_custom_item_count`](../c/custom-items.md#sona_custom_item_count) and 3 more. |
| `fitCrowd(view)` | Fits every ready avatar in view (the web's preset "crowd").<br>Calls [`sona_camera_fit_crowd`](../c/camera-helpers.md#sona_camera_fit_crowd). |
| `setLod(opts = null)` | LOD and sprites from the next update: { fullPx, quarterPx, spritePx, fadeSeconds, spriteAngles, spriteHeight, maxLooks, bakeMs }; missing fields take lodDefaults.<br>Calls [`sona_lod_defaults`](../c/crowds-level-of-detail-and-sprites.md#sona_lod_defaults), [`sona_lod_set`](../c/crowds-level-of-detail-and-sprites.md#sona_lod_set). |
| `lod()` | Copies the current options: before any sona_lod_set, thresholds 120 and 40 and no sprites (sprite_px 0).<br>Calls [`sona_lod_get`](../c/crowds-level-of-detail-and-sprites.md#sona_lod_get). |
| `lodStats()` | The level-of-detail statistics: avatars in view at each step, those fading, the baked looks and the bakes of the last draw.<br>Calls [`sona_lod_stats_get`](../c/crowds-level-of-detail-and-sprites.md#sona_lod_stats_get). |
| `addItemPreview(itemId, opts = {})` | One item worn alone on a grey stand-in body.<br>Calls [`sona_item_preview_add`](../c/item-previews.md#sona_item_preview_add). |
| `createRenderer({ canvas = '#canvas', alpha = true, antialias = false, framesInFlight = 0 } = {})` | WebGL2 on a canvas (CSS selector): { result, renderer }; PENDING until the shading data has loaded.<br>Calls [`sona_renderer_create`](../c/drawing-with-the-sdks-backends.md#sona_renderer_create). |

## SonaAvatar

`class SonaAvatar`: The C type sona_avatar.

| Declaration | What it does |
|---|---|
| `get state()` | The avatar's state.<br>Calls [`sona_avatar_state_of`](../c/avatars.md#sona_avatar_state_of). |
| `play(clip, opts = null)` | Plays a clip.<br>Calls [`sona_avatar_play`](../c/avatars.md#sona_avatar_play). |
| `crossfade(clip, seconds, opts = null)` | play, blending from the current pose over seconds (0: a cut).<br>Calls [`sona_avatar_crossfade`](../c/game-features.md#sona_avatar_crossfade). |
| `queue(clip, fadeSeconds = 0, opts = null)` | Plays clip when the current one ends; LIMIT past QUEUE_MAX.<br>Calls [`sona_avatar_queue`](../c/game-features.md#sona_avatar_queue). |
| `get queued()` | How many clips are waiting in the queue.<br>Calls [`sona_avatar_queued`](../c/game-features.md#sona_avatar_queued). |
| `jointWorld(joint)` | A joint's world matrix at the last update (row-vector, metres), a copy; null before READY and posed.<br>Calls [`sona_joint_world`](../c/game-features.md#sona_joint_world). |
| `setOverride(joint, rotation, weight = 1, mode = 'replace')` | rotation: a unit quaternion x, y, z, w, or null to clear the joint.<br>Calls [`sona_avatar_override`](../c/game-features.md#sona_avatar_override). |
| `clearOverrides()` | Clears every override of the avatar.<br>Calls [`sona_avatar_clear_overrides`](../c/game-features.md#sona_avatar_clear_overrides). |
| `capsule()` | { a: x, y, z, b: x, y, z, radius } in world metres; null before READY.<br>Calls [`sona_avatar_capsule`](../c/game-features.md#sona_avatar_capsule). |
| `setExpression(values)` | values: mouth, left eyebrow, right eyebrow, left eye, right eye, 255 leaves that part to the clip; null hands the face back to the clip.<br>Calls [`sona_avatar_expression`](../c/game-features.md#sona_avatar_expression). |
| `expressionCounts()` | { mouth, eyebrows, eyes }: the shapes this face has; null before READY.<br>Calls [`sona_avatar_expression_counts`](../c/game-features.md#sona_avatar_expression_counts). |
| `clipEvents()` | { kind: 'started' \| 'looped' \| 'ended' \| 'foot-left' \| 'foot-right' \| 'mark', mark, clip, time } since the last call, oldest first.<br>Calls [`sona_avatar_clip_events`](../c/game-features.md#sona_avatar_clip_events). |
| `mark(seconds, id)` | A 'mark' event with this id each time the current clip passes seconds.<br>Calls [`sona_avatar_mark`](../c/game-features.md#sona_avatar_mark). |
| `clearMarks()` | Removes the avatar's marks.<br>Calls [`sona_avatar_clear_marks`](../c/game-features.md#sona_avatar_clear_marks). |
| `setRootMotion(mode)` | 'off', 'extract' (collect the hips' travel for takeRootMotion) or 'apply' (move the placement by it).<br>Calls [`sona_avatar_root_motion`](../c/game-features.md#sona_avatar_root_motion). |
| `takeRootMotion()` | dx, dy, dz in world metres since the last call; clears it.<br>Calls [`sona_avatar_take_root_motion`](../c/game-features.md#sona_avatar_take_root_motion). |
| `lod()` | { step: 'full' \| 'sampled' \| 'quarter' \| 'sprite', fade } at the last update.<br>Calls [`sona_avatar_lod`](../c/crowds-level-of-detail-and-sprites.md#sona_avatar_lod). |
| `previewBounds()` | A preview's item box in the world: { lo, hi }; null before READY.<br>Calls [`sona_item_preview_bounds`](../c/item-previews.md#sona_item_preview_bounds). |
| `previewView(width, height)` | The framed camera for a width x height picture of this preview; null before READY.<br>Calls [`sona_item_preview_view`](../c/item-previews.md#sona_item_preview_view). |
| `stop()` | Holds the current pose.<br>Calls [`sona_avatar_stop`](../c/avatars.md#sona_avatar_stop). |
| `move(to, overSeconds = 0)` | Moves the avatar to a new placement over over_seconds.<br>Calls [`sona_avatar_move`](../c/avatars.md#sona_avatar_move). |
| `setVisible(v)` | Shows or hides it.<br>Calls [`sona_avatar_set_visible`](../c/avatars.md#sona_avatar_set_visible). |
| `bounds()` | A bounding sphere, in metres.<br>Calls [`sona_avatar_bounds`](../c/avatars.md#sona_avatar_bounds). |
| `missingItems()` | Custom ids this avatar wears that no loaded item supplied, as last built.<br>Calls [`sona_avatar_missing_items`](../c/custom-items.md#sona_avatar_missing_items). |
| `remove()` | Removes the avatar and frees what only it used.<br>Calls [`sona_avatar_remove`](../c/avatars.md#sona_avatar_remove). |
| `cameraPreset(preset = 'full', view = null)` | Sets view->eye and view->target to one of the console's framings on one ready avatar.<br>Calls [`sona_camera_preset`](../c/camera-helpers.md#sona_camera_preset). |
| `pose()` | The data API: views into WASM memory, valid until the next update.<br>Calls [`sona_pose`](../c/the-data-api.md#sona_pose). |
| `vertices(mesh, space = 'avatar', normals = true)` | CPU-skinned positions (and normals) of one mesh, copied out: { positions, normals } as Float32Array x3.<br>Calls [`sona_pose_vertices`](../c/the-data-api.md#sona_pose_vertices). |

## SonaRenderer

`class SonaRenderer`: The C type sona_renderer.

| Declaration | What it does |
|---|---|
| `draw(view, target = {}, opts = {})` | Draws every visible ready avatar, as posed by the last sona_update, folding each palette with this view.<br>Calls [`sona_draw`](../c/drawing-with-the-sdks-backends.md#sona_draw). |
| `snapshot(view, width, height, opts = {})` | Straight RGBA8, row 0 at the top (a copy).<br>Calls [`sona_snapshot`](../c/drawing-with-the-sdks-backends.md#sona_snapshot). |
| `previewDraw(preview, view, target = {}, opts = {})` | draw with only this preview in the frame; view null: avatar.previewView for the target's size.<br>Calls [`sona_item_preview_draw`](../c/item-previews.md#sona_item_preview_draw). |
| `previewSnapshot(preview, width, height, opts = {})` | Only this preview, framed for width x height: straight RGBA8, row 0 at the top (a copy).<br>Calls [`sona_item_preview_snapshot`](../c/item-previews.md#sona_item_preview_snapshot). |
| `setQuality(q = null)` | { msaa, flags } from the next draw; null: qualityDefaults.<br>Calls [`sona_quality_defaults`](../c/rendering-quality.md#sona_quality_defaults), [`sona_renderer_set_quality`](../c/rendering-quality.md#sona_renderer_set_quality). |
| `quality()` | What the renderer uses: msaa is the sample count this device draws with.<br>Calls [`sona_renderer_quality`](../c/rendering-quality.md#sona_renderer_quality). |
| `get frameIndex()` | The index of the last frame recorded (0 before the first).<br>Calls [`sona_renderer_frame_index`](../c/drawing-with-the-sdks-backends.md#sona_renderer_frame_index). |
| `destroy()` | Frees the renderer and its GPU objects.<br>Calls [`sona_renderer_destroy`](../c/drawing-with-the-sdks-backends.md#sona_renderer_destroy). |

## SonaCatalogue

`class SonaCatalogue`: The offline catalogue (core.loadCatalogue(bytes)).

| Declaration | What it does |
|---|---|
| `get count()` | Items, sorted by id.<br>Calls [`sona_catalogue_count`](../c/the-offline-catalogue.md#sona_catalogue_count). |
| `get generated()` | When its data was made, ISO 8601.<br>Calls [`sona_catalogue_generated`](../c/the-offline-catalogue.md#sona_catalogue_generated). |
| `get(index)` | { guid, id, kind, gender, section, sectionName, mask, flags, route, colourSet, name, game, type, family, description, subcategory, colourChoices, textureType, shapeType }; null past the end.<br>Calls [`sona_catalogue_get`](../c/the-offline-catalogue.md#sona_catalogue_get). |
| `find(id)` | The index of an item id (any case, dashes or not), or -1.<br>Calls [`sona_catalogue_find`](../c/the-offline-catalogue.md#sona_catalogue_find). |
| `findGuid(guid)` | The same by the 16 wire-order bytes of a sona_guid.<br>Calls [`sona_catalogue_find_guid`](../c/the-offline-catalogue.md#sona_catalogue_find_guid). |
| `search(q = {}, max = 100)` | q: { text, game, slots, section, gender, require, exclude, offset }.<br>Calls [`sona_catalogue_search`](../c/the-offline-catalogue.md#sona_catalogue_search). |
| `games()` | { name, items }, sorted by name.<br>Calls [`sona_catalogue_game_count`](../c/the-offline-catalogue.md#sona_catalogue_game_count), [`sona_catalogue_game`](../c/the-offline-catalogue.md#sona_catalogue_game). |
| `free()` | Frees it and every string it handed out.<br>Calls [`sona_catalogue_free`](../c/the-offline-catalogue.md#sona_catalogue_free). |

## Debug

`class Debug`: Debug helpers for tests: the core's counters and checks.

| Declaration | What it does |
|---|---|
| `decodeAsset(bytes, id)` | sona_decode_asset: { result, asset } with every array copied out. |
| `decodeClip(bytes, wantJoints)` | sona_decode_clip: { result, clip } where clip keeps its handle until clip.free. |

## Types

| Declaration | What it does |
|---|---|
| `class SonaCoreError extends Error` | What a call throws when it fails: code, name, message and fix. |
