@onda-lang/wasm-compiler 0.9.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/api.md CHANGED
@@ -2,48 +2,208 @@
2
2
 
3
3
  # Web API reference
4
4
 
5
- Onda publishes four ECMAScript-module packages for browsers and Node.js:
5
+ Use `@onda-lang/wasm-compiler` to compile Onda source in a browser or Node.js, and
6
+ `@onda-lang/webaudio` to play the result through an `AudioContext`.
6
7
 
7
- | Package | Purpose |
8
- | --- | --- |
9
- | `@onda-lang/wasm-compiler` | Compile Onda source, workspaces, and project images to complete WebAssembly processor artifacts. |
10
- | `@onda-lang/processor-abi` | Validate artifacts, inspect metadata, prepare parameter controls, and decode raw delegate and print output. |
11
- | `@onda-lang/binaryen-web` | Lower trusted, version-matched Onda MIR directly to a processor artifact. |
12
- | `@onda-lang/webaudio` | Host a complete processor artifact in an `AudioWorklet`. |
8
+ ```bash
9
+ npm install @onda-lang/wasm-compiler @onda-lang/webaudio
10
+ ```
13
11
 
14
- All packages are ESM-only. `@onda-lang/wasm-compiler` and `@onda-lang/binaryen-web` support modern
15
- browsers and Node.js 20 or newer. Web Audio construction requires a browser environment with
16
- `AudioWorklet`; the metadata and parameter helpers re-exported by `@onda-lang/webaudio` are ordinary
17
- synchronous JavaScript.
12
+ | Package | Use it to |
13
+ | --- | --- |
14
+ | `@onda-lang/wasm-compiler` | Compile source files or projects to WebAssembly processor artifacts. |
15
+ | `@onda-lang/webaudio` | Play an artifact, change parameters, send events, and save state. |
16
+ | `@onda-lang/processor-abi` | Validate artifacts, inspect metadata, and build a custom host. |
17
+ | `@onda-lang/binaryen-web` | Compile trusted Onda MIR when integrating a separate compiler frontend. |
18
18
 
19
- Each published package contains this reference as `api.md`. TypeScript declarations are included
20
- at every exported module path.
19
+ All packages use ECMAScript modules and include TypeScript declarations. The compiler packages
20
+ support modern browsers and Node.js 20 or newer. Playback requires a browser with `AudioWorklet`.
21
+ Each published package includes this reference as `api.md`.
21
22
 
22
23
  ## Compile source and start audio
23
24
 
25
+ Create a compiler once and reuse it. Worker mode keeps compilation off the browser's main thread.
26
+ Call `startAudio(source)` from a user action such as a Play button, passing the Onda source text:
27
+
24
28
  ```js
25
29
  import { createCompiler } from "@onda-lang/wasm-compiler";
26
- import {
27
- createOndaAudioProcessorInitialized,
28
- } from "@onda-lang/webaudio";
30
+ import { createOndaAudioProcessorInitialized } from "@onda-lang/webaudio";
31
+
32
+ const compiler = await createCompiler({ worker: true });
33
+
34
+ async function startAudio(source) {
35
+ const context = new AudioContext();
36
+ await context.resume();
37
+
38
+ const { artifact } = await compiler.compileSource(source, {
39
+ sampleRate: context.sampleRate,
40
+ blockSize: 512,
41
+ });
42
+ const processor = await createOndaAudioProcessorInitialized(context, artifact);
43
+ processor.node.connect(context.destination);
44
+ return { context, processor };
45
+ }
46
+ ```
47
+
48
+ Compile for the context's exact sample rate. The adapter rejects a mismatch, and the program must
49
+ have at least one audio input or output. The initialized factory resolves only after successful
50
+ initialization.
51
+
52
+ Keep the returned processor and context so you can release them when playback ends:
53
+
54
+ ```js
55
+ processor.close();
56
+ processor.node.disconnect();
57
+ await context.close();
58
+ ```
59
+
60
+ Call `await compiler.dispose()` when you no longer need compilation. Closing a processor rejects pending
61
+ requests and removes its listeners; it does not disconnect the caller-owned node or close the
62
+ context.
63
+
64
+ Your bundler must make the compiler worker and AudioWorklet modules available at runtime. Pass
65
+ `workerUrl` to `createCompiler` or `workletUrl` to the audio factory if your deployment serves them
66
+ from custom URLs. The [playground example](https://github.com/onda-lang/onda/tree/main/examples/web/onda_wasm_playground)
67
+ shows a complete browser integration.
29
68
 
30
- const compiler = await createCompiler();
31
- const { artifact } = await compiler.compileSource(source, {
32
- sampleRate: audioContext.sampleRate,
69
+ ## `@onda-lang/wasm-compiler`
70
+
71
+ ### `createCompiler(options?)`
72
+
73
+ Returns an `OndaCompilerInstance`. With no options, compilation runs on the calling JavaScript
74
+ thread. Pass `{ worker: true }` for a module worker. `workerUrl`, `frontendWasm`, and a custom
75
+ `Worker` constructor are available for custom loading environments.
76
+
77
+ | Task | Methods |
78
+ | --- | --- |
79
+ | Compile source | `compileSource(source, options?)`, `compileWorkspace(workspace, options?)` |
80
+ | Inspect compile-time settings | `inspectSourceConstants`, `inspectWorkspaceConstants`, `inspectProjectImageConstants` |
81
+ | Save or reopen portable projects | `createProjectImage`, `inspectProjectImage`, `loadProjectFiles`, `materializeProjectImage`, `compileProjectImage` |
82
+ | Read or write typed assets | `encodeBufferAsset`, `decodeBufferAsset`, `decodeBufferFile` |
83
+ | Query supported project formats | `projectCapabilities()` |
84
+ | Integrate language-server features | `sendLspMessage`, `setLspAnalysisOptions` |
85
+ | Release compiler resources | `dispose()` |
86
+
87
+ ### Multiple source files
88
+
89
+ Supply an entry path and a map of source filenames to text. Imports and includes resolve from this
90
+ map and the bundled standard library:
91
+
92
+ ```js
93
+ const result = await compiler.compileWorkspace({
94
+ entry: "main.onda",
95
+ sources: {
96
+ "main.onda": mainSource,
97
+ "dsp/filter.onda": filterSource,
98
+ },
99
+ }, {
100
+ sampleRate: 48000,
33
101
  blockSize: 512,
34
102
  });
103
+ ```
35
104
 
36
- const print = ({ text }) => console.debug(text);
37
- const processor = await createOndaAudioProcessorInitialized(
38
- audioContext,
39
- artifact,
40
- {
41
- params: { gain: 0.5 },
42
- // A construction-time listener also receives prints emitted by init.
43
- onPrint: print,
44
- },
45
- );
46
- processor.node.connect(audioContext.destination);
105
+ A successful result contains `artifact`, resolved `sourceFiles`, and `sourceGraph` when available.
106
+ Use the source graph with `createProjectImage` to save a portable project with its buffer assets.
107
+ See [Working with projects](https://onda-lang.org/docs/projects/) for the editable project format.
108
+
109
+ ### Compile options and diagnostics
110
+
111
+ `sampleRate` defaults to 48000 and `blockSize` to 512. `constants` supplies overrides for declared
112
+ compile-time settings. Values use booleans, numbers, `bigint` for `i64`, boolean arrays, and matching
113
+ numeric typed arrays.
114
+ Inspection methods return each constant's type, shape, and resolved value; enum descriptors also
115
+ include member names and labels.
116
+
117
+ A workspace may carry project defaults in `workspace.constants`, using the project file's JSON
118
+ representation, including decimal strings for `i64`. Explicit `options.constants` override these
119
+ defaults. Pass the workspace defaults to `createProjectImage` when exporting an edited project.
120
+
121
+ `codegen` controls optimization level (`optimizeLevel`, 0–4), size optimization (`shrinkLevel`, 0–2),
122
+ `fastMath`, `simd`, and optional WAT output (`emitText`). See
123
+ [the TypeScript declarations](https://github.com/onda-lang/onda/blob/main/packages/onda_wasm_compiler/src/index.d.ts)
124
+ for all options and method signatures.
125
+
126
+ Catch `OndaCompileError` for source and project compilation failures. Its `diagnostics` provide
127
+ messages and source locations. `sourceFiles` and `unresolvedSourceFiles` let editors retain file
128
+ watches while a program is invalid. `OndaCompilerError` reports compiler setup or lifecycle errors;
129
+ `OndaBinaryenError` reports a WebAssembly compilation failure.
130
+
131
+ The `/artifact` module path exposes artifact helpers without loading the compiler. The `/worker`
132
+ path is the worker's entry module and has no named exports.
133
+
134
+ ## `@onda-lang/webaudio`
135
+
136
+ ### Construction
137
+
138
+ Use `createOndaAudioProcessorInitialized(context, artifact, options?)` for immediate playback.
139
+ Use `createOndaAudioProcessor` when you need to change parameters before the first initialization,
140
+ then call `processor.init(ONDA_INIT_FULL)` explicitly. Until initialization succeeds, the processor
141
+ emits silence and rejects operations that require initialized state.
142
+
143
+ | Option | Purpose |
144
+ | --- | --- |
145
+ | `params` | Initial plain parameter values. Names must match the program. |
146
+ | `buffers` | Initial external-buffer bindings by name, array group, or slot order. |
147
+ | `paramSmoothingSeconds` | Optional host parameter ramps; defaults to `0`. |
148
+ | `eventPayloadCapacityBytes` | Reserved dynamic event capacity; defaults to 64 KiB. |
149
+ | `delegateCapacityBytes`, `printCapacityBytes` | Output collection capacities; each defaults to 64 KiB. Zero disables that stream. |
150
+ | `onPrint` | Initial print listener, including prints from initialization. |
151
+ | `compiledModule` | Reuse a module prepared with `compileOndaProcessorModule`. |
152
+ | `workletUrl` | Custom URL for the AudioWorklet module. |
153
+
154
+ The factory registers the worklet and prepares the WebAssembly module before playback. Advanced
155
+ hosts can use `registerOndaAudioWorklet`, `compileOndaProcessorModule`, and
156
+ `ondaAudioWorkletNodeOptions` separately. See
157
+ [the adapter declarations](https://github.com/onda-lang/onda/blob/main/packages/onda_webaudio/src/index.d.ts)
158
+ for custom node options and constructors.
159
+
160
+ ### Parameters
161
+
162
+ For a program with a `cutoff` parameter and an `offsets` array:
163
+
164
+ ```js
165
+ await processor.setParam("cutoff", 440);
166
+ await processor.setParamNormalized("cutoff", 0.5);
167
+ await processor.setParamElement("offsets", 1, 12);
168
+ await processor.resetParams();
169
+ ```
170
+
171
+ Plain writes use the parameter's declared units. Normalized writes use its range and scale, clamp
172
+ to the range, and snap stepped values. Whole arrays require an exact-length array. Indexed names
173
+ such as `offsets[1]` also work with `setParam` and `setParamNormalized`. Use
174
+ `setParamElementNormalized` for a normalized write to one array element.
175
+
176
+ `paramSmoothingSeconds` applies finite linear ramps to continuous floating-point parameters.
177
+ Integer, boolean, and stepped parameters update directly. Ramps update once per Onda compile block;
178
+ they do not interpolate inside individual samples. Durations at most one block are bypassed.
179
+ Change the duration live with `setParamSmoothingSeconds(seconds)`, using a finite, nonnegative value.
180
+ Initial parameters, reinitialization, and `resetParams()` settle immediately. Ramps are not saved
181
+ in processor snapshots.
182
+
183
+ ### Events and output
184
+
185
+ `trigger(nameOrIndex, values?)` accepts an array in declaration order or an object keyed by parameter
186
+ name. Structs are objects with their declared fields; tuples, fixed arrays, and slices are sequences.
187
+ For an event with a `note` argument containing `frequency` and `velocity`:
188
+
189
+ ```js
190
+ await processor.trigger("note_on", {
191
+ note: { frequency: 523.25, velocity: 0.7 },
192
+ });
193
+ ```
194
+
195
+ Missing event arguments use declared defaults. Fixed arrays must match their declared length.
196
+ Supply `i64` values as `bigint`, exact safe integers, or decimal strings. Unknown names and negative
197
+ indices are rejected; unknown nonnegative numeric indices are successful no-ops.
198
+
199
+ `onPrint`, `onDelegates`, and `onExecutionError` return unsubscribe functions. Register `onPrint`
200
+ in the factory options to include initialization output, or subscribe later for future calls:
201
+
202
+ ```js
203
+ const stopPrints = processor.onPrint(({ text, overflowCount, transportDropCount }) => {
204
+ console.debug(text);
205
+ if (overflowCount || transportDropCount) console.warn("Some output was dropped");
206
+ });
47
207
 
48
208
  const stopDelegates = processor.onDelegates(({ occurrences }) => {
49
209
  for (const occurrence of occurrences) {
@@ -52,281 +212,139 @@ const stopDelegates = processor.onDelegates(({ occurrences }) => {
52
212
  });
53
213
  ```
54
214
 
55
- Compilation is an offline operation and may allocate. Constructing the adapter compiles or accepts
56
- a reusable `WebAssembly.Module` before the audio node starts. Normal rendering uses preallocated
57
- storage. Delegate and print callbacks run on the main side after bounded worklet transport; they do
58
- not call JavaScript from generated DSP execution.
215
+ Print and delegate delivery requires cross-origin isolation and `SharedArrayBuffer`; ordinary audio
216
+ playback remains available without shared memory. Collection is active only while listeners are
217
+ registered and capacity is nonzero. `overflowCount` counts records dropped by the processor;
218
+ `transportDropCount` counts records lost during delivery to the main thread. A notification may
219
+ report loss without carrying any occurrences.
59
220
 
60
- ## `@onda-lang/wasm-compiler`
221
+ Both listener types run on the main thread in call-local sequence order. They do not run inside
222
+ DSP execution. Ordering starts again for each initialization, event, or process segment.
61
223
 
62
- ### `createCompiler(options?)`
224
+ ### State and errors
63
225
 
64
- Creates an `OndaCompilerInstance`. With no options, compilation runs directly on the calling
65
- JavaScript thread. Pass `{ worker: true }` to run the frontend and backend in a module worker;
66
- `workerUrl`, `frontendWasm`, and a custom `Worker` constructor are optional integration hooks.
67
-
68
- The returned instance provides:
69
-
70
- - `compileSource(source, options?)` and `inspectSourceConstants(source, options?)`.
71
- - `compileWorkspace(workspace, options?)` and `inspectWorkspaceConstants(workspace, options?)`.
72
- - `compileProjectImage(bytes, options?)` and `inspectProjectImageConstants(bytes, options?)`.
73
- - `createProjectImage(sourceGraph, buffers?, constants?)`, `inspectProjectImage(bytes)`,
74
- `loadProjectFiles(files, projectFilePath?)`, and `materializeProjectImage(bytes, names?)`.
75
- - `encodeBufferAsset(binding)`, `decodeBufferAsset(bytes)`, and `decodeBufferFile(bytes, path?)`.
76
- - `projectCapabilities()` for supported image, buffer, and standard-library versions.
77
- - `sendLspMessage(message)` and `setLspAnalysisOptions(options?)` for the embedded language server.
78
- - `dispose()`, an idempotent terminal release of compiler and worker resources.
79
-
80
- Enum configuration inspection returns optional `enumeration` metadata on `OndaCompileConstDescriptor`.
81
- Its `element` is `i32`; scalar values and `Int32Array` selections use ordinary integer configuration
82
- transport and are clamped to the member range during compilation.
83
-
84
- Compile options accept `sampleRate`, `blockSize`, typed compile-constant overrides, and `codegen`.
85
- Workspaces may carry `constants` in project-manifest form (numbers, booleans, decimal strings for
86
- `i64`, and primitive arrays). These are project defaults; explicit `options.constants` take
87
- precedence. Pass the same defaults to `createProjectImage` when exporting an edited workspace.
88
- The sample rate defaults to 48000 Hz and the block size to 512 frames.
89
- Code generation can select optimization level `0..4`, shrink level `0..2`, strict or fast math,
90
- SIMD, loop-containing inlining, and optional WAT emission. A successful compilation returns an
91
- `OndaCompilationResult` containing the artifact, resolved source paths, and the exact source graph
92
- when one is available.
93
-
94
- Configuration and lifecycle failures throw `OndaCompilerError`. Authored-source, project, MIR, and
95
- code-generation failures throw `OndaCompileError`, whose `diagnostics`, `sourceFiles`, and
96
- `unresolvedSourceFiles` fields support editors and file watchers. `OndaBinaryenError` identifies a
97
- failure in the MIR-to-Wasm backend.
98
-
99
- `MIR_SCHEMA_VERSION` is the schema accepted by the bundled backend. `ONDA_VERSION` is the compiler
100
- version. Artifacts are self-contained; instantiate them with an empty import object (`{}`).
101
-
102
- The `@onda-lang/wasm-compiler/artifact` subpath re-exports the complete
103
- `@onda-lang/processor-abi` surface without loading the compiler. The
104
- `@onda-lang/wasm-compiler/worker` subpath is a side-effect-only module-worker entry and has no
105
- named exports.
226
+ | Operation | Purpose |
227
+ | --- | --- |
228
+ | `init(ONDA_INIT_FULL)` | Clear and initialize all processor state. |
229
+ | `init(ONDA_INIT_PRESERVE_PINNED)` | Reinitialize while retaining pinned state. |
230
+ | `snapshot()`, `restoreSnapshot(bytes)` | Save and restore persistent state. Restore does not deliver initialization prints or delegates. |
231
+ | `readControlOutputs()` | Read held control-output values. |
232
+ | `readBuffer(nameOrIndex)` | Read buffer contents. |
233
+ | `close(reason?)` | Release adapter resources; subsequent operations fail. |
234
+
235
+ Catch rejected parameter, initialization, and event promises. `OndaRuntimeError` exposes an
236
+ `operation` and numeric `code` from `ONDA_RUNTIME_ERROR`. `OndaExecutionError` exposes an `operation`
237
+ and generated execution `status`:
238
+
239
+ | Status | Meaning |
240
+ | --- | --- |
241
+ | `PROCESSOR_EXECUTION_OK` (`0`) | Execution succeeded. |
242
+ | `PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE` (`1`) | State is invalidated; audio is silenced until full initialization or snapshot restoration succeeds. |
243
+ | `PROCESSOR_EXECUTION_INPUT_REJECTED` (`2`, events only) | The payload or workspace was rejected; state remains usable. |
244
+
245
+ Use `onExecutionError` for asynchronous processing failures. Initialization and event failures reject
246
+ their own promises and are not reported again to this listener. If the adapter closes, including
247
+ a terminal control-transport failure, create a new processor. Print/delegate overflow is reported
248
+ separately and does not by itself close the processor.
249
+
250
+ Web Audio adapts its callbacks to Onda's compiled block size; you do not need a segmented-process
251
+ method. Audio converts at Web Audio's `f32` boundary: integer inputs truncate and saturate (NaN
252
+ becomes zero), boolean inputs use nonzero comparison, and outputs convert to `f32`. Event and
253
+ delegate values retain their declared types and precision.
254
+
255
+ The `/worklet` module path registers the AudioWorklet processor and has no named exports.
106
256
 
107
257
  ## `@onda-lang/processor-abi`
108
258
 
109
- An `OndaProcessorArtifact` contains WebAssembly bytes, an `OndaProcessorMetadata` descriptor, and
110
- optional WAT. Treat the bytes and descriptor as one integrity-associated pair.
259
+ Use this package for artifact files, metadata-driven controls, or a custom WebAssembly host.
260
+ An `OndaProcessorArtifact` contains WebAssembly bytes, a metadata descriptor, and optional WAT.
261
+ Keep the bytes and descriptor together; they describe one exact compilation.
111
262
 
112
263
  ### Validation and files
113
264
 
114
- - `validateProcessorMetadata(metadata, expectedKind?)` validates and returns the current descriptor.
265
+ - `validateProcessorMetadata(metadata, expectedKind?)` checks a descriptor.
115
266
  - `validateProcessorArtifact(artifact, options?)` normalizes bytes and optionally inspects the module.
116
- - `validateProcessorModule(module, metadata)` verifies a precompiled module against its descriptor.
117
- - `parseProcessorMetadata(input, expectedKind?)` parses JSON or validates an object.
118
- - `serializeProcessorMetadata(metadata, space?)` validates before producing newline-terminated JSON.
119
- - `createProcessorArtifactFiles(artifact, options?)` creates associated `.wasm` and `.onda.json`
120
- records, including integrity metadata.
121
- - `loadProcessorArtifactFiles(wasm, metadata)` validates a loaded pair and its integrity association.
267
+ - `validateProcessorModule(module, metadata)` checks a precompiled module against its descriptor.
268
+ - `parseProcessorMetadata(input, expectedKind?)` accepts JSON or an object.
269
+ - `serializeProcessorMetadata(metadata, space?)` validates and produces JSON.
270
+ - `createProcessorArtifactFiles(artifact, options?)` creates matching `.wasm` and `.onda.json` records.
271
+ - `loadProcessorArtifactFiles(wasmBytes, metadataJson)` verifies and loads a saved pair.
122
272
 
123
- Failures throw `OndaArtifactError`. Hosts must reject unsupported artifact-format, ABI, and snapshot
124
- versions rather than guessing layout compatibility.
273
+ Failures throw `OndaArtifactError`. Complete modules have no imports and can be instantiated with
274
+ `WebAssembly.instantiate(artifact.wasm, {})`. Direct hosts must allocate storage and drive the
275
+ [Processor API](https://onda-lang.org/docs/processor-api/); the Web Audio adapter does this for you.
125
276
 
126
277
  ### Parameter controls
127
278
 
128
- `createParamControl(metadata)` validates one scalar parameter descriptor and returns a reusable
129
- `OndaPreparedParamControl`. For an array, `createParamControl(metadata, index)` prepares one element;
130
- `paramElementMetadata(metadata, index)` projects its scalar descriptor, default, and storage offset.
131
- The Web Audio adapter exposes `setParamElement(nameOrIndex, element, value)` and
132
- `setParamElementNormalized(nameOrIndex, element, normalized)` for individual scalar or fixed-array
133
- elements. Indexed names such as `offsets[1]` remain accepted by `setParam` and
134
- `setParamNormalized`; exact-length arrays use `setParam("offsets", values)`.
135
- `createParamDomain(domain)` does the same from already-decoded values.
136
- Prepared controls expose `constrainPlain`, `normalizedToPlain`, and `plainToNormalized` methods.
137
-
138
- The one-shot `constrainParamPlain`, `paramNormalizedToPlain`, and `paramPlainToNormalized`
139
- functions provide the same behavior. Preparing once is preferable for frequently updated UI:
140
- validation and decimal descriptor decoding stay off the interaction path. Mappings preserve exact
141
- endpoints, apply linear, logarithmic, or curved scale, and clamp and snap to the declared grid.
142
-
143
- ### Delegates and print output
144
-
145
- See the [host output guide](https://onda-lang.org/docs/host-output/#javascript-and-web-audio)
146
- for batch sizing, decoding, formatting, and Web Audio listener examples.
147
-
148
- Complete wasm32 processor exports receive an optional execution-output descriptor containing
149
- independently nullable delegate and print batches. Allocate all descriptors and storage before
150
- real-time execution. Their linear-memory regions must be mutually disjoint and must not overlap any
151
- other region accessed by the processor call, matching the processor ABI's execution-output
152
- contract.
153
-
154
- `writeDelegateBatch` and `writePrintBatch` initialize reusable batch descriptors.
155
- `writeExecutionOutput` connects their addresses. Call `resetExecutionOutput` immediately before
156
- every generated init or process entry. Generated event entries reset before input preflight, so
157
- rejected input returns empty batches. After a successful generated call,
158
- `readDelegateBatch` or `readPrintBatch` validates the result counters.
159
- `decodeDelegateBatch` validates and decodes a complete delegate batch in one call;
160
- `decodeDelegateRecords` decodes an already-isolated storage region using `metadata.delegates`.
161
- `decodePrintRecords` preserves primitive types and source sites; `formatPrintRecords` and
162
- `formatPrintBatch` add canonical text formatting. Both decoded record types expose a `sequence` from
163
- the host-reset call-local counter; merge that call's two arrays by this field when presenting one
164
- chronological output stream.
165
-
166
- Batch capacity is host policy. `overflowCount` reports whole records that did not fit; it is not a
167
- byte count. Consume the returned storage before reusing it for another init, process, or event call.
168
- See the [language guide](https://onda-lang.org/docs/language/#delegates-and-when) for authored semantics and
169
- the [processor API](https://onda-lang.org/docs/processor-api/#call-scoped-execution-output) for
170
- physical record layout.
171
-
172
- The metadata interfaces expose target facts, storage sizes, ports, parameters, states, events,
173
- delegates, print sites, buffers, and integration profiles. Scalar `i64` values decoded from records
174
- use `bigint`; booleans use `boolean`; fixed arrays and slices become JavaScript arrays.
279
+ Prepare a control with `createParamControl(metadata, elementIndex?)` for repeated conversion, or
280
+ use `paramNormalizedToPlain`, `paramPlainToNormalized`, and `constrainParamPlain` for individual
281
+ values. Prepared controls expose `constrainPlain`, `normalizedToPlain`, and `plainToNormalized`.
282
+ `paramElementMetadata` selects one array element; `createParamDomain` accepts already decoded
283
+ values.
175
284
 
176
- ## `@onda-lang/binaryen-web`
285
+ Conversions preserve endpoints, clamp ranges, and snap steps. Booleans use a `0.5` threshold;
286
+ unranged numbers have no normalized control domain. Full-width `i64` values use `bigint` for direct
287
+ writes. Numeric host controls are limited to exactly representable binary64 integer domains.
288
+ These helpers are also re-exported by `@onda-lang/webaudio`.
177
289
 
178
- ### `compileTrustedMir(mir, options?)`
290
+ ### Structured event and delegate values
179
291
 
180
- Lowers MIR emitted by the matching Onda semantic frontend. Input may be compact MessagePack, JSON,
181
- or an already-decoded object. The function is synchronous and returns an
182
- `OndaProcessorArtifact`. It is intentionally not a validator for untrusted or hand-authored MIR;
183
- the producer owns semantic, type, bounds, and resource proofs.
292
+ `PayloadPlan` prepares a message schema for encoding and decoding. `encode(values)` accepts named
293
+ objects or positional arrays; `decode(bytes)` returns named values with `bigint` for `i64`.
294
+ Structs must contain exactly their declared fields; unknown names and extra positional values are
295
+ rejected. Missing event arguments use declared defaults.
184
296
 
185
- `OndaBinaryenOptions` controls the same backend policies exposed through compiler `codegen`.
186
- `SUPPORTED_MIR_SCHEMA_VERSION` identifies the required producer schema. Instantiate self-contained
187
- artifacts with `{}` imports. Backend failures throw
188
- `OndaBinaryenError`.
297
+ `tensorMetadata` describes each primitive leaf's path, encoding, fixed shape, owning parameter,
298
+ slice status, and fixed element count. For a slice, multiply its logical length by
299
+ `fixedElementCount` to obtain the tensor length. Tuple path components use `__0`, `__1`, and so on.
189
300
 
190
- The package root re-exports the common artifact validation and file helpers. The
191
- `@onda-lang/binaryen-web/artifact` subpath re-exports the complete
192
- `@onda-lang/processor-abi` module without loading Binaryen.
301
+ For direct Wasm calls, use `sizes(lengths)` or `requiredWorkspace(bytes)` to provision packed input
302
+ and aligned workspace, then `writeEventInput` to write the required 16-byte event descriptor.
303
+ `OndaAudioProcessor.trigger` performs this preparation for ordinary browser hosts.
193
304
 
194
- ## `@onda-lang/webaudio`
305
+ Decoded `f32` values use `canonicalF32Number` to return the shortest decimal representation that
306
+ round-trips to the same `f32` value.
195
307
 
196
- Audio ports retain their declared scalar types in Wasm. At the Web Audio `f32`
197
- boundary, integer inputs truncate toward zero and saturate (NaN becomes zero),
198
- and boolean inputs use nonzero comparison, including NaN. Outputs convert
199
- numerically to `f32`; booleans become zero or one. Event/delegate payloads retain
200
- their schema-defined types and precision independently of audio conversion.
308
+ ### Raw delegate and print batches
201
309
 
202
- ### Construction
310
+ Direct hosts use `writeDelegateBatch`, `writePrintBatch`, and `writeExecutionOutput` to prepare
311
+ caller-owned collection storage. Reset it with `resetExecutionOutput` before each init or process
312
+ call; event entries reset it before input validation. Storage must be disjoint from other memory
313
+ accessed by the call and remain valid until records have been consumed.
314
+
315
+ `readDelegateBatch` and `readPrintBatch` validate result counters. `decodeDelegateBatch` decodes a
316
+ complete delegate batch; `decodeDelegateRecords` handles an isolated storage region.
317
+ `decodePrintRecords` retains typed values and source sites. `formatPrintRecords` and
318
+ `formatPrintBatch` produce text. Merge print and delegate records by `sequence` when presenting
319
+ one call's output; `overflowCount` counts whole records that did not fit.
320
+
321
+ See the [processor output layout](https://onda-lang.org/docs/processor-api/#call-scoped-execution-output)
322
+ for storage requirements and the
323
+ [repository integration guide](https://github.com/onda-lang/onda/blob/main/docs/host-output.md#javascript-and-web-audio)
324
+ for complete collection examples.
203
325
 
204
- - `registerOndaAudioWorklet(context, workletUrl?)` registers the processor once per context.
205
- - `compileOndaProcessorModule(artifact)` validates and compiles a reusable module off the render thread.
206
- - `ondaAudioWorkletNodeOptions(artifact, options?)` builds low-level node options.
207
- - `createOndaAudioProcessor(context, artifact, options?)` allocates an uninitialized adapter.
208
- - `createOndaAudioProcessorInitialized(context, artifact, options?)` allocates it, requests full
209
- initialization through the status-bearing control protocol, and resolves only on success.
210
- - `flattenedAudioChannelCount(ports?)` totals declared physical channels with validation.
211
-
212
- `OndaAudioProcessorOptions` accepts initial plain parameter values, external buffers, event,
213
- delegate, and print capacities, an optional construction-time `onPrint` listener, a precompiled
214
- module, custom node options, and an `AudioWorkletNode` constructor. Pass `onPrint` when using the
215
- initialized factory if initialization output must be observed; registering a listener after
216
- construction cannot replay output from an execution that has already completed. The artifact sample
217
- rate must equal the context sample rate and it must expose at least one audio input or output.
218
- Print and delegate delivery uses a bounded `SharedArrayBuffer` ring and requires cross-origin
219
- isolation in browsers; ordinary audio processing remains available when shared memory is absent.
220
- Low-level callers that manually pair the returned node options with `OndaAudioProcessor` must pass
221
- the artifact metadata as the adapter constructor's second argument and
222
- `processorOptions.executionOutputRing` as its fourth argument and
223
- `processorOptions.executionStatusRing` as its fifth argument. Event encoding and numeric
224
- unknown-index classification require that metadata.
225
-
226
- `paramSmoothingSeconds` is an optional **host** setting on `OndaAudioProcessorOptions`, defaulting
227
- to `0`. It applies finite linear ramps to continuous floating-point parameters and array elements;
228
- integer, boolean, and stepped parameters update directly. Ramps publish once per logical compile
229
- block, independent of Web Audio callback sizes. Durations round up to host samples and are bypassed
230
- when they fit within one block. A changed target starts a fresh ramp from the published value;
231
- repeated writes of the same target keep its deadline. Initial values and reinitialization settle
232
- immediately, and processor snapshots do not contain the host ramps. The browser playground opts
233
- into `0.03` seconds (30 ms). These block-level updates do not interpolate inside `sample:`.
234
-
235
- ### `OndaAudioProcessor`
236
-
237
- The adapter exposes its `node` and validated `metadata`, plus these operations:
238
-
239
- - `setParam(nameOrIndex, plain)` and `setParamNormalized(nameOrIndex, normalized)` for whole
240
- parameters.
241
- - `resetParams()` to restore parameter defaults immediately and cancel host ramps, retaining DSP state.
242
- - `setParamSmoothingSeconds(seconds)` to change the host duration live without recompiling or
243
- reinitializing DSP state. Finite, nonnegative durations are required. Active ramps restart from
244
- their current values using the new duration; 0 (or a duration at most one block) settles their
245
- targets immediately. Smoothing can be enabled after starting with 0.
246
- - `setParamElement(nameOrIndex, element, plain)` and
247
- `setParamElementNormalized(nameOrIndex, element, normalized)` for one scalar or fixed-array
248
- element.
249
- - `trigger(nameOrIndex, values?)` for input events. Unknown nonnegative numeric indices are
250
- successful no-ops, matching native dispatch; unknown names and negative indices are rejected.
251
- - `onExecutionError(listener)`, `onDelegates(listener)`, and `onPrint(listener)`, each returning an
252
- unsubscribe function.
253
- - `init(mode)`, `snapshot()`, and `restoreSnapshot(bytes)`.
254
- - `readControlOutputs()` and `readBuffer(nameOrIndex)`.
255
- - `request(type, fields?, transfer?)` for adapter protocol extensions.
256
- - `close(reason?)`, an idempotent terminal release of adapter-side resources.
257
-
258
- Delegate and print batches report `overflowCount` for generated-storage loss and
259
- `transportDropCount` for bounded worklet-to-main queue loss. Loss-only notifications can arrive
260
- without occurrences. Collection is enabled only while the corresponding listener set is nonempty;
261
- setting the capacity to zero disables host delivery even with listeners while preserving language
262
- evaluation semantics.
263
-
264
- With both listener types active, the adapter invokes them in call-local sequence order and may split
265
- a same-stream batch around an intervening occurrence from the other stream. Ordering resets for
266
- each init, event, or process segment.
267
-
268
- `ONDA_INIT_FULL` clears and initializes all physical state. `ONDA_INIT_PRESERVE_PINNED` retains
269
- pinned state according to the processor ABI. The package also re-exports the prepared and one-shot
270
- parameter conversion helpers. Snapshot restoration performs its internal full initialization
271
- silently, without delivering init prints or delegates.
272
-
273
- Raw WebAssembly exports use the same generated status values as native processor objects:
274
- `PROCESSOR_EXECUTION_OK` (`0`), `PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE` (`1`), and event-only
275
- `PROCESSOR_EXECUTION_INPUT_REJECTED` (`2`). The Web Audio adapter translates host-side validation
276
- problems into rejected promises before generated execution. It also rejects init and event promises
277
- when generated code returns a nonzero status: status `1` invalidates the live processor, while event
278
- status `2` preserves it. These generated failures use `OndaExecutionError`, whose `operation` and
279
- `status` fields retain the machine-readable failure. The Web Audio root re-exports all three
280
- `PROCESSOR_EXECUTION_*` constants for direct comparison. Render-time process failure invalidates the
281
- processor and silences subsequent callbacks. `onExecutionError(listener)` receives its typed
282
- `OndaExecutionError`; requested init and event failures remain on their promise rejection path and
283
- are not reported twice.
284
- Worklet validation failures use `OndaRuntimeError` with a numeric `code` from `ONDA_RUNTIME_ERROR`
285
- and an `operation`. Rejected input leaves the instance usable; invalid output/storage and unexpected
286
- execution failures invalidate it and silence subsequent callbacks until full initialization or
287
- snapshot restoration succeeds. Unexpected engine exceptions also follow this recovery path.
288
- Compiler diagnostics remain unchanged.
289
-
290
- The worklet reports generated failures and host validation failures as numeric statuses, without
291
- constructing errors or formatting text. A separate bounded shared-memory status ring carries
292
- execution failures and command acknowledgements independently of the lossy print/delegate ring.
293
- The adapter drains diagnostics before reporting a status, constructs errors on the main thread,
294
- and bounds in-flight control requests to reserve capacity for replies and render failures.
295
- Without `Atomics.waitAsync`, control replies wake the adapter through the port instead of waiting
296
- for a polling interval; asynchronous render failures are polled. Transport overflow is terminal:
297
- processing stops, the adapter closes, and every pending or queued request rejects. Recreate the
298
- processor after this error. Status monitoring remains active without print/delegate listeners.
299
-
300
- Without shared memory, the same numeric protocol uses a reused MessagePort packet; browser
301
- structured cloning can allocate. This is not a blanket JavaScript allocation-free guarantee:
302
- incoming control messages, control wakeups without `Atomics.waitAsync`, BigInt conversion,
303
- snapshots, buffer/control-output reads, and engine
304
- exceptions can allocate. The normal f32 rendering and shared-memory status publication paths use
305
- prepared storage. Public promises and `onExecutionError` continue delivering errors on the main
306
- thread; requested failures are not also sent to that listener.
307
-
308
- The browser API exposes no thread FP-mode setter. WebAssembly uses the engine's specified
309
- [floating-point semantics](https://webassembly.github.io/spec/core/exec/numerics.html#floating-point-operations),
310
- including subnormal arithmetic; native x86 FTZ/DAZ setup does not apply to browser execution.
311
-
312
- The raw `@onda-lang/processor-abi` package exposes `PROCESSOR_BEGIN_BLOCK`,
313
- `PROCESSOR_END_BLOCK`, and `PROCESSOR_FULL_BLOCK` for native and direct WebAssembly hosts that use
314
- segmented processing. Web Audio schedules render quanta internally and has no segmented-process
315
- method.
316
-
317
- `@onda-lang/webaudio/worklet` is the side-effect-only AudioWorklet registration module and has no
318
- named exports.
319
-
320
- ## Complete exported surface
321
-
322
- The following indexes include runtime values and TypeScript-only types from each package root.
323
- They are checked against the shipped declarations so additions cannot silently escape this
324
- reference. Artifact subpaths are complete processor-ABI re-exports; worker and worklet subpaths are
325
- side-effect-only as described above.
326
-
327
- ### `@onda-lang/processor-abi`
326
+ ## `@onda-lang/binaryen-web`
327
+
328
+ Use `compileTrustedMir(mir, options?)` only when supplying MIR from a matching Onda frontend. For
329
+ source text, use `@onda-lang/wasm-compiler` instead. MIR input may be MessagePack, JSON, or an
330
+ already decoded object; this synchronous function returns an `OndaProcessorArtifact`. It does not
331
+ validate untrusted or hand-authored MIR.
332
+
333
+ `SUPPORTED_MIR_SCHEMA_VERSION` identifies the required input version. `OndaBinaryenOptions`
334
+ controls optimization, fast math, SIMD, and optional WAT. Failures throw `OndaBinaryenError`.
335
+ The `/artifact` module path exposes artifact helpers without loading Binaryen.
336
+
337
+ ## Export indexes
338
+
339
+ Expand a package's index to look up runtime exports and TypeScript types. Exact signatures are
340
+ included in each installed package's declarations.
341
+
342
+ <details markdown="1">
343
+ <summary>@onda-lang/processor-abi exports</summary>
328
344
 
329
345
  <!-- BEGIN WEB API onda_processor_abi -->
346
+
347
+ ```text
330
348
  DELEGATE_BATCH_SIZE_BYTES
331
349
  DELEGATE_RECORD_HEADER_SIZE_BYTES
332
350
  EXECUTION_OUTPUT_SIZE_BYTES
@@ -404,11 +422,18 @@ canonicalF32Number
404
422
  EVENT_INPUT_SIZE_BYTES
405
423
  PROCESSOR_EXECUTION_INPUT_REJECTED
406
424
  writeEventInput
425
+ ```
426
+
407
427
  <!-- END WEB API onda_processor_abi -->
408
428
 
409
- ### `@onda-lang/binaryen-web`
429
+ </details>
430
+
431
+ <details markdown="1">
432
+ <summary>@onda-lang/binaryen-web exports</summary>
410
433
 
411
434
  <!-- BEGIN WEB API onda_binaryen_web -->
435
+
436
+ ```text
412
437
  OndaArtifactError
413
438
  OndaBinaryenError
414
439
  OndaBinaryenOptions
@@ -436,11 +461,18 @@ serializeProcessorMetadata
436
461
  validateProcessorArtifact
437
462
  validateProcessorMetadata
438
463
  validateProcessorModule
464
+ ```
465
+
439
466
  <!-- END WEB API onda_binaryen_web -->
440
467
 
441
- ### `@onda-lang/wasm-compiler`
468
+ </details>
469
+
470
+ <details markdown="1">
471
+ <summary>@onda-lang/wasm-compiler exports</summary>
442
472
 
443
473
  <!-- BEGIN WEB API onda_wasm_compiler -->
474
+
475
+ ```text
444
476
  DirectCompilerOptions
445
477
  MIR_SCHEMA_VERSION
446
478
  ONDA_VERSION
@@ -502,11 +534,18 @@ serializeProcessorMetadata
502
534
  validateProcessorArtifact
503
535
  validateProcessorMetadata
504
536
  validateProcessorModule
537
+ ```
538
+
505
539
  <!-- END WEB API onda_wasm_compiler -->
506
540
 
507
- ### `@onda-lang/webaudio`
541
+ </details>
542
+
543
+ <details markdown="1">
544
+ <summary>@onda-lang/webaudio exports</summary>
508
545
 
509
546
  <!-- BEGIN WEB API onda_webaudio -->
547
+
548
+ ```text
510
549
  ONDA_AUDIO_WORKLET_PROCESSOR_NAME
511
550
  ONDA_INIT_FULL
512
551
  ONDA_INIT_PRESERVE_PINNED
@@ -537,32 +576,8 @@ ondaAudioWorkletNodeOptions
537
576
  paramNormalizedToPlain
538
577
  paramPlainToNormalized
539
578
  registerOndaAudioWorklet
540
- <!-- END WEB API onda_webaudio -->
579
+ ```
541
580
 
542
- ### Structured event and delegate values
581
+ <!-- END WEB API onda_webaudio -->
543
582
 
544
- `PayloadPlan` prepares a recursive message schema once. `encode(values)` accepts ordered parameter
545
- arrays or objects keyed by parameter name; structs are objects containing exactly their declared
546
- own fields, and arrays/tuples are sequences. Unknown named parameters and excess positional values
547
- are rejected. Missing event arguments use declared constant defaults.
548
- Supply `i64` as `bigint`, an exact safe integer, or a decimal string. `decode(bytes)` returns named
549
- nested values with `bigint` for `i64`. Plans own immutable schema snapshots.
550
-
551
- `tensorMetadata` exposes the schema's flattened SoA contract without reparsing JSON. Each immutable
552
- record contains `path`, `encoding`, fixed `shape`, `parameterIndex`, `isSlice`, and
553
- `fixedElementCount`. Tuple path components use `__0`, `__1`, and so on. A slice's runtime tensor
554
- length is its logical length times `fixedElementCount`; the dynamic outer axis is therefore not
555
- repeated in `shape`.
556
-
557
- `requiredWorkspace(bytes)` preflights packed little-endian input. `sizes(lengths)` reports wire
558
- and aligned workspace sizes without allocating payload storage. Low-level wasm hosts provision
559
- both regions and a 16-byte descriptor, then call `writeEventInput` before invoking the event.
560
- Rejected input returns `PROCESSOR_EXECUTION_INPUT_REJECTED` (2) and leaves processor state usable.
561
- `OndaAudioProcessor.trigger` performs logical encoding before transferring bytes to the worklet.
562
- Web hosts intentionally have no unchecked tensor-view event entry: JavaScript values must cross the
563
- main-thread/worklet and Wasm linear-memory boundaries, so native borrowed addresses cannot be
564
- preserved end to end. Web event dispatch remains the packed, checked `onda_event_N` path and uses
565
- its preallocated workspace.
566
- Decoded `f32` leaves use `canonicalF32Number(value)`: the returned JavaScript number has the
567
- shortest decimal representation that round-trips to the same `f32`, so JSON and controls do not
568
- expose an irrelevant widened binary tail.
583
+ </details>