@onda-lang/processor-abi 0.8.2 → 0.8.4

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/README.md CHANGED
@@ -27,6 +27,48 @@ validate artifacts without installing the compiler or duplicating the ABI schema
27
27
  The detailed TypeScript records mirror `onda_processor_abi::ProcessorDescriptor`; both packages
28
28
  validate the same checked-in conformance fixture.
29
29
 
30
+ ## Structured event payloads
31
+
32
+ Every event and delegate descriptor carries a recursive `schema`. `PayloadPlan` validates that
33
+ schema once and encodes or decodes logical values without exposing the flattened executable
34
+ parameters. Top-level parameters may be supplied by position or name; nominal structs are objects
35
+ with exactly their declared fields, and tuples, fixed arrays, and slices are sequences. An omitted
36
+ top-level parameter is legal only when its schema declares a default.
37
+
38
+ ```js
39
+ import {
40
+ PayloadPlan,
41
+ writeEventInput,
42
+ } from "@onda-lang/processor-abi";
43
+
44
+ const event = artifact.metadata.metadata.events.find(({ name }) => name === "note_on");
45
+ const plan = new PayloadPlan(event.schema);
46
+ const payload = plan.encode({
47
+ note: { frequency: 440, velocity: 0.8 },
48
+ });
49
+ const workspaceBytes = plan.requiredWorkspace(payload);
50
+
51
+ // Addresses come from the host's wasm32 linear-memory allocator. Workspace must be 8-byte aligned.
52
+ new Uint8Array(memory.buffer, payloadAddress, payload.byteLength).set(payload);
53
+ writeEventInput(
54
+ memory,
55
+ inputAddress,
56
+ payloadAddress,
57
+ payload.byteLength,
58
+ workspaceAddress,
59
+ workspaceBytes,
60
+ );
61
+ // Pass inputAddress as the first argument to instance.exports[event.export](...).
62
+ ```
63
+
64
+ Wire payloads are packed little-endian in canonical structure-of-arrays leaf order. Use
65
+ `sizes(lengths)` when only dynamic slice lengths are known, or `requiredWorkspace(payload)` to
66
+ preflight encoded bytes. Allocate payload, workspace, and the 16-byte `EventInput` descriptor before
67
+ realtime dispatch, and keep their memory regions disjoint from one another and processor storage.
68
+ `PayloadPlan.encode()` itself allocates and therefore belongs on a host/control thread, as does
69
+ decoding published delegate records. An event result of `PROCESSOR_EXECUTION_INPUT_REJECTED` (`2`)
70
+ means preflight failed without handler or output mutation.
71
+
30
72
  ## Delegate batches
31
73
 
32
74
  The package exports `DELEGATE_RECORD_HEADER_SIZE_BYTES`, `DELEGATE_BATCH_SIZE_BYTES`,
@@ -55,8 +97,9 @@ const fixedRecordBytes = delegates.map((delegate) =>
55
97
 
56
98
  writeDelegateBatch(memory, batchAddress, storageAddress, capacityBytes);
57
99
  writeExecutionOutput(memory, outputAddress, batchAddress, 0);
100
+ // Before onda_process (or initialization):
58
101
  resetExecutionOutput(memory, outputAddress);
59
- // Pass outputAddress as the final onda_process or onda_event_N argument.
102
+ // Pass outputAddress as the final entry argument. onda_event_N resets it itself after preflight.
60
103
  const batch = readDelegateBatch(memory, batchAddress);
61
104
  const storage = new Uint8Array(memory.buffer, storageAddress, batch.usedBytes);
62
105
  const occurrences = decodeDelegateRecords(
@@ -93,7 +136,9 @@ they are valid bindings, not an incomplete artifact.
93
136
  `constrainPlain()`, `normalizedToPlain()`, and `plainToNormalized()` methods. It preserves exact
94
137
  endpoints, clamps out-of-range values, applies linear, logarithmic, or SuperCollider-style curved
95
138
  mapping, and snaps stepped domains. The package also exports one-shot functions with the same
96
- behavior. Numeric parameters without a control domain and parameter arrays are rejected. These
139
+ behavior. Use `createParamControl(param, index)` for an array element or
140
+ `paramElementMetadata(param, index)` to obtain its scalar descriptor. Numeric parameters without
141
+ a control domain are rejected. These
97
142
  APIs are synchronous and do not require a compiler, WebAssembly instance, or `AudioWorklet`, so
98
143
  editors can prepare controls once and use them responsively.
99
144
  Boolean plain and normalized numeric inputs use the same `value >= 0.5` threshold as the native
package/api.md CHANGED
@@ -119,7 +119,11 @@ versions rather than guessing layout compatibility.
119
119
  ### Parameter controls
120
120
 
121
121
  `createParamControl(metadata)` validates one scalar parameter descriptor and returns a reusable
122
- `OndaPreparedParamControl`. `createParamDomain(domain)` does the same from already-decoded values.
122
+ `OndaPreparedParamControl`. For an array, `createParamControl(metadata, index)` prepares one element;
123
+ `paramElementMetadata(metadata, index)` projects its scalar descriptor, default, and storage offset.
124
+ The Web Audio adapter accepts indexed names such as `offsets[1]` in `setParam` and
125
+ `setParamNormalized`, and exact-length arrays in `setParam("offsets", values)`.
126
+ `createParamDomain(domain)` does the same from already-decoded values.
123
127
  Prepared controls expose `constrainPlain`, `normalizedToPlain`, and `plainToNormalized` methods.
124
128
 
125
129
  The one-shot `constrainParamPlain`, `paramNormalizedToPlain`, and `paramPlainToNormalized`
@@ -135,7 +139,8 @@ real-time execution.
135
139
 
136
140
  `writeDelegateBatch` and `writePrintBatch` initialize reusable batch descriptors.
137
141
  `writeExecutionOutput` connects their addresses. Call `resetExecutionOutput` immediately before
138
- every generated init, process, or event entry. After a successful generated call,
142
+ every generated init or process entry. Generated event entries reset after successful input
143
+ preflight instead, so rejected input preserves existing records. After a successful generated call,
139
144
  `readDelegateBatch` or `readPrintBatch` validates the result counters.
140
145
  `decodeDelegateRecords` converts delegate payloads using `metadata.delegates`.
141
146
  `decodePrintRecords` preserves primitive types and source sites; `formatPrintRecords` and
@@ -271,6 +276,7 @@ PROCESSOR_INIT_PRESERVE_PINNED
271
276
  PROCESSOR_SNAPSHOT_FORMAT_VERSION
272
277
  constrainParamPlain
273
278
  createParamControl
279
+ paramElementMetadata
274
280
  createParamDomain
275
281
  createProcessorArtifactFiles
276
282
  decodeDelegateRecords
@@ -291,6 +297,17 @@ validateProcessorModule
291
297
  writeDelegateBatch
292
298
  writeExecutionOutput
293
299
  writePrintBatch
300
+ OndaPayloadType
301
+ OndaPayloadField
302
+ OndaPayloadSchema
303
+ OndaPayloadDefault
304
+ OndaPayloadValue
305
+ OndaPayloadSizes
306
+ PayloadPlan
307
+ canonicalF32Number
308
+ EVENT_INPUT_SIZE_BYTES
309
+ PROCESSOR_EXECUTION_INPUT_REJECTED
310
+ writeEventInput
294
311
  <!-- END WEB API onda_processor_abi -->
295
312
 
296
313
  ### `@onda-lang/binaryen-web`
@@ -405,3 +422,21 @@ paramNormalizedToPlain
405
422
  paramPlainToNormalized
406
423
  registerOndaAudioWorklet
407
424
  <!-- END WEB API onda_webaudio -->
425
+
426
+ ### Structured event and delegate values
427
+
428
+ `PayloadPlan` prepares a recursive message schema once. `encode(values)` accepts ordered parameter
429
+ arrays or objects keyed by parameter name; structs are objects containing exactly their declared
430
+ own fields, and arrays/tuples are sequences. Unknown named parameters and excess positional values
431
+ are rejected. Missing event arguments use declared constant defaults.
432
+ Supply `i64` as `bigint`, an exact safe integer, or a decimal string. `decode(bytes)` returns named
433
+ nested values with `bigint` for `i64`. Plans own immutable schema snapshots.
434
+
435
+ `requiredWorkspace(bytes)` preflights packed little-endian input. `sizes(lengths)` reports wire
436
+ and aligned workspace sizes without allocating payload storage. Low-level wasm hosts provision
437
+ both regions and a 16-byte descriptor, then call `writeEventInput` before invoking the event.
438
+ Rejected input returns `PROCESSOR_EXECUTION_INPUT_REJECTED` (2) and leaves processor state usable.
439
+ `OndaAudioProcessor.trigger` performs logical encoding before transferring bytes to the worklet.
440
+ Decoded `f32` leaves use `canonicalF32Number(value)`: the returned JavaScript number has the
441
+ shortest decimal representation that round-trips to the same `f32`, so JSON and controls do not
442
+ expose an irrelevant widened binary tail.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onda-lang/processor-abi",
3
- "version": "0.8.2",
3
+ "version": "0.8.4",
4
4
  "type": "module",
5
5
  "description": "Shared Onda processor artifact schema, validation, and integrity helpers",
6
6
  "license": "MIT",
package/src/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export const PROCESSOR_ARTIFACT_FORMAT: "onda-processor";
2
2
  // Synchronized from format-versions.json; do not edit these copies directly.
3
- export const PROCESSOR_ARTIFACT_FORMAT_VERSION: 5;
4
- export const PROCESSOR_ABI_VERSION: 5;
3
+ export const PROCESSOR_ARTIFACT_FORMAT_VERSION: 6;
4
+ export const PROCESSOR_ABI_VERSION: 6;
5
5
  export const PROCESSOR_EXECUTION_OK: 0;
6
6
  export const PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE: 1;
7
7
  export const PROCESSOR_INIT_PRESERVE_PINNED: 0;
@@ -19,6 +19,9 @@ export const PRINT_BATCH_SIZE_BYTES: 20;
19
19
  /** wasm32 byte size of the call-scoped execution-output descriptor. */
20
20
  export const EXECUTION_OUTPUT_SIZE_BYTES: 12;
21
21
 
22
+ /** Returns the shortest host number that round-trips to the same f32. */
23
+ export function canonicalF32Number(value: number): number;
24
+
22
25
  export type OndaScalarType = "f32" | "f64" | "i32" | "i64" | "bool";
23
26
  export type OndaArtifactKind = "webassembly_module" | "relocatable_object";
24
27
 
@@ -108,7 +111,10 @@ export interface OndaParamDomain {
108
111
  export function createParamDomain(domain: OndaParamDomain): OndaPreparedParamControl;
109
112
 
110
113
  /** Validate and decode descriptor metadata once for repeated host-control use. */
111
- export function createParamControl(param: OndaIoMetadata): OndaPreparedParamControl;
114
+ export function createParamControl(param: OndaIoMetadata, element?: number): OndaPreparedParamControl;
115
+
116
+ /** Project one array element to scalar metadata, including its default and storage offset. */
117
+ export function paramElementMetadata(param: OndaIoMetadata, element: number): OndaIoMetadata;
112
118
 
113
119
  /** Clamp and snap a plain scalar value according to descriptor metadata. */
114
120
  export function constrainParamPlain(
@@ -147,6 +153,42 @@ export interface OndaBufferArrayMetadata {
147
153
  len: number;
148
154
  }
149
155
 
156
+ export type OndaPayloadDefault = string | OndaPayloadDefault[];
157
+ export type OndaPayloadType =
158
+ | { kind: "scalar"; encoding: OndaScalarType; integer_range?: OndaStateMetadata["integer_range"] }
159
+ | { kind: "tuple"; elements: OndaPayloadType[] }
160
+ | { kind: "struct"; name: string; fields: [OndaPayloadField, ...OndaPayloadField[]] }
161
+ | { kind: "array"; element: OndaPayloadType; len: number }
162
+ | { kind: "slice"; element: OndaPayloadType };
163
+ export interface OndaPayloadField {
164
+ name: string;
165
+ ty: OndaPayloadType;
166
+ default?: OndaPayloadDefault;
167
+ }
168
+ export interface OndaPayloadSchema { params: OndaPayloadField[] }
169
+
170
+ export type OndaPayloadValue = number | bigint | boolean | string | OndaPayloadValue[] | { [name: string]: OndaPayloadValue };
171
+ export interface OndaPayloadSizes { wire: number; workspace: number }
172
+ export class PayloadPlan {
173
+ constructor(schema: OndaPayloadSchema);
174
+ readonly schema: OndaPayloadSchema;
175
+ readonly fixedWireSize: number | null;
176
+ readonly minimumWorkspace: number;
177
+ readonly dynamicParameters: number;
178
+ readonly abiParameterCount: number;
179
+ /** Whether scalar representations match this flattened ABI parameter's schema default. */
180
+ matchesAbiDefault(parameter: number, defaultReprs: readonly string[] | null): boolean;
181
+ sizes(lengths: readonly number[]): OndaPayloadSizes;
182
+ requiredWorkspace(input: Uint8Array | ArrayBuffer): number;
183
+ encode(values: readonly unknown[] | Record<string, unknown>): Uint8Array;
184
+ decode(input: Uint8Array | ArrayBuffer): Record<string, OndaPayloadValue>;
185
+ }
186
+ export const EVENT_INPUT_SIZE_BYTES: 16;
187
+ export const PROCESSOR_EXECUTION_INPUT_REJECTED: 2;
188
+ export function writeEventInput(memory: WebAssembly.Memory | ArrayBuffer, address: number,
189
+ payloadAddress: number, payloadBytes: number, workspaceAddress: number, workspaceCapacityBytes: number): void;
190
+
191
+
150
192
  export interface OndaEventParamMetadata {
151
193
  name: string;
152
194
  type_repr: string;
@@ -162,6 +204,7 @@ export interface OndaEventParamMetadata {
162
204
  }
163
205
 
164
206
  export interface OndaEventMetadata {
207
+ schema: OndaPayloadSchema;
165
208
  name: string;
166
209
  export: string;
167
210
  payload_size_bytes: number | null;
@@ -183,6 +226,7 @@ export interface OndaDelegateParamMetadata {
183
226
  }
184
227
 
185
228
  export interface OndaDelegateMetadata {
229
+ schema: OndaPayloadSchema;
186
230
  index: number;
187
231
  name: string;
188
232
  payload_size_bytes: number | null;
@@ -211,9 +255,9 @@ export interface OndaStateMetadata {
211
255
 
212
256
  export interface OndaProcessorMetadata {
213
257
  format: "onda-processor";
214
- format_version: 5;
258
+ format_version: 6;
215
259
  artifact_kind: OndaArtifactKind;
216
- abi_version: 5;
260
+ abi_version: 6;
217
261
  backend: string;
218
262
  mir_schema_version: number;
219
263
  target: OndaTargetInfo;
package/src/index.js CHANGED
@@ -1,11 +1,13 @@
1
+ import { canonicalF32Number, PayloadPlan } from "./payload.js";
2
+ export { canonicalF32Number, PayloadPlan, EVENT_INPUT_SIZE_BYTES, PROCESSOR_EXECUTION_INPUT_REJECTED, writeEventInput } from "./payload.js";
1
3
  import "./param-control.js";
2
4
 
3
5
  const PARAM_CONTROL = globalThis.__ONDA_PARAM_CONTROL_V2__;
4
6
 
5
7
  export const PROCESSOR_ARTIFACT_FORMAT = "onda-processor";
6
8
  // Synchronized from format-versions.json; do not edit these copies directly.
7
- export const PROCESSOR_ARTIFACT_FORMAT_VERSION = 5;
8
- export const PROCESSOR_ABI_VERSION = 5;
9
+ export const PROCESSOR_ARTIFACT_FORMAT_VERSION = 6;
10
+ export const PROCESSOR_ABI_VERSION = 6;
9
11
  export const PROCESSOR_EXECUTION_OK = 0;
10
12
  export const PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE = 1;
11
13
  export const PROCESSOR_INIT_PRESERVE_PINNED = 0;
@@ -20,6 +22,7 @@ export const EXECUTION_OUTPUT_SIZE_BYTES = 12;
20
22
  export const {
21
23
  createParamDomain,
22
24
  createParamControl,
25
+ paramElementMetadata,
23
26
  constrainParamPlain,
24
27
  paramNormalizedToPlain,
25
28
  paramPlainToNormalized,
@@ -392,19 +395,12 @@ function validateIoMetadata(value, path, isParameter) {
392
395
  if (value.param_control !== null && value.range_min_repr === null) {
393
396
  throw new OndaArtifactError(`${path}.param_control requires range bounds`);
394
397
  }
395
- if (
396
- value.param_control !== null
397
- && (value.array_len !== 1 || value.type_repr !== value.scalar)
398
- ) {
399
- throw new OndaArtifactError(`${path}.param_control requires a scalar parameter`);
400
- }
401
398
  if (value.param_control !== null && !isParameter) {
402
399
  throw new OndaArtifactError(`${path}.param_control is only valid for parameters`);
403
400
  }
404
401
  if (
405
402
  isParameter
406
403
  && value.range_min_repr !== null
407
- && value.type_repr === value.scalar
408
404
  && value.scalar !== "bool"
409
405
  && value.param_control === null
410
406
  ) {
@@ -412,7 +408,9 @@ function validateIoMetadata(value, path, isParameter) {
412
408
  }
413
409
  if (value.param_control !== null) {
414
410
  try {
415
- PARAM_CONTROL.validateParamControlDomain(value, true);
411
+ for (let index = 0; index < value.array_len; ++index) {
412
+ PARAM_CONTROL.validateParamControlDomain(paramElementMetadata(value, index), true);
413
+ }
416
414
  } catch (error) {
417
415
  throw new OndaArtifactError(`${path}.param_control is invalid: ${error.message}`);
418
416
  }
@@ -483,12 +481,27 @@ function validateEventMetadata(value, path) {
483
481
  }
484
482
 
485
483
  function validatePayloadMetadata(value, path, supportsDefaults) {
484
+ let plan;
485
+ try { plan = new PayloadPlan(value?.schema); }
486
+ catch (error) { throw new OndaArtifactError(`${path}.schema: ${error.message}`); }
487
+ const prefixes = new Set(plan.tensors.filter((tensor) => tensor.lengthPrefix).map((tensor) => tensor.parameter));
488
+ const lengths = new Set(plan.parameters.map((group) => group.lengthParameter).filter((index) => index !== null));
486
489
  requireNullableInteger(value?.payload_size_bytes, `${path}.payload_size_bytes`, 0);
487
490
  requireInteger(value?.payload_min_size_bytes, `${path}.payload_min_size_bytes`, 0);
488
491
  requireBoolean(value?.has_dynamic_payload, `${path}.has_dynamic_payload`);
489
492
  if (!Array.isArray(value?.params)) {
490
493
  throw new OndaArtifactError(`${path}.params must be an array`);
491
494
  }
495
+ if (value.params.length !== plan.abiParameterCount) throw new OndaArtifactError(`${path}.params do not match schema`);
496
+ const expected = Array(plan.abiParameterCount);
497
+ for (const group of plan.parameters) {
498
+ if (group.lengthParameter !== null) expected[group.lengthParameter] = { name: group.name, scalar: "i32", length: 1, array: false, slice: false };
499
+ for (let index = group.start; index < group.end; index += 1) {
500
+ const tensor = plan.tensors[index];
501
+ expected[tensor.parameter] = { name: tensor.path, scalar: tensor.encoding,
502
+ length: group.dynamic ? 0 : tensor.elements, array: !group.dynamic && tensor.shape.length > 0, slice: group.dynamic };
503
+ }
504
+ }
492
505
  let minimumSize = 0;
493
506
  let hasDynamicParam = false;
494
507
  value.params.forEach((param, index) => {
@@ -507,6 +520,11 @@ function validatePayloadMetadata(value, path, supportsDefaults) {
507
520
  requireNullableStringArray(param?.default_reprs, `${paramPath}.default_reprs`);
508
521
  }
509
522
  requireScalarElementSize(param, paramPath);
523
+ const shape = expected[index];
524
+ if (param.name !== shape.name || param.scalar !== shape.scalar || param.array_len !== shape.length
525
+ || param.is_array !== shape.array || param.is_slice !== shape.slice) {
526
+ throw new OndaArtifactError(`${paramPath} does not match its schema tensor`);
527
+ }
510
528
  if (hasDynamicParam ? param.byte_offset !== null : param.byte_offset !== minimumSize) {
511
529
  throw new OndaArtifactError(`${paramPath}.byte_offset is inconsistent with event layout`);
512
530
  }
@@ -520,7 +538,7 @@ function validatePayloadMetadata(value, path, supportsDefaults) {
520
538
  ) {
521
539
  throw new OndaArtifactError(`${paramPath} has an invalid slice descriptor`);
522
540
  }
523
- minimumSize += 4;
541
+ if (prefixes.has(index)) minimumSize += 4;
524
542
  hasDynamicParam = true;
525
543
  } else {
526
544
  const expectedType = param.is_array
@@ -535,13 +553,12 @@ function validatePayloadMetadata(value, path, supportsDefaults) {
535
553
  throw new OndaArtifactError(`${paramPath} has an invalid fixed-size descriptor`);
536
554
  }
537
555
  minimumSize += param.byte_size;
556
+ if (lengths.has(index)) hasDynamicParam = true;
538
557
  }
539
558
  if (supportsDefaults) {
540
- if (param.has_default !== (param.default_reprs !== null)) {
541
- throw new OndaArtifactError(`${paramPath}.has_default must reflect default_reprs`);
542
- }
543
- if (param.default_reprs !== null && param.default_reprs.length !== param.array_len) {
544
- throw new OndaArtifactError(`${paramPath}.default_reprs must contain one value per element`);
559
+ if (param.has_default !== (param.default_reprs !== null)
560
+ || !plan.matchesAbiDefault(index, param.default_reprs)) {
561
+ throw new OndaArtifactError(`${paramPath} defaults do not match schema`);
545
562
  }
546
563
  }
547
564
  });
@@ -1081,14 +1098,6 @@ export function decodePrintRecords(
1081
1098
  return records;
1082
1099
  }
1083
1100
 
1084
- function shortestF32(value) {
1085
- for (let precision = 1; precision <= 9; precision += 1) {
1086
- const candidate = value.toPrecision(precision);
1087
- if (Object.is(Math.fround(Number(candidate)), value)) return candidate;
1088
- }
1089
- return value.toPrecision(9);
1090
- }
1091
-
1092
1101
  function canonicalFloat(value, width) {
1093
1102
  if (Number.isNaN(value)) return "NaN";
1094
1103
  if (value === Infinity) return "inf";
@@ -1096,7 +1105,9 @@ function canonicalFloat(value, width) {
1096
1105
  if (Object.is(value, -0)) return "-0.0";
1097
1106
  if (value === 0) return "0.0";
1098
1107
  const negative = value < 0;
1099
- const shortest = width === 32 ? shortestF32(Math.fround(Math.abs(value))) : Math.abs(value).toString();
1108
+ const shortest = width === 32
1109
+ ? canonicalF32Number(Math.abs(value)).toString()
1110
+ : Math.abs(value).toString();
1100
1111
  const [mantissa, exponentText] = shortest.toLowerCase().split("e");
1101
1112
  let digits = mantissa.replace(".", "");
1102
1113
  const leading = digits.match(/^0*/u)[0].length;
@@ -1197,6 +1208,8 @@ export function formatPrintRecords(storage, usedBytes, metadata, overflowCount =
1197
1208
  return { text, entries: records, overflowCount };
1198
1209
  }
1199
1210
 
1211
+ const delegatePayloadPlans = new WeakMap();
1212
+
1200
1213
  export function decodeDelegateRecords(
1201
1214
  storage,
1202
1215
  usedBytes,
@@ -1217,6 +1230,7 @@ export function decodeDelegateRecords(
1217
1230
  }
1218
1231
  const view = new DataView(bytes.buffer, bytes.byteOffset, usedBytes);
1219
1232
  const records = [];
1233
+ const plans = new Array(delegates.length);
1220
1234
  let cursor = 0;
1221
1235
  while (cursor < usedBytes) {
1222
1236
  if (usedBytes - cursor < DELEGATE_RECORD_HEADER_SIZE_BYTES) {
@@ -1244,8 +1258,7 @@ export function decodeDelegateRecords(
1244
1258
  view,
1245
1259
  payloadOffset,
1246
1260
  payloadByteLength,
1247
- delegate,
1248
- littleEndian,
1261
+ plans[delegateIndex] ??= delegatePayloadPlan(delegate.schema),
1249
1262
  ),
1250
1263
  });
1251
1264
  cursor = end;
@@ -1253,50 +1266,20 @@ export function decodeDelegateRecords(
1253
1266
  return records;
1254
1267
  }
1255
1268
 
1256
- function decodeDelegatePayload(view, start, size, delegate, littleEndian) {
1257
- let cursor = start;
1258
- const end = start + size;
1259
- const values = {};
1260
- for (const param of delegate.params) {
1261
- let count = param.array_len;
1262
- if (param.is_slice) {
1263
- if (cursor + 4 > end) {
1264
- throw new OndaArtifactError(`delegate '${delegate.name}' has a truncated slice length`);
1265
- }
1266
- count = view.getInt32(cursor, littleEndian);
1267
- cursor += 4;
1268
- if (count < 0) {
1269
- throw new OndaArtifactError(`delegate '${delegate.name}' has a negative slice length`);
1270
- }
1271
- }
1272
- const byteLength = count * param.element_size_bytes;
1273
- if (!Number.isSafeInteger(byteLength) || cursor + byteLength > end) {
1274
- throw new OndaArtifactError(`delegate '${delegate.name}' has a truncated '${param.name}' payload`);
1275
- }
1276
- const entries = [];
1277
- for (let index = 0; index < count; index += 1) {
1278
- entries.push(readPayloadScalar(view, cursor, param.scalar, littleEndian));
1279
- cursor += param.element_size_bytes;
1280
- }
1281
- values[param.name] = param.is_array || param.is_slice ? entries : entries[0];
1282
- }
1283
- if (cursor !== end) {
1284
- throw new OndaArtifactError(`delegate '${delegate.name}' payload has trailing bytes`);
1269
+ function delegatePayloadPlan(schema) {
1270
+ let plan = delegatePayloadPlans.get(schema);
1271
+ if (plan === undefined) {
1272
+ plan = new PayloadPlan(schema);
1273
+ delegatePayloadPlans.set(schema, plan);
1285
1274
  }
1286
- return values;
1275
+ return plan;
1287
1276
  }
1288
1277
 
1289
- function readPayloadScalar(view, address, scalar, littleEndian) {
1290
- switch (scalar) {
1291
- case "bool": return view.getUint8(address) !== 0;
1292
- case "i32": return view.getInt32(address, littleEndian);
1293
- case "i64": return view.getBigInt64(address, littleEndian);
1294
- case "f32": return view.getFloat32(address, littleEndian);
1295
- case "f64": return view.getFloat64(address, littleEndian);
1296
- default: throw new OndaArtifactError(`unsupported delegate scalar '${String(scalar)}'`);
1297
- }
1278
+ function decodeDelegatePayload(view, start, size, plan) {
1279
+ return plan.decode(new Uint8Array(view.buffer, view.byteOffset + start, size));
1298
1280
  }
1299
1281
 
1282
+
1300
1283
  function writableDataView(memory) {
1301
1284
  if (memory instanceof DataView) return memory;
1302
1285
  if (memory instanceof WebAssembly.Memory) return new DataView(memory.buffer);
@@ -18,6 +18,27 @@
18
18
  throw new TypeError(`Onda parameter${name} ${message}`);
19
19
  }
20
20
 
21
+ function paramElementMetadata(param, index) {
22
+ if (!Number.isSafeInteger(index) || index < 0 || index >= param?.array_len) {
23
+ fail(param, "element index is out of bounds");
24
+ }
25
+ if (param.type_repr === param.scalar && param.array_len === 1) return param;
26
+ if (param.type_repr !== `${param.scalar}[${param.array_len}]`) {
27
+ fail(param, "has invalid array shape metadata");
28
+ }
29
+ const width = param.element_size_bytes;
30
+ return {
31
+ ...param,
32
+ name: `${param.name}[${index}]`,
33
+ type_repr: param.scalar,
34
+ array_len: 1,
35
+ byte_offset: param.byte_offset === null ? null : param.byte_offset + index * width,
36
+ byte_size: width,
37
+ slot_offset: param.slot_offset + index,
38
+ default_reprs: param.default_reprs === null ? null : [param.default_reprs?.[index]],
39
+ };
40
+ }
41
+
21
42
  function scalarKind(param) {
22
43
  if (!param || typeof param !== "object" || Array.isArray(param)) {
23
44
  fail(param, "metadata must be an object");
@@ -363,7 +384,8 @@
363
384
  return Math.min(1, Math.max(0, normalized));
364
385
  }
365
386
 
366
- function createParamControl(param) {
387
+ function createParamControl(param, element) {
388
+ if (element !== undefined) param = paramElementMetadata(param, element);
367
389
  const scalar = scalarKind(param);
368
390
  if (scalar === "bool") {
369
391
  return Object.freeze({
@@ -450,6 +472,7 @@
450
472
  validateParamControlDomain,
451
473
  createParamDomain,
452
474
  createParamControl,
475
+ paramElementMetadata,
453
476
  constrainParamPlain,
454
477
  paramNormalizedToPlain,
455
478
  paramPlainToNormalized,
package/src/payload.js ADDED
@@ -0,0 +1,427 @@
1
+ // Logical SoA shape planning. Array extents remain axes; plans never expand
2
+ // array elements into metadata. This mirrors the compiler-free Rust planner.
3
+ const LIMIT = 0x7fffffff;
4
+ const SIZES = Object.freeze({ bool: 1, i32: 4, i64: 8, f32: 4, f64: 8 });
5
+ const SIGNED_DECIMAL_INTEGER = /^[+-]?[0-9]+$/;
6
+ export const EVENT_INPUT_SIZE_BYTES = 16;
7
+ export const PROCESSOR_EXECUTION_INPUT_REJECTED = 2;
8
+
9
+ /** Return the shortest host number that round-trips to the same f32. */
10
+ export function canonicalF32Number(value) {
11
+ const rounded = Math.fround(value);
12
+ if (!Number.isFinite(rounded) || rounded === 0) return rounded;
13
+ for (let precision = 1; precision <= 9; precision += 1) {
14
+ const candidate = Number(rounded.toPrecision(precision));
15
+ if (Math.fround(candidate) === rounded) return candidate;
16
+ }
17
+ return rounded;
18
+ }
19
+
20
+ function freeze(value, seen = new Set()) {
21
+ if (!value || typeof value !== "object" || seen.has(value)) return;
22
+ seen.add(value);
23
+ for (const child of Object.values(value)) freeze(child, seen);
24
+ Object.freeze(value);
25
+ }
26
+
27
+ function extent(value) {
28
+ if (!Number.isSafeInteger(value) || value < 0 || value > LIMIT) {
29
+ throw new RangeError("payload byte extent exceeds i32");
30
+ }
31
+ return value;
32
+ }
33
+ function align(value, alignment) {
34
+ return Math.floor(extent(value + alignment - 1) / alignment) * alignment;
35
+ }
36
+ function fields(entries) {
37
+ if (!Array.isArray(entries)) throw new TypeError("invalid payload fields");
38
+ const names = new Set();
39
+ for (const entry of entries) {
40
+ if (typeof entry?.name !== "string" || !entry.name || /[.\[\]]/.test(entry.name) || names.has(entry.name)) {
41
+ throw new TypeError("invalid or duplicate payload field name");
42
+ }
43
+ names.add(entry.name);
44
+ }
45
+ return names;
46
+ }
47
+ function arrayElement(ty) {
48
+ return ty?.kind === "scalar" || ty?.kind === "struct";
49
+ }
50
+ function parseSignedDecimalInteger(value, message) {
51
+ if (typeof value !== "string" || !SIGNED_DECIMAL_INTEGER.test(value)) {
52
+ throw new TypeError(message);
53
+ }
54
+ return BigInt(value);
55
+ }
56
+ function domain(encoding, range) {
57
+ if (range == null) return null;
58
+ if (!["i32", "i64"].includes(encoding) || !["clamp", "wrap"].includes(range.mode)
59
+ || range.min?.type !== encoding || range.max?.type !== encoding) {
60
+ throw new TypeError("invalid payload integer range");
61
+ }
62
+ const bits = encoding === "i32" ? 32 : 64;
63
+ const min = parseSignedDecimalInteger(range.min.value, "invalid payload integer range");
64
+ const max = parseSignedDecimalInteger(range.max.value, "invalid payload integer range");
65
+ if (min > max || BigInt.asIntN(bits, min) !== min || BigInt.asIntN(bits, max) !== max) {
66
+ throw new RangeError("invalid payload integer range");
67
+ }
68
+ return { min, max, wrap: range.mode === "wrap" };
69
+ }
70
+
71
+ export class PayloadPlan {
72
+ #parameterNames;
73
+ #abiDefaults;
74
+
75
+ constructor(schema) {
76
+ schema = structuredClone(schema);
77
+ this.#parameterNames = fields(schema?.params);
78
+ this.parameters = [];
79
+ this.tensors = [];
80
+ this.schema = schema;
81
+ const active = new Set();
82
+ const visit = (ty, path, shape, steps) => {
83
+ if (!ty || active.has(ty)) throw new TypeError("invalid recursive payload schema");
84
+ active.add(ty);
85
+ shape.reduce((count, axis) => extent(count * axis), 1);
86
+ switch (ty.kind) {
87
+ case "scalar": {
88
+ const size = SIZES[ty.encoding];
89
+ if (size === undefined) throw new TypeError("invalid payload scalar encoding");
90
+ const elements = shape.reduce((count, axis) => extent(count * axis), 1);
91
+ this.tensors.push({ path, encoding: ty.encoding, size, shape, steps: steps.map((step) => ({ ...step })), elements,
92
+ domain: domain(ty.encoding, ty.integer_range) });
93
+ break;
94
+ }
95
+ case "tuple":
96
+ if (!Array.isArray(ty.elements) || !ty.elements.length
97
+ || ty.elements.some((element) => element?.kind !== "scalar")) {
98
+ throw new TypeError("invalid payload tuple");
99
+ }
100
+ ty.elements.forEach((element, index) =>
101
+ visit(element, `${path}.__${index}`, shape, [...steps, { field: index }]));
102
+ break;
103
+ case "struct":
104
+ if (typeof ty.name !== "string" || !ty.name) throw new TypeError("invalid payload struct name");
105
+ fields(ty.fields);
106
+ if (!ty.fields.length) throw new TypeError("payload structs must contain at least one field");
107
+ for (const field of ty.fields) {
108
+ if (field.default !== undefined) parsePayloadDefault(field.ty, field.default);
109
+ visit(field.ty, `${path}.${field.name}`, shape, [...steps, { field: field.name }]);
110
+ }
111
+ break;
112
+ case "array":
113
+ if (!arrayElement(ty.element) || extent(ty.len) === 0) {
114
+ throw new TypeError("invalid payload array");
115
+ }
116
+ visit(ty.element, path, [...shape, ty.len], [...steps, { axis: ty.len }]);
117
+ break;
118
+ default: throw new TypeError("invalid payload type");
119
+ }
120
+ active.delete(ty);
121
+ };
122
+ let abiParameter = 0;
123
+ for (const field of schema.params) {
124
+ const dynamic = field.ty?.kind === "slice";
125
+ const start = this.tensors.length;
126
+ const ty = dynamic ? field.ty.element : field.ty;
127
+ if (dynamic && !arrayElement(ty)) throw new TypeError("invalid payload slice element");
128
+ const lengthParameter = dynamic && ty.kind === "struct" ? abiParameter++ : null;
129
+ visit(ty, field.name, [], dynamic ? [{ axis: null }] : []);
130
+ if (this.tensors.length === start) throw new TypeError("payload types must contain at least one scalar");
131
+ for (let index = start; index < this.tensors.length; index += 1) {
132
+ this.tensors[index].parameter = abiParameter++;
133
+ this.tensors[index].lengthPrefix = dynamic && lengthParameter === null;
134
+ }
135
+ this.parameters.push({ name: field.name, dynamic, lengthParameter, start, end: this.tensors.length });
136
+ }
137
+ this.abiParameterCount = abiParameter;
138
+ this.dynamicParameters = this.parameters.filter((param) => param.dynamic).length;
139
+ const minimum = this.sizes(Array(this.dynamicParameters).fill(0));
140
+ this.fixedWireSize = this.dynamicParameters === 0 ? minimum.wire : null;
141
+ this.minimumWorkspace = minimum.workspace;
142
+ this.defaults = schema.params.map((field) =>
143
+ field.default === undefined ? undefined : parsePayloadDefault(field.ty, field.default));
144
+ for (const tensor of this.tensors) {
145
+ let stride = 1;
146
+ for (let index = tensor.steps.length - 1; index >= 0; index -= 1) {
147
+ const step = tensor.steps[index];
148
+ if (step.field === undefined) { step.stride = stride; if (step.axis !== null) stride *= step.axis; }
149
+ }
150
+ }
151
+ this.#abiDefaults = Array(this.abiParameterCount).fill(null);
152
+ for (let parameter = 0; parameter < this.parameters.length; parameter += 1) {
153
+ const source = this.defaults[parameter];
154
+ if (source === undefined) continue;
155
+ const group = this.parameters[parameter];
156
+ for (let index = group.start; index < group.end; index += 1) {
157
+ const tensor = this.tensors[index];
158
+ this.#abiDefaults[tensor.parameter] = {
159
+ encoding: tensor.encoding,
160
+ values: Array.from(
161
+ { length: tensor.elements },
162
+ (_, element) => leafValue(source, tensor.steps, element),
163
+ ),
164
+ };
165
+ }
166
+ }
167
+ freeze(this);
168
+ }
169
+
170
+ matchesAbiDefault(parameter, defaultReprs) {
171
+ if (!Number.isInteger(parameter) || parameter < 0 || parameter >= this.abiParameterCount) return false;
172
+ const defaults = this.#abiDefaults[parameter];
173
+ if (defaults === null || defaultReprs === null) return defaults === defaultReprs;
174
+ if (!Array.isArray(defaultReprs) || defaultReprs.length !== defaults.values.length) return false;
175
+ try {
176
+ return defaultReprs.every((repr, index) => {
177
+ const actual = parseScalarDefault(defaults.encoding, repr);
178
+ const expected = defaults.values[index];
179
+ return defaults.encoding === "f32"
180
+ ? Object.is(Math.fround(actual), Math.fround(expected))
181
+ : Object.is(actual, expected);
182
+ });
183
+ } catch {
184
+ return false;
185
+ }
186
+ }
187
+
188
+ // Read-only preflight: no per-element metadata or temporary payload copies.
189
+ walk(length, tensor, prefix = null) {
190
+ let wire = 0;
191
+ let workspace = 0;
192
+ for (let parameter = 0; parameter < this.parameters.length; parameter += 1) {
193
+ const param = this.parameters[parameter];
194
+ let logicalLength = 1;
195
+ if (param.dynamic) {
196
+ logicalLength = extent(length(wire, parameter));
197
+ workspace = align(workspace, 4);
198
+ if (prefix) prefix(wire, workspace, logicalLength);
199
+ wire = extent(wire + 4);
200
+ workspace = extent(workspace + 4);
201
+ }
202
+ for (let index = param.start; index < param.end; index += 1) {
203
+ const leaf = this.tensors[index];
204
+ const elements = extent(logicalLength * leaf.elements);
205
+ const bytes = extent(elements * leaf.size);
206
+ workspace = align(workspace, leaf.size);
207
+ if (tensor) tensor(index, wire, workspace, elements, parameter);
208
+ wire = extent(wire + bytes);
209
+ workspace = extent(workspace + bytes);
210
+ }
211
+ }
212
+ return { wire, workspace };
213
+ }
214
+
215
+ sizes(lengths) {
216
+ if (lengths.length !== this.dynamicParameters) throw new RangeError("payload lengths do not match schema");
217
+ let index = 0;
218
+ return this.walk(() => lengths[index++], null);
219
+ }
220
+
221
+ requiredWorkspace(input) {
222
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
223
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
224
+ const sizes = this.walk((offset) => {
225
+ if (offset + 4 > bytes.byteLength) throw new RangeError("truncated payload slice length");
226
+ const length = view.getInt32(offset, true);
227
+ if (length < 0) throw new RangeError("negative payload slice length");
228
+ return length;
229
+ }, null);
230
+ if (sizes.wire > bytes.byteLength) throw new RangeError("truncated payload");
231
+ if (sizes.wire < bytes.byteLength) throw new RangeError("unexpected trailing payload bytes");
232
+ return sizes.workspace;
233
+ }
234
+ /** Encode logical values outside realtime dispatch, preserving exact i64 values.
235
+ * Accept ordered parameter arrays or objects keyed by the declared names. */
236
+ encode(values) {
237
+ const positional = Array.isArray(values);
238
+ const named = !positional && values !== null && typeof values === "object";
239
+ if (!positional && !named) throw new TypeError("payload values must be an ordered array or named object");
240
+ if (positional && values.length > this.parameters.length) {
241
+ throw new RangeError("payload parameter count exceeds schema");
242
+ }
243
+ if (named) {
244
+ const unexpected = Object.keys(values).find((name) => !this.#parameterNames.has(name));
245
+ if (unexpected !== undefined) throw new TypeError(`unexpected payload parameter '${unexpected}'`);
246
+ }
247
+ const roots = this.schema.params.map((field, index) => {
248
+ let value;
249
+ if (positional) value = values[index];
250
+ else if (named && Object.hasOwn(values, field.name)) value = values[field.name];
251
+ const result = value === undefined ? this.defaults[index] : value;
252
+ if (result === undefined) throw new TypeError(`missing payload parameter '${field.name}'`);
253
+ validateValue(field.ty, result);
254
+ return result;
255
+ });
256
+ const sizes = this.walk((_, parameter) => roots[parameter].length, null);
257
+ const bytes = new Uint8Array(sizes.wire);
258
+ const view = new DataView(bytes.buffer);
259
+ this.walk((_, parameter) => roots[parameter].length, (index, offset, _workspace, count, parameter) => {
260
+ const tensor = this.tensors[index];
261
+ for (let element = 0; element < count; element += 1) {
262
+ writeScalar(view, offset + element * tensor.size, tensor.encoding, leafValue(roots[parameter], tensor.steps, element));
263
+ }
264
+ }, (offset, _workspace, length) => view.setInt32(offset, length, true));
265
+ return bytes;
266
+ }
267
+
268
+ /** Decode one complete wire payload into nested host values. */
269
+ decode(input) {
270
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
271
+ this.requiredWorkspace(bytes);
272
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
273
+ const roots = this.schema.params.map((field) => field.ty.kind === "slice" ? null : emptyValue(field.ty));
274
+ this.walk((offset, parameter) => {
275
+ const length = view.getInt32(offset, true);
276
+ roots[parameter] = emptyValue(this.schema.params[parameter].ty, length);
277
+ return length;
278
+ }, (index, offset, _workspace, count, parameter) => {
279
+ const tensor = this.tensors[index];
280
+ for (let element = 0; element < count; element += 1) {
281
+ roots[parameter] = leafValue(roots[parameter], tensor.steps, element,
282
+ readScalar(view, offset + element * tensor.size, tensor.encoding), true);
283
+ }
284
+ });
285
+ return Object.fromEntries(this.schema.params.map((field, index) => [field.name, roots[index]]));
286
+ }
287
+ }
288
+
289
+ export function writeEventInput(memory, address, payloadAddress, payloadBytes, workspaceAddress, workspaceCapacityBytes) {
290
+ const view = new DataView(memory.buffer ?? memory);
291
+ for (const value of [address, payloadAddress, payloadBytes, workspaceAddress, workspaceCapacityBytes]) extent(value);
292
+ if (address % 4 || workspaceAddress % 8) throw new RangeError("misaligned event input storage");
293
+ if (address + EVENT_INPUT_SIZE_BYTES > view.byteLength
294
+ || payloadAddress + payloadBytes > view.byteLength
295
+ || workspaceAddress + workspaceCapacityBytes > view.byteLength) throw new RangeError("event input exceeds memory");
296
+ view.setUint32(address, payloadAddress, true);
297
+ view.setUint32(address + 4, payloadBytes, true);
298
+ view.setUint32(address + 8, workspaceAddress, true);
299
+ view.setUint32(address + 12, workspaceCapacityBytes, true);
300
+ }
301
+
302
+ function scalarValue(encoding, value) {
303
+ if (encoding === "bool") {
304
+ if (typeof value !== "boolean") throw new TypeError("bool payload value must be a boolean");
305
+ return value;
306
+ }
307
+ if (encoding === "i64") {
308
+ if (typeof value === "number" && !Number.isSafeInteger(value)) throw new TypeError("i64 payload value must be an exact integer");
309
+ let integer;
310
+ if (typeof value === "string") {
311
+ integer = parseSignedDecimalInteger(value, "invalid i64 payload value");
312
+ } else {
313
+ if (typeof value !== "bigint" && typeof value !== "number") {
314
+ throw new TypeError("invalid i64 payload value");
315
+ }
316
+ integer = BigInt(value);
317
+ }
318
+ if (BigInt.asIntN(64, integer) !== integer) throw new RangeError("i64 payload value is outside the signed 64-bit range");
319
+ return integer;
320
+ }
321
+ if (typeof value !== "number") throw new TypeError(`${encoding} payload value must be a number`);
322
+ if (encoding === "i32" && (!Number.isInteger(value) || value < -2147483648 || value > 2147483647)) {
323
+ throw new RangeError("i32 payload value is outside the signed 32-bit range");
324
+ }
325
+ return value;
326
+ }
327
+ function parseScalarDefault(encoding, value) {
328
+ if (typeof value !== "string") throw new TypeError("invalid scalar payload default");
329
+ switch (encoding) {
330
+ case "bool":
331
+ if (value !== "true" && value !== "false") throw new TypeError("invalid bool payload default");
332
+ return value === "true";
333
+ case "i32":
334
+ return scalarValue(encoding, Number(parseSignedDecimalInteger(value, "invalid i32 payload default")));
335
+ case "i64":
336
+ return scalarValue(encoding, parseSignedDecimalInteger(value, "invalid i64 payload default"));
337
+ case "f32": case "f64":
338
+ if (!/^[+-]?(?:(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|inf(?:inity)?|nan)$/i.test(value)) {
339
+ throw new TypeError("invalid floating-point payload default");
340
+ }
341
+ return /^[+-]?inf(?:inity)?$/i.test(value)
342
+ ? (value.startsWith("-") ? -Infinity : Infinity)
343
+ : Number(value);
344
+ default: throw new TypeError("invalid payload scalar encoding");
345
+ }
346
+ }
347
+ function parsePayloadDefault(ty, value) {
348
+ if (ty.kind === "scalar") return parseScalarDefault(ty.encoding, value);
349
+ if (!Array.isArray(value)) throw new TypeError("invalid aggregate payload default");
350
+ if (ty.kind === "struct") {
351
+ if (value.length !== ty.fields.length) throw new TypeError("payload default field count mismatch");
352
+ return Object.fromEntries(ty.fields.map((field, index) =>
353
+ [field.name, parsePayloadDefault(field.ty, value[index])]));
354
+ }
355
+ if (ty.kind === "tuple") {
356
+ if (value.length !== ty.elements.length) throw new TypeError("payload default tuple length mismatch");
357
+ return value.map((entry, index) => parsePayloadDefault(ty.elements[index], entry));
358
+ }
359
+ if (ty.kind === "array" && value.length === ty.len) {
360
+ return value.map((entry) => parsePayloadDefault(ty.element, entry));
361
+ }
362
+ throw new TypeError("invalid payload default shape");
363
+ }
364
+ function validateValue(ty, value) {
365
+ switch (ty.kind) {
366
+ case "scalar": scalarValue(ty.encoding, value); return;
367
+ case "struct": {
368
+ const keys = value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : [];
369
+ if (!value || typeof value !== "object" || Array.isArray(value) || keys.length !== ty.fields.length
370
+ || ty.fields.some((field) => !Object.hasOwn(value, field.name))) {
371
+ throw new TypeError(`payload '${ty.name}' must be an object with exactly its declared fields`);
372
+ }
373
+ for (const field of ty.fields) validateValue(field.ty, value[field.name]);
374
+ return;
375
+ }
376
+ case "tuple":
377
+ if (!Array.isArray(value) || value.length !== ty.elements.length) throw new TypeError("payload tuple length mismatch");
378
+ for (let index = 0; index < value.length; index += 1) validateValue(ty.elements[index], value[index]);
379
+ return;
380
+ case "slice": case "array":
381
+ if (!Array.isArray(value) && !(ArrayBuffer.isView(value) && !(value instanceof DataView))) throw new TypeError("payload array must be a sequence");
382
+ extent(value.length);
383
+ if (ty.kind === "array" && value.length !== ty.len) throw new RangeError("payload fixed array length mismatch");
384
+ for (let index = 0; index < value.length; index += 1) validateValue(ty.element, value[index]);
385
+ return;
386
+ default: throw new TypeError("invalid payload value type");
387
+ }
388
+ }
389
+ function emptyValue(ty, length = 0) {
390
+ switch (ty.kind) {
391
+ case "scalar": return null;
392
+ case "struct": return Object.fromEntries(ty.fields.map((field) => [field.name, emptyValue(field.ty)]));
393
+ case "tuple": return ty.elements.map((element) => emptyValue(element));
394
+ case "array": return Array.from({ length: ty.len }, () => emptyValue(ty.element));
395
+ case "slice": return Array.from({ length }, () => emptyValue(ty.element));
396
+ default: throw new TypeError("invalid payload type");
397
+ }
398
+ }
399
+ function leafValue(root, steps, index, replacement, write) {
400
+ if (steps.length === 0) return write ? replacement : root;
401
+ let current = root;
402
+ for (let part = 0; part < steps.length; part += 1) {
403
+ const step = steps[part];
404
+ const key = step.field !== undefined ? step.field : (step.axis === null ? Math.floor(index / step.stride) : Math.floor(index / step.stride) % step.axis);
405
+ if (write && part === steps.length - 1) current[key] = replacement;
406
+ else current = current[key];
407
+ }
408
+ return write ? root : current;
409
+ }
410
+ function readScalar(view, offset, encoding) {
411
+ switch (encoding) {
412
+ case "bool": return view.getUint8(offset) !== 0;
413
+ case "i32": return view.getInt32(offset, true);
414
+ case "i64": return view.getBigInt64(offset, true);
415
+ case "f32": return canonicalF32Number(view.getFloat32(offset, true));
416
+ case "f64": return view.getFloat64(offset, true);
417
+ }
418
+ }
419
+ function writeScalar(view, offset, encoding, value) {
420
+ switch (encoding) {
421
+ case "bool": view.setUint8(offset, value ? 1 : 0); break;
422
+ case "i32": view.setInt32(offset, value, true); break;
423
+ case "i64": view.setBigInt64(offset, scalarValue(encoding, value), true); break;
424
+ case "f32": view.setFloat32(offset, value, true); break;
425
+ case "f64": view.setFloat64(offset, value, true); break;
426
+ }
427
+ }