animader 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not limited
43
+ to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "animader",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "JS glue for animader.wasm, the deterministic runtime",
5
+ "license": "CC0-1.0",
6
+ "type": "module",
7
+ "main": "./src/index.js",
8
+ "exports": {
9
+ ".": "./src/index.js",
10
+ "./log": "./src/log.js",
11
+ "./route": "./src/route.js",
12
+ "./session": "./src/session.js",
13
+ "./piece": "./src/piece.js",
14
+ "./wasm": "./wasm/animader.wasm",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "wasm",
20
+ "LICENSE"
21
+ ],
22
+ "scripts": {
23
+ "test": "node --test"
24
+ }
25
+ }
package/src/index.js ADDED
@@ -0,0 +1,482 @@
1
+ // animader - JS glue around animader.wasm.
2
+ //
3
+ // The log tier is a pure function of a session document and its 'ANEV'
4
+ // blob. This file mirrors src/wasm_entry.zig's zone convention byte for
5
+ // byte: the host writes the text or the blob into
6
+ // `exports.anm_log_inPtr()`, calls one of the six exports with the byte
7
+ // length, and reads `anm_log_outLen()` bytes from `anm_log_outPtr()`.
8
+ // 'ANEV' itself (src/Abi.zig) is:
9
+ //
10
+ // [magic u32]['ANEV'][version u32][count u32][strtab_len u32]
11
+ // count x 32-byte records
12
+ // strtab_len bytes: NUL-separated strings referenced by index
13
+ //
14
+ // Return convention, mirrored from the entry header: a call answers a
15
+ // byte length (>= 0) or a negative status, never data:
16
+ //
17
+ // -1 diagnostics; `LogError.code` is the first EventLog code
18
+ // -2 bad call (over a zone cap, malformed blob, no cached session)
19
+ // -3 out of memory
20
+ // -4 output over its zone
21
+ // -5 a component over its cap
22
+ //
23
+ // Session state: 'ANEV' carries no `(session ...)` header, so the wasm
24
+ // module caches the session from the last clean parse; `encode` renders
25
+ // that session with the blob's records. `parse` must therefore run before
26
+ // `encode` in the same instance.
27
+ //
28
+ // `pointerState` decodes the boundary's 64-byte little-endian
29
+ // PointerState wire (the field-by-field layout is in src/wasm_entry.zig's
30
+ // header) into the same field object the native fold produces.
31
+ //
32
+ // Memory views are re-taken from `exports.memory.buffer` on every call
33
+ // (the pacer discipline): a view taken before a grow would detach. This
34
+ // module's zones never grow, but the glue does not rely on that.
35
+
36
+ const MAGIC = 0x56454e41; // 'ANEV' read little-endian
37
+ const VERSION = 1;
38
+ const HEADER_LEN = 20;
39
+ const RECORD_LEN = 32;
40
+ const MAX_EVENTS = 1 << 20;
41
+ const MAX_STRTAB = 1 << 16;
42
+ const NO_CODE = 0xffff;
43
+ const MAX_SAFE = Number.MAX_SAFE_INTEGER;
44
+ const POINTER_STATE_LEN = 64;
45
+
46
+ const STATUS_DIAGNOSTICS = -1;
47
+ const STATUS_BAD_CALL = -2;
48
+ const STATUS_OOM = -3;
49
+ const STATUS_OUTPUT_TOO_SMALL = -4;
50
+ const STATUS_COMPONENT_TOO_LARGE = -5;
51
+
52
+ /** Kind ordinals, append-only on the wire (`EventLog.Kind`). */
53
+ export const KINDS = [
54
+ "resize",
55
+ "down",
56
+ "move",
57
+ "up",
58
+ "wheel",
59
+ "key",
60
+ "custom",
61
+ "input-write",
62
+ "mark",
63
+ "adjust",
64
+ "reset",
65
+ "cancel",
66
+ "derived",
67
+ ];
68
+
69
+ const encoder = new TextEncoder();
70
+ const decoder = new TextDecoder();
71
+
72
+ // SJON's executable-plugin dispatch import (`env.sjon_host_invoke_plugin`).
73
+ // The session schema declares no executable plugins, so it is never
74
+ // called; returning 0 maps to a clean SJON diagnostic rather than a trap.
75
+ // Every instantiation must provide it.
76
+ export const IMPORTS = { env: { sjon_host_invoke_plugin: () => 0 } };
77
+
78
+ /** A boundary failure or a malformed 'ANEV' blob. */
79
+ export class LogError extends Error {
80
+ /**
81
+ * @param {string} message
82
+ * @param {{ status?: number | null, code?: number | null }} [details]
83
+ * `status` is the boundary's negative return (null for a JS-side
84
+ * defect); `code` is the first EventLog diagnostic code for a
85
+ * diagnosed parse.
86
+ */
87
+ constructor(message, { status = null, code = null } = {}) {
88
+ super(message);
89
+ this.name = "LogError";
90
+ this.status = status;
91
+ this.code = code;
92
+ }
93
+ }
94
+
95
+ /** The status semantics, so a caller does not have to know the integers. */
96
+ export const STATUS = {
97
+ DIAGNOSTICS: STATUS_DIAGNOSTICS,
98
+ BAD_CALL: STATUS_BAD_CALL,
99
+ OOM: STATUS_OOM,
100
+ OUTPUT_TOO_SMALL: STATUS_OUTPUT_TOO_SMALL,
101
+ COMPONENT_TOO_LARGE: STATUS_COMPONENT_TOO_LARGE,
102
+ };
103
+
104
+ const describeStatus = (status) => {
105
+ switch (status) {
106
+ case STATUS_DIAGNOSTICS:
107
+ return "the session has diagnostics";
108
+ case STATUS_BAD_CALL:
109
+ return "bad call";
110
+ case STATUS_OOM:
111
+ return "out of memory";
112
+ case STATUS_OUTPUT_TOO_SMALL:
113
+ return "the output would not fit its zone";
114
+ case STATUS_COMPONENT_TOO_LARGE:
115
+ return "a session component is over its cap";
116
+ default:
117
+ return `unknown status ${status}`;
118
+ }
119
+ };
120
+
121
+ function toBytes(blob) {
122
+ if (blob instanceof Uint8Array) return blob;
123
+ if (blob instanceof ArrayBuffer) return new Uint8Array(blob);
124
+ if (ArrayBuffer.isView(blob)) return new Uint8Array(blob.buffer, blob.byteOffset, blob.byteLength);
125
+ throw new TypeError("animader: expected an ArrayBuffer or a typed array");
126
+ }
127
+
128
+ function micros(value, what) {
129
+ if (!Number.isSafeInteger(value)) {
130
+ throw new LogError(`animader: ${what} must be a safe integer (microseconds), got ${value}`, {
131
+ status: STATUS_BAD_CALL,
132
+ });
133
+ }
134
+ return value;
135
+ }
136
+
137
+ /** The decoded string table: one entry per NUL-separated name. */
138
+ function decodeStrings(bytes) {
139
+ const out = [];
140
+ let pos = 0;
141
+ while (pos < bytes.length) {
142
+ const end = bytes.indexOf(0, pos);
143
+ if (end === -1) {
144
+ out.push(decoder.decode(bytes.subarray(pos)));
145
+ break;
146
+ }
147
+ out.push(decoder.decode(bytes.subarray(pos, end)));
148
+ pos = end + 1;
149
+ }
150
+ return out;
151
+ }
152
+
153
+ /** The loaded boundary artifact and the JS-side 'ANEV' decode. */
154
+ export class Log {
155
+ #e;
156
+
157
+ /**
158
+ * Instantiate the artifact synchronously (node, tests). `bytes` is the
159
+ * built animader.wasm, e.g. from `readFileSync`.
160
+ * @param {BufferSource} bytes
161
+ * @returns {Log}
162
+ */
163
+ static loadSync(bytes) {
164
+ return new Log(new WebAssembly.Instance(new WebAssembly.Module(bytes), IMPORTS));
165
+ }
166
+
167
+ /**
168
+ * Instantiate the artifact from bytes or a compiled module (browser).
169
+ * @param {BufferSource | WebAssembly.Module} source
170
+ * @returns {Promise<Log>}
171
+ */
172
+ static async load(source) {
173
+ const instance =
174
+ source instanceof WebAssembly.Module
175
+ ? await WebAssembly.instantiate(source, IMPORTS)
176
+ : (await WebAssembly.instantiate(source, IMPORTS)).instance;
177
+ return new Log(instance);
178
+ }
179
+
180
+ /** @param {WebAssembly.Instance} instance */
181
+ constructor(instance) {
182
+ this.#e = instance.exports;
183
+ if (typeof this.#e.animader_abiVersion !== "function" || this.#e.animader_abiVersion() !== 1) {
184
+ throw new LogError("animader: unsupported or missing ABI version 1");
185
+ }
186
+ for (const name of [
187
+ "anm_log_inPtr",
188
+ "anm_log_inCap",
189
+ "anm_log_outPtr",
190
+ "anm_log_outLen",
191
+ "anm_log_diagCode",
192
+ "anm_log_parse",
193
+ "anm_log_encode",
194
+ "anm_log_window",
195
+ "anm_log_pointer",
196
+ "anm_log_pointerState",
197
+ "anm_log_recognise",
198
+ "memory",
199
+ ]) {
200
+ if (this.#e[name] === undefined) throw new LogError(`animader: missing export ${name}`);
201
+ }
202
+ }
203
+
204
+ /** The boundary ABI version (1). */
205
+ get abiVersion() {
206
+ return this.#e.animader_abiVersion();
207
+ }
208
+
209
+ #writeInput(bytes) {
210
+ const e = this.#e;
211
+ const cap = e.anm_log_inCap();
212
+ if (bytes.byteLength > cap) {
213
+ throw new LogError(
214
+ `animader: input is ${bytes.byteLength} bytes, over the ${cap}-byte input zone`,
215
+ { status: STATUS_BAD_CALL },
216
+ );
217
+ }
218
+ new Uint8Array(e.memory.buffer, e.anm_log_inPtr(), bytes.byteLength).set(bytes);
219
+ }
220
+
221
+ #output(len) {
222
+ return new Uint8Array(this.#e.memory.buffer, this.#e.anm_log_outPtr(), len).slice();
223
+ }
224
+
225
+ #check(status, what) {
226
+ if (status < 0) {
227
+ const message = status === STATUS_DIAGNOSTICS ? `${what}: the session has diagnostics` : `${what}: ${describeStatus(status)}`;
228
+ throw new LogError(`animader: ${message} (status ${status})`, { status });
229
+ }
230
+ return status;
231
+ }
232
+
233
+ /**
234
+ * Canonical session text in, 'ANEV' blob out. A clean parse caches the
235
+ * session the wasm module renders back in `encode`.
236
+ * @param {string} text
237
+ * @returns {Uint8Array}
238
+ */
239
+ parse(text) {
240
+ const bytes = encoder.encode(text);
241
+ this.#writeInput(bytes);
242
+ const status = this.#e.anm_log_parse(bytes.byteLength);
243
+ if (status === STATUS_DIAGNOSTICS) {
244
+ const raw = this.#e.anm_log_diagCode();
245
+ const code = raw === NO_CODE ? null : raw;
246
+ throw new LogError(
247
+ `animader: the session has diagnostics${code === null ? "" : ` (event-log code ${code})`}`,
248
+ { status, code },
249
+ );
250
+ }
251
+ this.#check(status, "parse");
252
+ return this.#output(status);
253
+ }
254
+
255
+ /**
256
+ * 'ANEV' blob in, the canonical text out, byte for byte, rendering the
257
+ * session cached by the last clean `parse`.
258
+ * @param {Uint8Array} blob
259
+ * @returns {string}
260
+ */
261
+ encode(blob) {
262
+ const bytes = toBytes(blob);
263
+ this.#writeInput(bytes);
264
+ const status = this.#e.anm_log_encode(bytes.byteLength);
265
+ this.#check(status, "encode");
266
+ return decoder.decode(this.#output(status));
267
+ }
268
+
269
+ /**
270
+ * 'ANEV' blob plus the half-open window [t0, t1) in, the window's blob
271
+ * out. The full original string table rides along.
272
+ * @param {Uint8Array} blob
273
+ * @param {number} t0
274
+ * @param {number} t1
275
+ * @returns {Uint8Array}
276
+ */
277
+ window(blob, t0, t1) {
278
+ const bytes = toBytes(blob);
279
+ const from = micros(t0, "t0");
280
+ const to = micros(t1, "t1");
281
+ this.#writeInput(bytes);
282
+ const status = this.#e.anm_log_window(bytes.byteLength, BigInt(from), BigInt(to));
283
+ this.#check(status, "window");
284
+ return this.#output(status);
285
+ }
286
+
287
+ /**
288
+ * 'ANEV' blob plus t / t_prev / a pointer id in, the twelve pngine
289
+ * lanes out (x, y, clickX, clickY, dx, dy, buttons, pressure,
290
+ * modifiers, scrollX, scrollY, pad).
291
+ * @param {Uint8Array} blob
292
+ * @param {number} t
293
+ * @param {number} tPrev
294
+ * @param {number} [ptr]
295
+ * @returns {Float32Array}
296
+ */
297
+ pointer(blob, t, tPrev, ptr = 0) {
298
+ const bytes = toBytes(blob);
299
+ const now = micros(t, "t");
300
+ const prev = micros(tPrev, "t_prev");
301
+ if (!Number.isInteger(ptr) || ptr < 0 || ptr > 255) {
302
+ throw new LogError(`animader: pointer id must be an integer 0..255, got ${ptr}`, {
303
+ status: STATUS_BAD_CALL,
304
+ });
305
+ }
306
+ this.#writeInput(bytes);
307
+ const status = this.#e.anm_log_pointer(bytes.byteLength, BigInt(now), BigInt(prev), ptr);
308
+ if (status !== 48) {
309
+ this.#check(status, "pointer");
310
+ throw new LogError(`animader: pointer answered ${status} bytes, expected 48`, {
311
+ status,
312
+ });
313
+ }
314
+ const out = this.#output(status);
315
+ return new Float32Array(out.buffer, out.byteOffset, 12);
316
+ }
317
+
318
+ /**
319
+ * 'ANEV' blob plus t / t_prev / a pointer id in, the pointer's folded
320
+ * state out: the `EventLog.PointerState` fields in declaration order,
321
+ * decoded from the boundary's 64-byte wire. `downAt` is null before the
322
+ * pointer's first down; `dx`/`dy` and the wheel and scroll sums are
323
+ * against `tPrev`. A pointer with no records in a blob that has records
324
+ * is the fresh state (present false, every lane zero), not an error.
325
+ * @param {Uint8Array} blob
326
+ * @param {number} t
327
+ * @param {number} tPrev
328
+ * @param {number} [ptr]
329
+ * @returns {{
330
+ * ptr: number, present: boolean, down: boolean, x: number, y: number,
331
+ * buttons: number, pressure: number, mods: number,
332
+ * downAt: number | null, downX: number, downY: number,
333
+ * clickTouched: boolean, dx: number, dy: number,
334
+ * wheelX: number, wheelY: number, scrollX: number, scrollY: number,
335
+ * }}
336
+ */
337
+ pointerState(blob, t, tPrev, ptr = 0) {
338
+ const bytes = toBytes(blob);
339
+ const now = micros(t, "t");
340
+ const prev = micros(tPrev, "t_prev");
341
+ if (!Number.isInteger(ptr) || ptr < 0 || ptr > 255) {
342
+ throw new LogError(`animader: pointer id must be an integer 0..255, got ${ptr}`, {
343
+ status: STATUS_BAD_CALL,
344
+ });
345
+ }
346
+ this.#writeInput(bytes);
347
+ const status = this.#e.anm_log_pointerState(bytes.byteLength, BigInt(now), BigInt(prev), ptr);
348
+ this.#check(status, "pointerState");
349
+ if (status !== POINTER_STATE_LEN) {
350
+ throw new LogError(
351
+ `animader: pointerState answered ${status} bytes, expected ${POINTER_STATE_LEN}`,
352
+ { status },
353
+ );
354
+ }
355
+ const out = this.#output(status);
356
+ // The offsets of the wire, pinned in src/wasm_entry.zig's header:
357
+ // 0 ptr, 1 present, 2 down, 4 x, 6 y, 8 buttons, 10 pressure,
358
+ // 12 mods, 13 down-at present, 16 down-at, 24 down-x, 26 down-y,
359
+ // 28 click-touched, 32 dx, 36 dy, 40 wheel-x, 48 wheel-y,
360
+ // 56 scroll-x, 60 scroll-y; 64 bytes total.
361
+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
362
+ return {
363
+ ptr: view.getUint8(0),
364
+ present: view.getUint8(1) !== 0,
365
+ down: view.getUint8(2) !== 0,
366
+ x: view.getUint16(4, true),
367
+ y: view.getUint16(6, true),
368
+ buttons: view.getUint8(8),
369
+ pressure: view.getUint16(10, true),
370
+ mods: view.getUint8(12),
371
+ downAt: view.getUint8(13) === 0 ? null : Number(view.getBigInt64(16, true)),
372
+ downX: view.getUint16(24, true),
373
+ downY: view.getUint16(26, true),
374
+ clickTouched: view.getUint8(28) !== 0,
375
+ dx: view.getInt32(32, true),
376
+ dy: view.getInt32(36, true),
377
+ wheelX: Number(view.getBigInt64(40, true)),
378
+ wheelY: Number(view.getBigInt64(48, true)),
379
+ scrollX: view.getInt32(56, true),
380
+ scrollY: view.getInt32(60, true),
381
+ };
382
+ }
383
+
384
+ /**
385
+ * 'ANEV' blob plus a pointer id in, the gestures the recognisers fold
386
+ * out of its records as an 'ANEV' blob out (derived records, never
387
+ * canonical text; `encode` refuses them). The output keeps the input's
388
+ * full string table, so a key press's `:code` index stays valid. A
389
+ * malformed blob, a blob with no records, or a pointer id above 255 is
390
+ * a bad call (status -2), never data.
391
+ * @param {Uint8Array} blob
392
+ * @param {number} [ptr]
393
+ * @returns {Uint8Array}
394
+ */
395
+ recognise(blob, ptr = 0) {
396
+ const bytes = toBytes(blob);
397
+ if (!Number.isInteger(ptr) || ptr < 0 || ptr > 255) {
398
+ throw new LogError(`animader: pointer id must be an integer 0..255, got ${ptr}`, {
399
+ status: STATUS_BAD_CALL,
400
+ });
401
+ }
402
+ this.#writeInput(bytes);
403
+ const status = this.#e.anm_log_recognise(bytes.byteLength, ptr);
404
+ this.#check(status, "recognise");
405
+ return this.#output(status);
406
+ }
407
+
408
+ /**
409
+ * Decode an 'ANEV' blob in JS. The record shape is the wire's:
410
+ * `{ at, kind, ptr, buttons, mods, x, y, p, str, v }`, with `kind` the
411
+ * string name, `str` the decoded string or null, and `v` three lanes.
412
+ * @param {Uint8Array} blob
413
+ * @returns {{ records: Array<object>, strings: string[] }}
414
+ */
415
+ decode(blob) {
416
+ const bytes = toBytes(blob);
417
+ if (bytes.byteLength < HEADER_LEN) {
418
+ throw new LogError(`animader: 'ANEV' blob is ${bytes.byteLength} bytes, under the 20-byte header`);
419
+ }
420
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
421
+ if (view.getUint32(0, true) !== MAGIC) throw new LogError("animader: 'ANEV' magic is missing");
422
+ if (view.getUint32(4, true) !== VERSION) {
423
+ throw new LogError(`animader: 'ANEV' version ${view.getUint32(4, true)} is not ${VERSION}`);
424
+ }
425
+ const count = view.getUint32(8, true);
426
+ const strtabLen = view.getUint32(12, true);
427
+ if (count > MAX_EVENTS) throw new LogError(`animader: 'ANEV' count ${count} over the ceiling`);
428
+ if (strtabLen > MAX_STRTAB) throw new LogError(`animader: 'ANEV' strtab ${strtabLen} over the ceiling`);
429
+ if (HEADER_LEN + count * RECORD_LEN + strtabLen !== bytes.byteLength) {
430
+ throw new LogError("animader: 'ANEV' length does not match its header");
431
+ }
432
+
433
+ const strings = decodeStrings(
434
+ bytes.subarray(HEADER_LEN + count * RECORD_LEN, bytes.byteLength),
435
+ );
436
+ const records = [];
437
+ for (let i = 0; i < count; i++) {
438
+ const o = HEADER_LEN + i * RECORD_LEN;
439
+ const kind = KINDS[view.getUint8(o + 8)];
440
+ if (kind === undefined) throw new LogError(`animader: 'ANEV' record kind ${view.getUint8(o + 8)} is not a Kind`);
441
+ const at = view.getBigInt64(o, true);
442
+ if (at < 0n || at > BigInt(MAX_SAFE)) {
443
+ throw new LogError(`animader: 'ANEV' record :at ${at} is outside the writer's 0..2^53-1 domain`);
444
+ }
445
+ const strRaw = view.getUint16(o + 18, true);
446
+ if (strRaw !== NO_CODE && strRaw >= strings.length) {
447
+ throw new LogError(`animader: 'ANEV' record string index ${strRaw} has no table entry`);
448
+ }
449
+ records.push({
450
+ at: Number(at),
451
+ kind,
452
+ ptr: view.getUint8(o + 9),
453
+ buttons: view.getUint8(o + 10),
454
+ mods: view.getUint8(o + 11),
455
+ x: view.getUint16(o + 12, true),
456
+ y: view.getUint16(o + 14, true),
457
+ p: view.getUint16(o + 16, true),
458
+ str: strRaw === NO_CODE ? null : strings[strRaw],
459
+ v: [view.getInt32(o + 20, true), view.getInt32(o + 24, true), view.getInt32(o + 28, true)],
460
+ });
461
+ }
462
+ return { records, strings };
463
+ }
464
+ }
465
+
466
+ // The machine tier (plan 02, phase 6): `Machine` over the machine exports,
467
+ // its decoders and its error type.
468
+ export {
469
+ Machine,
470
+ MachineError,
471
+ MACHINE_CODES,
472
+ decodeSnapshot,
473
+ decodeMeta,
474
+ decodeOutputs,
475
+ decodeDiags,
476
+ decodeEmits,
477
+ } from "./machine.js";
478
+
479
+ // The composed session tier (plan 03, phase 4): `Session` over one
480
+ // instance's machine and bridge exports, with the score and the consumer
481
+ // seams.
482
+ export { Session, SessionError, encodeTargets } from "./session.js";