@blockcast/fec-worker 0.1.0-main.0c300647d0a5

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.
Files changed (43) hide show
  1. package/README.md +213 -0
  2. package/dist/.build-stamp +0 -0
  3. package/dist/fec-worker-client.d.ts +80 -0
  4. package/dist/fec-worker-client.d.ts.map +1 -0
  5. package/dist/fec-worker-client.js +270 -0
  6. package/dist/fec-worker-client.js.map +1 -0
  7. package/dist/fec-worker-types.d.ts +252 -0
  8. package/dist/fec-worker-types.d.ts.map +1 -0
  9. package/dist/fec-worker-types.js +11 -0
  10. package/dist/fec-worker-types.js.map +1 -0
  11. package/dist/fec-worker.d.ts +14 -0
  12. package/dist/fec-worker.d.ts.map +1 -0
  13. package/dist/fec-worker.js +565 -0
  14. package/dist/fec-worker.js.map +7 -0
  15. package/dist/index.d.ts +10 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +8 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/shred-fec-worker.d.ts +20 -0
  20. package/dist/shred-fec-worker.d.ts.map +1 -0
  21. package/dist/shred-fec-worker.js +349 -0
  22. package/dist/shred-fec-worker.js.map +7 -0
  23. package/dist/shred-worker-client.d.ts +104 -0
  24. package/dist/shred-worker-client.d.ts.map +1 -0
  25. package/dist/shred-worker-client.js +181 -0
  26. package/dist/shred-worker-client.js.map +1 -0
  27. package/dist/shred-worker-types.d.ts +179 -0
  28. package/dist/shred-worker-types.d.ts.map +1 -0
  29. package/dist/shred-worker-types.js +47 -0
  30. package/dist/shred-worker-types.js.map +1 -0
  31. package/dist/transfer.d.ts +9 -0
  32. package/dist/transfer.d.ts.map +1 -0
  33. package/dist/transfer.js +13 -0
  34. package/dist/transfer.js.map +1 -0
  35. package/package.json +59 -0
  36. package/src/fec-worker-client.ts +309 -0
  37. package/src/fec-worker-types.ts +268 -0
  38. package/src/fec-worker.ts +1048 -0
  39. package/src/index.ts +32 -0
  40. package/src/shred-fec-worker.ts +558 -0
  41. package/src/shred-worker-client.ts +222 -0
  42. package/src/shred-worker-types.ts +194 -0
  43. package/src/transfer.ts +12 -0
@@ -0,0 +1,565 @@
1
+ // Self-contained worker bundle (no bare imports). See build.mjs.
2
+
3
+ // src/transfer.ts
4
+ function toOwnedArrayBuffer(view) {
5
+ const copy = new Uint8Array(view.byteLength);
6
+ copy.set(view);
7
+ return copy.buffer;
8
+ }
9
+
10
+ // src/fec-worker.ts
11
+ var wasmDecoder = null;
12
+ var config = null;
13
+ var altaEnabled = false;
14
+ var altaVerifier = null;
15
+ var snapshotTimer = null;
16
+ var blocks = /* @__PURE__ */ new Map();
17
+ var acceptedSourceEsis = /* @__PURE__ */ new Map();
18
+ var acceptedRepairEsis = /* @__PURE__ */ new Map();
19
+ var UINT32_MAX = 4294967295;
20
+ var UINT24_MAX = 16777215;
21
+ var MAX_INTERLEAVE_DEPTH = 255;
22
+ var MAX_SYMBOL_SIZE = 65528;
23
+ var MAX_RAPTORQ_SOURCE_SYMBOLS_PER_BLOCK = 56403;
24
+ var sourceSymbols = 0;
25
+ var repairSymbols = 0;
26
+ var blocksComplete = 0;
27
+ var blocksRecovered = 0;
28
+ var blocksFailed = 0;
29
+ var greenFillFrames = 0;
30
+ var altaVerified = 0;
31
+ var altaFailed = 0;
32
+ var altaFailedDetails = [];
33
+ var altaPending = 0;
34
+ var altaPendingEvictedCap = 0;
35
+ var altaPendingEvictedTtl = 0;
36
+ var altaError = 0;
37
+ var altaInitFailed = false;
38
+ var relayBlocksVerified = 0;
39
+ var relayBlocksFailed = 0;
40
+ var liveSbn = 0;
41
+ var retiredSbnFrontier = -1;
42
+ var repairSymbolSizeMismatch = 0;
43
+ var recoveryTimes = [];
44
+ var pendingVerify = /* @__PURE__ */ new Map();
45
+ var pendingVerifyCap = 0;
46
+ var pendingVerifyTtlMs = 0;
47
+ function emit(event, transfer) {
48
+ self.postMessage(event, transfer ?? []);
49
+ }
50
+ function isUint32(value) {
51
+ return Number.isInteger(value) && value >= 0 && value <= UINT32_MAX;
52
+ }
53
+ function isTerminalBlock(block) {
54
+ return block.state !== "collecting";
55
+ }
56
+ function retireAcceptedIds(sbn) {
57
+ acceptedSourceEsis.delete(sbn);
58
+ acceptedRepairEsis.delete(sbn);
59
+ }
60
+ function clearBlockTracking() {
61
+ blocks.clear();
62
+ acceptedSourceEsis.clear();
63
+ acceptedRepairEsis.clear();
64
+ pendingVerify.clear();
65
+ recoveryTimes.length = 0;
66
+ liveSbn = 0;
67
+ retiredSbnFrontier = -1;
68
+ }
69
+ function trimBlockRetention() {
70
+ for (const [sbn, block] of blocks) {
71
+ if (!isTerminalBlock(block) || sbn > retiredSbnFrontier) continue;
72
+ blocks.delete(sbn);
73
+ retireAcceptedIds(sbn);
74
+ }
75
+ }
76
+ function advanceMediaHorizon(sbn) {
77
+ if (!config || sbn <= liveSbn) return;
78
+ liveSbn = sbn;
79
+ const firstRetainedSbn = Math.max(0, liveSbn - config.interleaveDepth);
80
+ retiredSbnFrontier = Math.max(retiredSbnFrontier, firstRetainedSbn - 1);
81
+ trimBlockRetention();
82
+ }
83
+ function markBlockTerminal(block, state) {
84
+ block.state = state;
85
+ block.completedTs = performance.now();
86
+ retireAcceptedIds(block.sbn);
87
+ trimBlockRetention();
88
+ }
89
+ function synchronizeDecoderHorizon() {
90
+ if (!wasmDecoder) return;
91
+ const expired = wasmDecoder.cleanup_by_sbn(liveSbn);
92
+ for (const sbn of expired) {
93
+ const block = blocks.get(sbn);
94
+ if (!block || isTerminalBlock(block)) {
95
+ retireAcceptedIds(sbn);
96
+ continue;
97
+ }
98
+ markBlockTerminal(block, "failed");
99
+ blocksFailed++;
100
+ emitBlockUpdate(block);
101
+ }
102
+ trimBlockRetention();
103
+ }
104
+ function getOrCreateBlock(sbn) {
105
+ let block = blocks.get(sbn);
106
+ if (!block) {
107
+ if (!config) throw new Error("[FecWorker] not configured");
108
+ const now = performance.now();
109
+ block = {
110
+ sbn,
111
+ state: "collecting",
112
+ sourceReceived: 0,
113
+ repairReceived: 0,
114
+ k: config.k,
115
+ repairCount: config.repairCount,
116
+ firstSymbolTs: now,
117
+ lastSymbolTs: now,
118
+ deadlineTs: now + config.deliveryWindowMs,
119
+ altaVerified: 0,
120
+ relayBlockSigValid: null
121
+ };
122
+ blocks.set(sbn, block);
123
+ trimBlockRetention();
124
+ }
125
+ return block;
126
+ }
127
+ function buildStatsSnapshot() {
128
+ if (!config) throw new Error("[FecWorker] not configured");
129
+ const decoderStats = wasmDecoder?.get_stats();
130
+ const decoder = decoderStats ? {
131
+ sourcePackets: Number(decoderStats.source_packets),
132
+ repairPackets: Number(decoderStats.repair_packets),
133
+ blocksComplete: Number(decoderStats.blocks_complete),
134
+ blocksRecovered: Number(decoderStats.blocks_recovered),
135
+ blocksFailed: Number(decoderStats.blocks_failed),
136
+ bytesRecovered: Number(decoderStats.bytes_recovered),
137
+ pendingBlocks: wasmDecoder?.pending_blocks() ?? 0
138
+ } : void 0;
139
+ const avgRecoveryMs = recoveryTimes.length > 0 ? recoveryTimes.reduce((a, b) => a + b, 0) / recoveryTimes.length : 0;
140
+ const maxRecoveryMs = recoveryTimes.length > 0 ? Math.max(...recoveryTimes) : 0;
141
+ const maxBlocks = Math.max(config.interleaveDepth * 3, 24);
142
+ const blockArray = Array.from(blocks.values()).sort((a, b) => b.sbn - a.sbn).slice(0, maxBlocks);
143
+ return {
144
+ config,
145
+ sourceSymbols,
146
+ repairSymbols,
147
+ blocksComplete,
148
+ blocksRecovered,
149
+ blocksFailed,
150
+ greenFillFrames,
151
+ recoveryRate: blocksComplete + blocksRecovered > 0 ? Math.round(
152
+ blocksRecovered / (blocksRecovered + blocksFailed) * 100
153
+ ) || 0 : 0,
154
+ altaVerified,
155
+ altaFailed,
156
+ altaPending,
157
+ altaPendingEvictedCap,
158
+ altaPendingEvictedTtl,
159
+ altaError,
160
+ altaInitFailed,
161
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
162
+ altaFailedDetails: altaFailedDetails.slice(),
163
+ relayBlocksVerified,
164
+ relayBlocksFailed,
165
+ liveSbn,
166
+ blocks: blockArray,
167
+ interleaveWindowBlocks: config.interleaveDepth,
168
+ avgRecoveryMs: Math.round(avgRecoveryMs * 100) / 100,
169
+ maxRecoveryMs: Math.round(maxRecoveryMs * 100) / 100,
170
+ repairSymbolSizeMismatch,
171
+ decoder
172
+ };
173
+ }
174
+ function emitSnapshot() {
175
+ if (!config) return;
176
+ emit({ type: "snapshot", stats: buildStatsSnapshot() });
177
+ }
178
+ function emitBlockUpdate(block) {
179
+ emit({ type: "blockUpdate", block: { ...block } });
180
+ }
181
+ function emitRecoveredSymbols(sbn, recoveredBlock, block) {
182
+ if (!config) return;
183
+ const symbolSize = config.symbolSize;
184
+ if (symbolSize <= 0) {
185
+ emit({
186
+ type: "error",
187
+ code: "recovered-symbol-size-unconfigured",
188
+ message: "[FecWorker] recovered block has no configured symbolSize"
189
+ });
190
+ return;
191
+ }
192
+ if (recoveredBlock.byteLength < symbolSize * config.k) {
193
+ emit({
194
+ type: "error",
195
+ code: "recovered-block-too-short",
196
+ message: `[FecWorker] recovered block too short: got ${recoveredBlock.byteLength}B, expected at least ${symbolSize * config.k}B`
197
+ });
198
+ return;
199
+ }
200
+ for (let i = 0; i < config.k; i++) {
201
+ const symbol = recoveredBlock.subarray(i * symbolSize, (i + 1) * symbolSize);
202
+ const recoveredAltaVerified = null;
203
+ if (altaEnabled) altaPending++;
204
+ const buf = toOwnedArrayBuffer(symbol);
205
+ const meta = {
206
+ altaVerified: recoveredAltaVerified,
207
+ recovered: true,
208
+ sbn,
209
+ esi: i
210
+ };
211
+ emit({ type: "frame", data: buf, meta }, [buf]);
212
+ }
213
+ }
214
+ function startSnapshotTimer() {
215
+ if (snapshotTimer !== null) clearInterval(snapshotTimer);
216
+ snapshotTimer = setInterval(() => emitSnapshot(), 200);
217
+ }
218
+ function resolveWasmBindings() {
219
+ const bindings = self.__MMT_WASM_BINDINGS__;
220
+ if (!bindings) {
221
+ throw new Error(
222
+ "[FecWorker] WASM bindings not available. Set self.__MMT_WASM_BINDINGS__ = { initSync, MmtFecDecoder } before configure."
223
+ );
224
+ }
225
+ return bindings;
226
+ }
227
+ async function handleConfigure(cmd) {
228
+ if (!cmd.wasmModule) {
229
+ throw new Error("[FecWorker] configure: wasmModule required");
230
+ }
231
+ if (!cmd.config) {
232
+ throw new Error("[FecWorker] configure: config required");
233
+ }
234
+ if (!Number.isFinite(cmd.config.interleaveDepth) || !Number.isInteger(cmd.config.interleaveDepth) || cmd.config.interleaveDepth <= 0 || cmd.config.interleaveDepth > MAX_INTERLEAVE_DEPTH) {
235
+ throw new Error(
236
+ `[FecWorker] configure: interleaveDepth must be an integer in 1..${MAX_INTERLEAVE_DEPTH} (got ${cmd.config.interleaveDepth})`
237
+ );
238
+ }
239
+ if (!Number.isFinite(cmd.config.interleaveMs) || cmd.config.interleaveMs <= 0) {
240
+ throw new Error(
241
+ `[FecWorker] configure: interleaveMs must be finite and > 0 (got ${cmd.config.interleaveMs})`
242
+ );
243
+ }
244
+ if (!Number.isFinite(cmd.config.deliveryWindowMs) || cmd.config.deliveryWindowMs <= 0) {
245
+ throw new Error(
246
+ `[FecWorker] configure: deliveryWindowMs must be > 0 (got ${cmd.config.deliveryWindowMs})`
247
+ );
248
+ }
249
+ if (!Number.isInteger(cmd.config.k) || cmd.config.k <= 0 || cmd.config.k > MAX_RAPTORQ_SOURCE_SYMBOLS_PER_BLOCK) {
250
+ throw new Error(
251
+ `[FecWorker] configure: k must be an integer in 1..${MAX_RAPTORQ_SOURCE_SYMBOLS_PER_BLOCK} (got ${cmd.config.k})`
252
+ );
253
+ }
254
+ if (!Number.isInteger(cmd.config.symbolSize) || cmd.config.symbolSize <= 0 || cmd.config.symbolSize > MAX_SYMBOL_SIZE || cmd.config.symbolSize % 8 !== 0) {
255
+ throw new Error(
256
+ `[FecWorker] configure: symbolSize must be an 8-byte-aligned integer in 8..${MAX_SYMBOL_SIZE} (got ${cmd.config.symbolSize})`
257
+ );
258
+ }
259
+ const wasm = resolveWasmBindings();
260
+ wasm.initSync({ module: cmd.wasmModule });
261
+ wasmDecoder?.free();
262
+ wasmDecoder = null;
263
+ clearBlockTracking();
264
+ wasmDecoder = new wasm.MmtFecDecoder(
265
+ cmd.config.interleaveDepth,
266
+ cmd.config.trackType === "video"
267
+ );
268
+ config = cmd.config;
269
+ altaEnabled = !!cmd.altaPublicKey;
270
+ pendingVerifyCap = Math.ceil(config.interleaveDepth * 1.5);
271
+ pendingVerifyTtlMs = Math.ceil(config.interleaveMs * config.k * 1.5);
272
+ altaVerifier = null;
273
+ altaInitFailed = false;
274
+ if (cmd.altaPublicKey && cmd.altaWasmModule) {
275
+ try {
276
+ const altaGlueUrl = "/wasm/alta/alta_rs.js";
277
+ const altaGlue = await import(
278
+ /* webpackIgnore: true */
279
+ altaGlueUrl
280
+ );
281
+ altaGlue.initSync({ module: cmd.altaWasmModule });
282
+ const keyBytes = new Uint8Array(cmd.altaPublicKey);
283
+ altaVerifier = new altaGlue.JsAltaVerifier(keyBytes);
284
+ } catch (e) {
285
+ console.warn("[FecWorker] ALTA WASM init failed, verification disabled:", e);
286
+ altaVerifier = null;
287
+ altaEnabled = false;
288
+ altaInitFailed = true;
289
+ }
290
+ }
291
+ wasmDecoder.configure_params(config.k, config.symbolSize);
292
+ startSnapshotTimer();
293
+ emitSnapshot();
294
+ }
295
+ function handleFeedSource(cmd) {
296
+ if (!wasmDecoder) {
297
+ throw new Error("[FecWorker] feedSource: not configured");
298
+ }
299
+ if (!config) {
300
+ throw new Error("[FecWorker] feedSource: config missing");
301
+ }
302
+ if (!isUint32(cmd.ssId) || !(cmd.data instanceof ArrayBuffer)) {
303
+ throw new Error("[FecWorker] feedSource: invalid source symbol");
304
+ }
305
+ const view = new Uint8Array(cmd.data);
306
+ const sbn = config.k > 0 ? Math.floor(cmd.ssId / config.k) : cmd.ssId;
307
+ const esi = cmd.ssId % config.k;
308
+ if (sbn <= retiredSbnFrontier) return;
309
+ const existingBlock = blocks.get(sbn);
310
+ if (existingBlock && isTerminalBlock(existingBlock)) return;
311
+ if (acceptedSourceEsis.get(sbn)?.has(esi)) return;
312
+ const result = wasmDecoder.add_source(cmd.ssId, view, cmd.ts);
313
+ advanceMediaHorizon(sbn);
314
+ let sourceEsis = acceptedSourceEsis.get(sbn);
315
+ if (!sourceEsis) {
316
+ sourceEsis = /* @__PURE__ */ new Set();
317
+ acceptedSourceEsis.set(sbn, sourceEsis);
318
+ }
319
+ sourceEsis.add(esi);
320
+ const block = getOrCreateBlock(sbn);
321
+ block.sourceReceived++;
322
+ block.lastSymbolTs = performance.now();
323
+ sourceSymbols++;
324
+ if (altaEnabled) altaPending++;
325
+ if (block.sourceReceived >= block.k && block.state === "collecting") {
326
+ markBlockTerminal(block, "complete");
327
+ blocksComplete++;
328
+ emitBlockUpdate(block);
329
+ }
330
+ if (result && result.byteLength > 0 && block.sourceReceived < block.k) {
331
+ const recovered = new Uint8Array(toOwnedArrayBuffer(result));
332
+ const recoveryMs = performance.now() - block.firstSymbolTs;
333
+ recoveryTimes.push(recoveryMs);
334
+ if (recoveryTimes.length > 1e3) recoveryTimes.shift();
335
+ if (block.state === "collecting") {
336
+ markBlockTerminal(block, "recovered");
337
+ blocksRecovered++;
338
+ emitBlockUpdate(block);
339
+ }
340
+ emitRecoveredSymbols(sbn, recovered, block);
341
+ }
342
+ synchronizeDecoderHorizon();
343
+ }
344
+ function handleFeedRepair(cmd) {
345
+ if (!wasmDecoder) {
346
+ throw new Error("[FecWorker] feedRepair: not configured");
347
+ }
348
+ if (!config) {
349
+ throw new Error("[FecWorker] feedRepair: config missing");
350
+ }
351
+ if (!isUint32(cmd.ssStart) || !isUint32(cmd.ssbLength) || cmd.ssbLength <= 0 || cmd.ssbLength !== config.k || cmd.ssStart % cmd.ssbLength !== 0 || !isUint32(cmd.rsId) || cmd.ssbLength + cmd.rsId > UINT24_MAX || !(cmd.data instanceof ArrayBuffer)) {
352
+ throw new Error("[FecWorker] feedRepair: invalid repair symbol");
353
+ }
354
+ const view = new Uint8Array(cmd.data);
355
+ if (config.symbolSize > 0 && view.byteLength !== config.symbolSize) {
356
+ repairSymbolSizeMismatch++;
357
+ if (repairSymbolSizeMismatch <= 5 || repairSymbolSizeMismatch % 100 === 0) {
358
+ emit({
359
+ type: "error",
360
+ code: "repair-symbol-size-mismatch",
361
+ message: `[FecWorker] Dropping repair symbol with invalid size: got ${view.byteLength}B, expected ${config.symbolSize}B (ssStart=${cmd.ssStart}, ssbLength=${cmd.ssbLength}, rsId=${cmd.rsId})`
362
+ });
363
+ }
364
+ return;
365
+ }
366
+ const sbn = Math.floor(cmd.ssStart / cmd.ssbLength);
367
+ const repairEsi = cmd.ssbLength + cmd.rsId;
368
+ if (sbn <= retiredSbnFrontier) return;
369
+ const existingBlock = blocks.get(sbn);
370
+ if (existingBlock && isTerminalBlock(existingBlock)) return;
371
+ if (acceptedRepairEsis.get(sbn)?.has(repairEsi)) return;
372
+ const result = wasmDecoder.add_repair(
373
+ cmd.ssStart,
374
+ cmd.ssbLength,
375
+ cmd.rsId,
376
+ view,
377
+ cmd.ts
378
+ );
379
+ advanceMediaHorizon(sbn);
380
+ let repairEsis = acceptedRepairEsis.get(sbn);
381
+ if (!repairEsis) {
382
+ repairEsis = /* @__PURE__ */ new Set();
383
+ acceptedRepairEsis.set(sbn, repairEsis);
384
+ }
385
+ repairEsis.add(repairEsi);
386
+ const block = getOrCreateBlock(sbn);
387
+ block.repairReceived++;
388
+ block.lastSymbolTs = performance.now();
389
+ repairSymbols++;
390
+ if (result && result.byteLength > 0) {
391
+ const recovered = new Uint8Array(toOwnedArrayBuffer(result));
392
+ const recoveryMs = performance.now() - block.firstSymbolTs;
393
+ recoveryTimes.push(recoveryMs);
394
+ if (recoveryTimes.length > 1e3) recoveryTimes.shift();
395
+ if (block.state === "collecting") {
396
+ markBlockTerminal(block, "recovered");
397
+ blocksRecovered++;
398
+ emitBlockUpdate(block);
399
+ }
400
+ emitRecoveredSymbols(sbn, recovered, block);
401
+ }
402
+ synchronizeDecoderHorizon();
403
+ }
404
+ function handleRelayBlockSig(cmd) {
405
+ const block = blocks.get(cmd.sbn);
406
+ if (block) {
407
+ block.relayBlockSigValid = null;
408
+ emitBlockUpdate(block);
409
+ }
410
+ }
411
+ function handleCleanup(cmd) {
412
+ if (!Array.isArray(cmd.sbns) || cmd.sbns.length === 0 || !cmd.sbns.every(isUint32)) {
413
+ throw new Error("[FecWorker] cleanup: invalid SBNs");
414
+ }
415
+ const sbns = [...new Set(cmd.sbns)].sort((a, b) => a - b);
416
+ const pendingSbns = sbns.filter((sbn) => sbn > retiredSbnFrontier);
417
+ try {
418
+ if (!wasmDecoder) {
419
+ throw new Error("[FecWorker] cleanup: not configured");
420
+ }
421
+ const cleanupRecords = pendingSbns.length > 0 ? wasmDecoder.cleanup_blocks_detailed(Uint32Array.from(pendingSbns)) : new Uint8Array();
422
+ for (const sbn of pendingSbns) {
423
+ let currentBlock = blocks.get(sbn);
424
+ if (currentBlock && isTerminalBlock(currentBlock)) {
425
+ retireAcceptedIds(sbn);
426
+ continue;
427
+ }
428
+ currentBlock ?? (currentBlock = getOrCreateBlock(sbn));
429
+ if (currentBlock.sourceReceived >= currentBlock.k) {
430
+ markBlockTerminal(currentBlock, "complete");
431
+ blocksComplete++;
432
+ } else {
433
+ markBlockTerminal(currentBlock, "failed");
434
+ blocksFailed++;
435
+ }
436
+ emitBlockUpdate(currentBlock);
437
+ }
438
+ const greenFills = decodeCleanupRecords(cleanupRecords);
439
+ for (const { sbn, data } of greenFills) {
440
+ greenFillFrames++;
441
+ emit({ type: "greenFill", sbn, data }, [data]);
442
+ }
443
+ } finally {
444
+ emit({ type: "cleanupComplete", sbns });
445
+ }
446
+ }
447
+ function decodeCleanupRecords(framed) {
448
+ const records = [];
449
+ const view = new DataView(framed.buffer, framed.byteOffset, framed.byteLength);
450
+ let offset = 0;
451
+ while (offset < framed.byteLength) {
452
+ if (framed.byteLength - offset < 8) {
453
+ throw new Error("[FecWorker] cleanup_blocks_detailed: truncated record header");
454
+ }
455
+ const sbn = view.getUint32(offset, false);
456
+ const length = view.getUint32(offset + 4, false);
457
+ offset += 8;
458
+ if (length > framed.byteLength - offset) {
459
+ throw new Error("[FecWorker] cleanup_blocks_detailed: truncated record payload");
460
+ }
461
+ const data = toOwnedArrayBuffer(framed.subarray(offset, offset + length));
462
+ records.push({ sbn, data });
463
+ offset += length;
464
+ }
465
+ return records;
466
+ }
467
+ function handleDispose() {
468
+ if (snapshotTimer !== null) {
469
+ clearInterval(snapshotTimer);
470
+ snapshotTimer = null;
471
+ }
472
+ if (altaVerifier) {
473
+ try {
474
+ altaVerifier.free();
475
+ } catch (_e) {
476
+ }
477
+ altaVerifier = null;
478
+ }
479
+ if (wasmDecoder) {
480
+ wasmDecoder.free();
481
+ wasmDecoder = null;
482
+ }
483
+ pendingVerify.clear();
484
+ pendingVerifyCap = 0;
485
+ pendingVerifyTtlMs = 0;
486
+ config = null;
487
+ clearBlockTracking();
488
+ }
489
+ function handleReset() {
490
+ try {
491
+ wasmDecoder?.flush();
492
+ wasmDecoder?.reset_stats();
493
+ } catch (err) {
494
+ emit({
495
+ type: "error",
496
+ code: "reset-failed",
497
+ message: err instanceof Error ? `[FecWorker] reset failed: ${err.message}` : `[FecWorker] reset failed: ${String(err)}`
498
+ });
499
+ return;
500
+ }
501
+ clearBlockTracking();
502
+ sourceSymbols = 0;
503
+ repairSymbols = 0;
504
+ blocksComplete = 0;
505
+ blocksRecovered = 0;
506
+ blocksFailed = 0;
507
+ greenFillFrames = 0;
508
+ altaVerified = 0;
509
+ altaFailed = 0;
510
+ altaFailedDetails.length = 0;
511
+ altaPending = 0;
512
+ altaPendingEvictedCap = 0;
513
+ altaPendingEvictedTtl = 0;
514
+ altaError = 0;
515
+ relayBlocksVerified = 0;
516
+ relayBlocksFailed = 0;
517
+ repairSymbolSizeMismatch = 0;
518
+ emit({ type: "resetComplete" });
519
+ if (config) emitSnapshot();
520
+ }
521
+ async function dispatchCommand(cmd) {
522
+ try {
523
+ switch (cmd.type) {
524
+ case "configure":
525
+ await handleConfigure(cmd);
526
+ break;
527
+ case "feedSource":
528
+ handleFeedSource(cmd);
529
+ break;
530
+ case "feedRepair":
531
+ handleFeedRepair(cmd);
532
+ break;
533
+ case "relayBlockSig":
534
+ handleRelayBlockSig(cmd);
535
+ break;
536
+ case "cleanup":
537
+ handleCleanup(cmd);
538
+ break;
539
+ case "reset":
540
+ handleReset();
541
+ break;
542
+ case "dispose":
543
+ handleDispose();
544
+ break;
545
+ default:
546
+ emit({
547
+ type: "error",
548
+ code: "unknown-command",
549
+ message: `Unknown command type: ${cmd.type}`
550
+ });
551
+ }
552
+ } catch (err) {
553
+ emit({
554
+ type: "error",
555
+ code: "command-failed",
556
+ message: err instanceof Error ? err.message : `[FecWorker] ${String(err)}`
557
+ });
558
+ }
559
+ }
560
+ var commandQueue = Promise.resolve();
561
+ self.onmessage = (e) => {
562
+ const cmd = e.data;
563
+ commandQueue = commandQueue.then(() => dispatchCommand(cmd));
564
+ };
565
+ //# sourceMappingURL=fec-worker.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/transfer.ts", "../src/fec-worker.ts"],
4
+ "sourcesContent": ["/**\n * Return a fresh ArrayBuffer containing exactly the bytes in `view`.\n *\n * Worker outputs must not transfer buffers that might be owned by a WASM\n * binding or by a larger shared packet. A fresh JS-owned buffer gives\n * postMessage() exclusive ownership without detaching unrelated memory.\n */\nexport function toOwnedArrayBuffer(view: Uint8Array): ArrayBuffer {\n\tconst copy = new Uint8Array(view.byteLength);\n\tcopy.set(view);\n\treturn copy.buffer;\n}\n", "/**\n * @blockcast/fec-worker \u2014 Worker Entry Point\n *\n * Runs inside DedicatedWorkerGlobalScope. Receives FecWorkerCommand messages,\n * drives the MmtFecDecoder WASM module, emits FecWorkerEvent messages back.\n *\n * WASM bindings are resolved via:\n * 1. (self as any).__MMT_WASM_BINDINGS__ \u2014 set by consumer's loader/importmap\n * 2. Falls back to error if not available (no defaults)\n *\n * This file must NOT import DOM globals incompatible with Worker scope.\n */\n\nimport type {\n\tFecWorkerCommand,\n\tFecWorkerEvent,\n\tFecTrackConfig,\n\tFecTrackStats,\n\tFecBlockSnapshot,\n\tFrameMeta,\n} from \"./fec-worker-types.js\";\nimport { toOwnedArrayBuffer } from \"./transfer.js\";\n\n// --- WASM binding types (from mmt-wasm) ---\n// Signatures MUST match a freshly generated external mmt_wasm.d.ts exactly.\n// The decoder derives SBN/ESI internally \u2014 do not pre-compute.\ninterface WasmFecDecoder {\n\t/** ISO 23008-1 \u00A7C.5.2: ss_id is the flat 32-bit Source Symbol ID. */\n\tadd_source(\n\t\tss_id: number,\n\t\tdata: Uint8Array,\n\t\ttimestamp: number,\n\t): Uint8Array | undefined;\n\t/** ISO 23008-1 \u00A7C.5.3: repair ESI = ssb_length + rs_id, SBN = ss_start / ssb_length. */\n\tadd_repair(\n\t\tss_start: number,\n\t\tssb_length: number,\n\t\trs_id: number,\n\t\tdata: Uint8Array,\n\t\ttimestamp: number,\n\t): Uint8Array | undefined;\n\tconfigure_params(k: number, symbolSize: number): void;\n\t/** Block-scoped counterpart driven by the manager's exact deadlines. */\n\tcleanup_blocks_detailed(sbns: Uint32Array): Uint8Array;\n\t/** Remove decoder blocks below its configured live-SBN interleave horizon. */\n\tcleanup_by_sbn(current_sbn: number): Uint32Array;\n\tflush(): void;\n\tpending_blocks(): number;\n\treset_stats(): void;\n\tget_stats(): {\n\t\tsource_packets: bigint;\n\t\trepair_packets: bigint;\n\t\tblocks_complete: bigint;\n\t\tblocks_recovered: bigint;\n\t\tblocks_failed: bigint;\n\t\tbytes_recovered: bigint;\n\t\trecovery_rate(): number;\n\t};\n\tfree(): void;\n}\n\ninterface WasmBindings {\n\tinitSync(module: { module: WebAssembly.Module }): unknown;\n\tMmtFecDecoder: new (\n\t\tinterleaveDepth: number,\n\t\tgreenFillEnabled: boolean,\n\t) => WasmFecDecoder;\n}\n\n// --- Worker state (local to this Worker instance) ---\n\nlet wasmDecoder: WasmFecDecoder | null = null;\nlet config: FecTrackConfig | null = null;\nlet altaEnabled = false;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet altaVerifier: any = null; // JsAltaVerifier instance (loaded from ALTA WASM)\nlet snapshotTimer: ReturnType<typeof setInterval> | null = null;\n\n// Block tracking\nconst blocks = new Map<number, FecBlockSnapshot>();\nconst acceptedSourceEsis = new Map<number, Set<number>>();\nconst acceptedRepairEsis = new Map<number, Set<number>>();\nconst UINT32_MAX = 0xffff_ffff;\nconst UINT24_MAX = 0xff_ffff;\n// ISO/IEC 23008-1 AL-FEC signaling carries interleave_depth in one byte.\nconst MAX_INTERLEAVE_DEPTH = 0xff;\n// Rust stores T as u16 and this decoder profile fixes RFC 6330 Al=8.\nconst MAX_SYMBOL_SIZE = 0xfff8;\n// RFC 6330 systematic table limit, enforced by the vendored raptorq decoder.\nconst MAX_RAPTORQ_SOURCE_SYMBOLS_PER_BLOCK = 56_403;\n\n// Aggregate counters\nlet sourceSymbols = 0;\nlet repairSymbols = 0;\nlet blocksComplete = 0;\nlet blocksRecovered = 0;\nlet blocksFailed = 0;\nlet greenFillFrames = 0;\nlet altaVerified = 0;\nlet altaFailed = 0; // Crypto-confirmed tamper (MAC / sig / hash chain mismatch)\nconst altaFailedDetails: Array<{\n\tseq: number;\n\terror: string;\n\tauthLen: number;\n\tpayloadLen: number;\n\tpath: string; // \"direct\" | \"recovered\" | \"pending-retry\"\n}> = [];\nlet altaPending = 0; // Unverifiable but not tamper (no trailer, verifier not ready, anchor missing)\nlet altaPendingEvictedCap = 0; // Incoming \"pending\" packets rejected because the queue was at cap after stale-sweep (flood indicator)\nlet altaPendingEvictedTtl = 0; // Deferred-queue entries dropped by TTL (retry window expired)\nlet altaError = 0; // verifyDetached threw \u2014 infrastructure flake, not tamper\nlet altaInitFailed = false; // ALTA configured but WASM init failed; altaEnabled was forced off\nlet relayBlocksVerified = 0;\nlet relayBlocksFailed = 0;\nlet liveSbn = 0;\n// Highest SBN that has fallen strictly below the decoder's retained\n// interleave window. Numeric ordering is per decoder epoch; reset/configure\n// starts a new epoch before the 32-bit source-symbol counter can wrap.\nlet retiredSbnFrontier = -1;\nlet repairSymbolSizeMismatch = 0;\n\n// Recovery timing\nconst recoveryTimes: number[] = [];\n\n// \u2500\u2500 Deferred ALTA verification queue (08-07 Path 3) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// When an ALTA packet arrives whose MAC references point at sequences not yet\n// in the verifier's ring buffer, we can't anchor trust \u2014 verify returns \"No\n// trust anchor\". Typical cause: a predecessor packet was lost and hasn't been\n// FEC-recovered yet. Rather than drop these, hold them in a bounded FIFO and\n// retry verification after every successful verify (direct or FEC-recovered)\n// that seeds the ring buffer with new raw bytes.\n//\n// Zero-copy (1B-B): the queue entry stores a Uint8Array view into the\n// original `data` ArrayBuffer. JS GC keeps the buffer alive via the view\n// reference; no bytes are copied on queue.\n//\n// Timeout entries (TTL exceeded) and cap-rejections count as `altaPending`\n// (2C-B): they're not tamper indicators, they're just packets that couldn't\n// be authenticated within the receive window \u2014 either loss or, in the cap\n// case, a flood of unanchorable arrivals (real or attacker-driven) that\n// exceeded the queue budget. See enqueuePendingVerify for the rate-limit\n// protocol.\ninterface PendingVerify {\n\tseq: number;\n\tauth: Uint8Array;\n\tpayload: Uint8Array;\n\tarrivalTs: number;\n}\nconst pendingVerify = new Map<number, PendingVerify>();\nlet pendingVerifyCap = 0;\nlet pendingVerifyTtlMs = 0;\n\n// --- Helpers ---\n\nfunction emit(event: FecWorkerEvent, transfer?: Transferable[]): void {\n\tself.postMessage(event, transfer ?? []);\n}\n\nfunction isUint32(value: number): boolean {\n\treturn Number.isInteger(value) && value >= 0 && value <= UINT32_MAX;\n}\n\nfunction isTerminalBlock(block: FecBlockSnapshot): boolean {\n\treturn block.state !== \"collecting\";\n}\n\nfunction retireAcceptedIds(sbn: number): void {\n\tacceptedSourceEsis.delete(sbn);\n\tacceptedRepairEsis.delete(sbn);\n}\n\nfunction clearBlockTracking(): void {\n\tblocks.clear();\n\tacceptedSourceEsis.clear();\n\tacceptedRepairEsis.clear();\n\tpendingVerify.clear();\n\trecoveryTimes.length = 0;\n\tliveSbn = 0;\n\tretiredSbnFrontier = -1;\n}\n\n/**\n * Retire terminal diagnostics only after the decoder's monotonic interleave\n * horizon proves that the SBN can no longer be valid out-of-order media.\n * Admission keeps the compact frontier as the durable tombstone, so deletion\n * never reopens a finalized block.\n */\nfunction trimBlockRetention(): void {\n\tfor (const [sbn, block] of blocks) {\n\t\tif (!isTerminalBlock(block) || sbn > retiredSbnFrontier) continue;\n\t\tblocks.delete(sbn);\n\t\tretireAcceptedIds(sbn);\n\t}\n}\n\nfunction advanceMediaHorizon(sbn: number): void {\n\tif (!config || sbn <= liveSbn) return;\n\tliveSbn = sbn;\n\tconst firstRetainedSbn = Math.max(0, liveSbn - config.interleaveDepth);\n\tretiredSbnFrontier = Math.max(retiredSbnFrontier, firstRetainedSbn - 1);\n\ttrimBlockRetention();\n}\n\nfunction markBlockTerminal(\n\tblock: FecBlockSnapshot,\n\tstate: \"complete\" | \"recovered\" | \"failed\",\n): void {\n\tblock.state = state;\n\tblock.completedTs = performance.now();\n\tretireAcceptedIds(block.sbn);\n\ttrimBlockRetention();\n}\n\nfunction synchronizeDecoderHorizon(): void {\n\tif (!wasmDecoder) return;\n\tconst expired = wasmDecoder.cleanup_by_sbn(liveSbn);\n\tfor (const sbn of expired) {\n\t\tconst block = blocks.get(sbn);\n\t\tif (!block || isTerminalBlock(block)) {\n\t\t\tretireAcceptedIds(sbn);\n\t\t\tcontinue;\n\t\t}\n\t\tmarkBlockTerminal(block, \"failed\");\n\t\tblocksFailed++;\n\t\temitBlockUpdate(block);\n\t}\n\ttrimBlockRetention();\n}\n\n/**\n * Run detached ALTA verify against the current verifier. Four-state result:\n * - \"valid\": crypto passed, packet authentic. Caller increments altaVerified.\n * - \"failed\": crypto confirmed tamper (MAC/sig mismatch, hash chain mismatch).\n * Caller increments altaFailed. Not retryable.\n * - \"pending\": anchor missing (MAC refs not in buffer, no signature, not\n * early-warmup). Caller may enqueue for retry after the next\n * successful verify seeds the ring buffer.\n * - \"error\": verifier threw \u2014 WASM trap, unmarshal panic, OOM. Caller\n * increments altaError (infrastructure flake, not tamper).\n * The distinction matters for ops alerting: a spike in\n * altaError indicates a runtime problem, not an attack.\n */\nlet _lastVerifyError = \"\";\nfunction runDetachedVerify(\n\tauth: Uint8Array,\n\tpayload: Uint8Array,\n): \"valid\" | \"failed\" | \"pending\" | \"error\" {\n\tif (!altaVerifier) return \"pending\";\n\ttry {\n\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\tconst r: any = altaVerifier.verifyDetached(auth, payload);\n\t\tif (r.valid) {\n\t\t\t_lastVerifyError = \"\";\n\t\t\treturn \"valid\";\n\t\t}\n\t\tconst err = (r.error as string | undefined) ?? \"\";\n\t\t_lastVerifyError = err;\n\t\t// The bootstrap-friendly verifier returns this specific error string when\n\t\t// the only obstacle to verification is a missing anchor (see alta-rs\n\t\t// verifier.rs verify()). Distinguishing this from tamper cases keeps us\n\t\t// from queuing packets that are definitively invalid.\n\t\tif (err.startsWith(\"No trust anchor\")) return \"pending\";\n\t\treturn \"failed\";\n\t} catch (e) {\n\t\t// Ratelimit: first ~N occurrences get logged. A sustained exception\n\t\t// stream indicates a real problem \u2014 the altaError counter is the\n\t\t// durable signal.\n\t\tif (altaError < 5) {\n\t\t\tconsole.warn(\"[FecWorker] verifyDetached threw:\", e);\n\t\t}\n\t\treturn \"error\";\n\t}\n}\n\n/** Extract u32 BE sequence number from the ALTA authenticator header (offset 0..3). */\nfunction seqFromAuth(auth: Uint8Array): number {\n\treturn (\n\t\t((auth[0]! << 24) | (auth[1]! << 16) | (auth[2]! << 8) | auth[3]!) >>> 0\n\t);\n}\n\n/**\n * Enqueue a packet whose ALTA verification returned \"pending\" (anchor\n * missing). Dedupes by sequence number.\n *\n * Flood resistance (08-08 review): when the queue is at cap we do NOT\n * evict the oldest entry. The oldest entry is typically the most\n * load-bearing one \u2014 it's the packet whose anchor everything else in the\n * queue is waiting on. Evict-oldest-on-insert let an attacker emitting a\n * stream of \"No trust anchor\" packets flood out legitimate entries and\n * prevent them from ever anchoring. Instead:\n * 1. First try to free stale TTL'd entries (they'd be evicted on next\n * drain anyway \u2014 pulling that forward is free).\n * 2. If still full, reject the NEW entry. altaPendingEvictedCap counts\n * these rejections (rate-limit trigger).\n *\n * Stores Uint8Array views into the original data + auth buffers \u2014 no copy.\n * The views keep their underlying ArrayBuffers alive via GC references.\n */\nfunction enqueuePendingVerify(\n\tauth: Uint8Array,\n\tpayload: Uint8Array,\n): void {\n\tconst seq = seqFromAuth(auth);\n\tif (pendingVerify.has(seq)) return;\n\n\tif (pendingVerify.size >= pendingVerifyCap) {\n\t\t// Step 1: sweep stale entries so legitimate traffic isn't penalized\n\t\t// by TTL'd junk that happens to still occupy slots.\n\t\tconst now = performance.now();\n\t\tfor (const [staleSeq, entry] of pendingVerify) {\n\t\t\tif (now - entry.arrivalTs > pendingVerifyTtlMs) {\n\t\t\t\tpendingVerify.delete(staleSeq);\n\t\t\t\taltaPendingEvictedTtl++;\n\t\t\t}\n\t\t}\n\t\t// Step 2: if the queue is still at cap it's a genuine flood \u2014\n\t\t// reject the new entry rather than evict an existing one. The\n\t\t// rejected packet counts as altaPendingEvictedCap (which is\n\t\t// surfaced up through stats for rate-limit alerting).\n\t\tif (pendingVerify.size >= pendingVerifyCap) {\n\t\t\taltaPendingEvictedCap++;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tpendingVerify.set(seq, {\n\t\tseq,\n\t\tauth,\n\t\tpayload,\n\t\tarrivalTs: performance.now(),\n\t});\n}\n\n/**\n * Retry every queued entry. Called after every successful verify (direct\n * source or FEC-recovered) \u2014 new raw bytes in the verifier's ring buffer may\n * unblock previously-pending MAC references.\n *\n * Three outcomes per entry:\n * - \"valid\" \u2192 remove from queue, altaVerified++\n * - \"failed\" \u2192 remove from queue, altaFailed++ (tamper on retry)\n * - \"pending\" \u2192 keep in queue, unless TTL expired (then evict as altaPending)\n *\n * Iteration order: Map preserves insertion order, so we drain oldest-first.\n * No-op when the queue is empty or the verifier isn't ready.\n */\nfunction drainPendingVerify(): void {\n\tif (pendingVerify.size === 0 || !altaVerifier) return;\n\tconst now = performance.now();\n\t// Collect keys to avoid mutating Map during iteration\n\tconst keys = Array.from(pendingVerify.keys());\n\tfor (const seq of keys) {\n\t\tconst entry = pendingVerify.get(seq);\n\t\tif (!entry) continue;\n\t\tif (now - entry.arrivalTs > pendingVerifyTtlMs) {\n\t\t\tpendingVerify.delete(seq);\n\t\t\taltaPendingEvictedTtl++;\n\t\t\tcontinue;\n\t\t}\n\t\tconst result = runDetachedVerify(entry.auth, entry.payload);\n\t\tif (result === \"valid\") {\n\t\t\tpendingVerify.delete(seq);\n\t\t\taltaVerified++;\n\t\t} else if (result === \"failed\") {\n\t\t\tpendingVerify.delete(seq);\n\t\t\taltaFailed++;\n\t\t\tif (altaFailedDetails.length < 16) {\n\t\t\t\taltaFailedDetails.push({\n\t\t\t\t\tseq: entry.seq,\n\t\t\t\t\terror: _lastVerifyError,\n\t\t\t\t\tauthLen: entry.auth.length,\n\t\t\t\t\tpayloadLen: entry.payload.length,\n\t\t\t\t\tpath: \"pending-retry\",\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (result === \"error\") {\n\t\t\t// Infrastructure failure \u2014 remove from queue, count as altaError.\n\t\t\t// Keeping it around would just re-throw on every subsequent drain.\n\t\t\tpendingVerify.delete(seq);\n\t\t\taltaError++;\n\t\t}\n\t\t// \"pending\" \u2192 leave in queue for next drain\n\t}\n}\n\nfunction getOrCreateBlock(sbn: number): FecBlockSnapshot {\n\tlet block = blocks.get(sbn);\n\tif (!block) {\n\t\tif (!config) throw new Error(\"[FecWorker] not configured\");\n\t\tconst now = performance.now();\n\t\tblock = {\n\t\t\tsbn,\n\t\t\tstate: \"collecting\",\n\t\t\tsourceReceived: 0,\n\t\t\trepairReceived: 0,\n\t\t\tk: config.k,\n\t\t\trepairCount: config.repairCount,\n\t\t\tfirstSymbolTs: now,\n\t\t\tlastSymbolTs: now,\n\t\t\tdeadlineTs: now + config.deliveryWindowMs,\n\t\t\taltaVerified: 0,\n\t\t\trelayBlockSigValid: null,\n\t\t};\n\t\tblocks.set(sbn, block);\n\t\ttrimBlockRetention();\n\t}\n\treturn block;\n}\n\nfunction buildStatsSnapshot(): FecTrackStats {\n\tif (!config) throw new Error(\"[FecWorker] not configured\");\n\tconst decoderStats = wasmDecoder?.get_stats();\n\tconst decoder = decoderStats\n\t\t? {\n\t\t\tsourcePackets: Number(decoderStats.source_packets),\n\t\t\trepairPackets: Number(decoderStats.repair_packets),\n\t\t\tblocksComplete: Number(decoderStats.blocks_complete),\n\t\t\tblocksRecovered: Number(decoderStats.blocks_recovered),\n\t\t\tblocksFailed: Number(decoderStats.blocks_failed),\n\t\t\tbytesRecovered: Number(decoderStats.bytes_recovered),\n\t\t\tpendingBlocks: wasmDecoder?.pending_blocks() ?? 0,\n\t\t}\n\t\t: undefined;\n\n\tconst avgRecoveryMs =\n\t\trecoveryTimes.length > 0\n\t\t\t? recoveryTimes.reduce((a, b) => a + b, 0) / recoveryTimes.length\n\t\t\t: 0;\n\tconst maxRecoveryMs =\n\t\trecoveryTimes.length > 0 ? Math.max(...recoveryTimes) : 0;\n\n\t// Cap block array to interleave window\n\tconst maxBlocks = Math.max(config.interleaveDepth * 3, 24);\n\tconst blockArray = Array.from(blocks.values())\n\t\t.sort((a, b) => b.sbn - a.sbn)\n\t\t.slice(0, maxBlocks);\n\n\treturn {\n\t\tconfig,\n\t\tsourceSymbols,\n\t\trepairSymbols,\n\t\tblocksComplete,\n\t\tblocksRecovered,\n\t\tblocksFailed,\n\t\tgreenFillFrames,\n\t\trecoveryRate:\n\t\t\tblocksComplete + blocksRecovered > 0\n\t\t\t\t? Math.round(\n\t\t\t\t\t\t(blocksRecovered / (blocksRecovered + blocksFailed)) * 100,\n\t\t\t\t\t) || 0\n\t\t\t\t: 0,\n\t\taltaVerified,\n\t\taltaFailed,\n\t\taltaPending,\n\t\taltaPendingEvictedCap,\n\t\taltaPendingEvictedTtl,\n\t\taltaError,\n\t\taltaInitFailed,\n\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\taltaFailedDetails: altaFailedDetails.slice() as any,\n\t\trelayBlocksVerified,\n\t\trelayBlocksFailed,\n\t\tliveSbn,\n\t\tblocks: blockArray,\n\t\tinterleaveWindowBlocks: config.interleaveDepth,\n\t\tavgRecoveryMs: Math.round(avgRecoveryMs * 100) / 100,\n\t\tmaxRecoveryMs: Math.round(maxRecoveryMs * 100) / 100,\n\t\trepairSymbolSizeMismatch,\n\t\tdecoder,\n\t};\n}\n\nfunction emitSnapshot(): void {\n\tif (!config) return;\n\temit({ type: \"snapshot\", stats: buildStatsSnapshot() });\n}\n\nfunction emitBlockUpdate(block: FecBlockSnapshot): void {\n\temit({ type: \"blockUpdate\", block: { ...block } });\n}\n\nfunction emitRecoveredSymbols(\n\tsbn: number,\n\trecoveredBlock: Uint8Array,\n\tblock: FecBlockSnapshot,\n): void {\n\tif (!config) return;\n\tconst symbolSize = config.symbolSize;\n\tif (symbolSize <= 0) {\n\t\temit({\n\t\t\ttype: \"error\",\n\t\t\tcode: \"recovered-symbol-size-unconfigured\",\n\t\t\tmessage: \"[FecWorker] recovered block has no configured symbolSize\",\n\t\t});\n\t\treturn;\n\t}\n\tif (recoveredBlock.byteLength < symbolSize * config.k) {\n\t\temit({\n\t\t\ttype: \"error\",\n\t\t\tcode: \"recovered-block-too-short\",\n\t\t\tmessage: `[FecWorker] recovered block too short: got ${recoveredBlock.byteLength}B, expected at least ${symbolSize * config.k}B`,\n\t\t});\n\t\treturn;\n\t}\n\n\tfor (let i = 0; i < config.k; i++) {\n\t\tconst symbol = recoveredBlock.subarray(i * symbolSize, (i + 1) * symbolSize);\n\n\t\t// Source authentication now runs once at router admission in\n\t\t// @blockcast/mmt-manifest-verify. The worker only records that this\n\t\t// legacy ALTA-enabled symbol bypassed hot-path verification.\n\t\tconst recoveredAltaVerified: boolean | null = null;\n\t\tif (altaEnabled) altaPending++;\n\n\t\tconst buf = toOwnedArrayBuffer(symbol);\n\t\tconst meta: FrameMeta = {\n\t\t\taltaVerified: recoveredAltaVerified,\n\t\t\trecovered: true,\n\t\t\tsbn,\n\t\t\tesi: i,\n\t\t};\n\t\temit({ type: \"frame\", data: buf, meta }, [buf]);\n\t}\n}\n\nfunction startSnapshotTimer(): void {\n\tif (snapshotTimer !== null) clearInterval(snapshotTimer);\n\tsnapshotTimer = setInterval(() => emitSnapshot(), 200);\n}\n\nfunction resolveWasmBindings(): WasmBindings {\n\tconst bindings = (self as unknown as Record<string, unknown>)\n\t\t.__MMT_WASM_BINDINGS__ as WasmBindings | undefined;\n\tif (!bindings) {\n\t\tthrow new Error(\n\t\t\t\"[FecWorker] WASM bindings not available. Set self.__MMT_WASM_BINDINGS__ = { initSync, MmtFecDecoder } before configure.\",\n\t\t);\n\t}\n\treturn bindings;\n}\n\n// --- Command handlers ---\n\nasync function handleConfigure(\n\tcmd: Extract<FecWorkerCommand, { type: \"configure\" }>,\n): Promise<void> {\n\tif (!cmd.wasmModule) {\n\t\tthrow new Error(\"[FecWorker] configure: wasmModule required\");\n\t}\n\tif (!cmd.config) {\n\t\tthrow new Error(\"[FecWorker] configure: config required\");\n\t}\n\tif (\n\t\t!Number.isFinite(cmd.config.interleaveDepth) ||\n\t\t!Number.isInteger(cmd.config.interleaveDepth) ||\n\t\tcmd.config.interleaveDepth <= 0 ||\n\t\tcmd.config.interleaveDepth > MAX_INTERLEAVE_DEPTH\n\t) {\n\t\tthrow new Error(\n\t\t\t`[FecWorker] configure: interleaveDepth must be an integer in 1..${MAX_INTERLEAVE_DEPTH} (got ${cmd.config.interleaveDepth})`,\n\t\t);\n\t}\n\tif (\n\t\t!Number.isFinite(cmd.config.interleaveMs) ||\n\t\tcmd.config.interleaveMs <= 0\n\t) {\n\t\tthrow new Error(\n\t\t\t`[FecWorker] configure: interleaveMs must be finite and > 0 (got ${cmd.config.interleaveMs})`,\n\t\t);\n\t}\n\tif (\n\t\t!Number.isFinite(cmd.config.deliveryWindowMs) ||\n\t\tcmd.config.deliveryWindowMs <= 0\n\t) {\n\t\tthrow new Error(\n\t\t\t`[FecWorker] configure: deliveryWindowMs must be > 0 (got ${cmd.config.deliveryWindowMs})`,\n\t\t);\n\t}\n\tif (\n\t\t!Number.isInteger(cmd.config.k) ||\n\t\tcmd.config.k <= 0 ||\n\t\tcmd.config.k > MAX_RAPTORQ_SOURCE_SYMBOLS_PER_BLOCK\n\t) {\n\t\tthrow new Error(\n\t\t\t`[FecWorker] configure: k must be an integer in 1..${MAX_RAPTORQ_SOURCE_SYMBOLS_PER_BLOCK} (got ${cmd.config.k})`,\n\t\t);\n\t}\n\tif (\n\t\t!Number.isInteger(cmd.config.symbolSize) ||\n\t\tcmd.config.symbolSize <= 0 ||\n\t\tcmd.config.symbolSize > MAX_SYMBOL_SIZE ||\n\t\tcmd.config.symbolSize % 8 !== 0\n\t) {\n\t\tthrow new Error(\n\t\t\t`[FecWorker] configure: symbolSize must be an 8-byte-aligned integer in 8..${MAX_SYMBOL_SIZE} (got ${cmd.config.symbolSize})`,\n\t\t);\n\t}\n\n\tconst wasm = resolveWasmBindings();\n\n\t// Initialize WASM from pre-compiled Module (no fetch, no re-compile)\n\twasm.initSync({ module: cmd.wasmModule });\n\n\t// A configure command starts a new decoder epoch. No terminal tombstone,\n\t// accepted-symbol ID, or active block from the previous decoder may affect it.\n\twasmDecoder?.free();\n\twasmDecoder = null;\n\tclearBlockTracking();\n\n\t// Decoder policy and geometry are explicit at the epoch boundary. The WASM\n\t// module has no guessed K/T/interleave slow path.\n\twasmDecoder = new wasm.MmtFecDecoder(\n\t\tcmd.config.interleaveDepth,\n\t\tcmd.config.trackType === \"video\",\n\t);\n\tconfig = cmd.config;\n\taltaEnabled = !!cmd.altaPublicKey;\n\n\t// Size the deferred-verify queue strictly from catalog-derived FEC\n\t// parameters. CLAUDE.md bans Math.max(x, floor) magic \u2014 if catalog\n\t// values are zero/missing, throw at init rather than silently applying\n\t// a hardcoded floor. Consumers of an undersized queue cap would see\n\t// altaPendingEvictedCap spike with no actionable signal.\n\t// Cap: 1.5\u00D7 interleave depth \u2014 wide enough to hold one full FEC recovery\n\t// window plus jitter, narrow enough to bound memory.\n\tpendingVerifyCap = Math.ceil(config.interleaveDepth * 1.5);\n\t// TTL: 1.5\u00D7 block duration (K symbols at one per interleave tick) \u2014\n\t// after this many ms, any unresolved entry has missed its FEC window.\n\tpendingVerifyTtlMs = Math.ceil(config.interleaveMs * config.k * 1.5);\n\n\t// Initialize ALTA WASM verifier if public key and WASM module provided (D-05, D-09)\n\taltaVerifier = null;\n\taltaInitFailed = false;\n\tif (cmd.altaPublicKey && cmd.altaWasmModule) {\n\t\ttry {\n\t\t\t// Load ALTA JS glue (wasm-bindgen output from wasm-pack build).\n\t\t\t// Mirrors the RaptorQ WASM pattern: initSync({ module }) then construct.\n\t\t\t// Dynamic import path matches the IWA static asset layout.\n\t\t\t// Cast via string to prevent TypeScript from attempting static resolution\n\t\t\t// of a runtime-only URL (same pattern as fec-worker-entry.js loading).\n\t\t\tconst altaGlueUrl = '/wasm/alta/alta_rs.js' as string;\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\tconst altaGlue: any = await import(/* webpackIgnore: true */ altaGlueUrl);\n\t\t\taltaGlue.initSync({ module: cmd.altaWasmModule });\n\t\t\tconst keyBytes = new Uint8Array(cmd.altaPublicKey);\n\t\t\taltaVerifier = new altaGlue.JsAltaVerifier(keyBytes);\n\t\t} catch (e) {\n\t\t\t// T-08-15: WASM init failure must NOT silently look like \"not-ready-yet\".\n\t\t\t// Force altaEnabled = false so handleFeedSource takes the disabled\n\t\t\t// branch instead of continuously bumping altaPending under the\n\t\t\t// misleading \"verifier not yet ready\" comment. altaInitFailed\n\t\t\t// flag in the snapshot tells consumers this is an error state, not\n\t\t\t// an opt-out.\n\t\t\tconsole.warn('[FecWorker] ALTA WASM init failed, verification disabled:', e);\n\t\t\taltaVerifier = null;\n\t\t\taltaEnabled = false;\n\t\t\taltaInitFailed = true;\n\t\t}\n\t}\n\n\twasmDecoder.configure_params(config.k, config.symbolSize);\n\n\t// Start periodic snapshot emission (200ms floor)\n\tstartSnapshotTimer();\n\n\t// Emit initial snapshot\n\temitSnapshot();\n}\n\nfunction handleFeedSource(\n\tcmd: Extract<FecWorkerCommand, { type: \"feedSource\" }>,\n): void {\n\tif (!wasmDecoder) {\n\t\tthrow new Error(\"[FecWorker] feedSource: not configured\");\n\t}\n\tif (!config) {\n\t\tthrow new Error(\"[FecWorker] feedSource: config missing\");\n\t}\n\tif (\n\t\t!isUint32(cmd.ssId) ||\n\t\t!(cmd.data instanceof ArrayBuffer)\n\t) {\n\t\tthrow new Error(\"[FecWorker] feedSource: invalid source symbol\");\n\t}\n\n\tconst view = new Uint8Array(cmd.data);\n\n\t// Derive SBN locally for block-level accounting. WASM derives the same\n\t// value internally (ISO 23008-1 \u00A7C.5.2: SBN = floor(SS_ID / K)).\n\tconst sbn = config.k > 0 ? Math.floor(cmd.ssId / config.k) : cmd.ssId;\n\tconst esi = cmd.ssId % config.k;\n\tif (sbn <= retiredSbnFrontier) return;\n\tconst existingBlock = blocks.get(sbn);\n\tif (existingBlock && isTerminalBlock(existingBlock)) return;\n\tif (acceptedSourceEsis.get(sbn)?.has(esi)) return;\n\n\tconst result = wasmDecoder.add_source(cmd.ssId, view, cmd.ts);\n\tadvanceMediaHorizon(sbn);\n\tlet sourceEsis = acceptedSourceEsis.get(sbn);\n\tif (!sourceEsis) {\n\t\tsourceEsis = new Set<number>();\n\t\tacceptedSourceEsis.set(sbn, sourceEsis);\n\t}\n\tsourceEsis.add(esi);\n\n\t// Update block state\n\tconst block = getOrCreateBlock(sbn);\n\tblock.sourceReceived++;\n\tblock.lastSymbolTs = performance.now();\n\tsourceSymbols++;\n\n\t// The FEC worker must remain decode-only on the per-symbol hot path. ALTA\n\t// WASM is retained temporarily for low-rate signaling users, but media is\n\t// authenticated by the canonical manifest verifier at router admission.\n\tif (altaEnabled) altaPending++;\n\n\t// Check if block is complete (all K source symbols received)\n\tif (\n\t\tblock.sourceReceived >= block.k &&\n\t\tblock.state === \"collecting\"\n\t) {\n\t\tmarkBlockTerminal(block, \"complete\");\n\t\tblocksComplete++;\n\t\temitBlockUpdate(block);\n\t}\n\n\t\t// A source-triggered return can be either clean block completion or recovery\n\t\t// of earlier missing symbols after repair arrived. Clean completion is\n\t\t// already routed by the source path, so only emit when the block did not\n\t\t// reach K source arrivals.\n\t\tif (result && result.byteLength > 0 && block.sourceReceived < block.k) {\n\t\t\tconst recovered = new Uint8Array(toOwnedArrayBuffer(result));\n\t\t\tconst recoveryMs = performance.now() - block.firstSymbolTs;\n\t\t\trecoveryTimes.push(recoveryMs);\n\t\t\tif (recoveryTimes.length > 1000) recoveryTimes.shift();\n\n\t\t\tif (block.state === \"collecting\") {\n\t\t\t\tmarkBlockTerminal(block, \"recovered\");\n\t\t\t\tblocksRecovered++;\n\t\t\t\temitBlockUpdate(block);\n\t\t\t}\n\t\t\temitRecoveredSymbols(sbn, recovered, block);\n\t\t}\n\t\tsynchronizeDecoderHorizon();\n\t}\n\nfunction handleFeedRepair(\n\tcmd: Extract<FecWorkerCommand, { type: \"feedRepair\" }>,\n): void {\n\tif (!wasmDecoder) {\n\t\tthrow new Error(\"[FecWorker] feedRepair: not configured\");\n\t}\n\tif (!config) {\n\t\tthrow new Error(\"[FecWorker] feedRepair: config missing\");\n\t}\n\tif (\n\t\t!isUint32(cmd.ssStart) ||\n\t\t!isUint32(cmd.ssbLength) ||\n\t\tcmd.ssbLength <= 0 ||\n\t\tcmd.ssbLength !== config.k ||\n\t\tcmd.ssStart % cmd.ssbLength !== 0 ||\n\t\t!isUint32(cmd.rsId) ||\n\t\tcmd.ssbLength + cmd.rsId > UINT24_MAX ||\n\t\t!(cmd.data instanceof ArrayBuffer)\n\t) {\n\t\tthrow new Error(\"[FecWorker] feedRepair: invalid repair symbol\");\n\t}\n\n\tconst view = new Uint8Array(cmd.data);\n\tif (config.symbolSize > 0 && view.byteLength !== config.symbolSize) {\n\t\trepairSymbolSizeMismatch++;\n\t\tif (repairSymbolSizeMismatch <= 5 || repairSymbolSizeMismatch % 100 === 0) {\n\t\t\temit({\n\t\t\t\ttype: \"error\",\n\t\t\t\tcode: \"repair-symbol-size-mismatch\",\n\t\t\t\tmessage: `[FecWorker] Dropping repair symbol with invalid size: got ${view.byteLength}B, expected ${config.symbolSize}B (ssStart=${cmd.ssStart}, ssbLength=${cmd.ssbLength}, rsId=${cmd.rsId})`,\n\t\t\t});\n\t\t}\n\t\treturn;\n\t}\n\tconst sbn = Math.floor(cmd.ssStart / cmd.ssbLength);\n\tconst repairEsi = cmd.ssbLength + cmd.rsId;\n\tif (sbn <= retiredSbnFrontier) return;\n\tconst existingBlock = blocks.get(sbn);\n\tif (existingBlock && isTerminalBlock(existingBlock)) return;\n\tif (acceptedRepairEsis.get(sbn)?.has(repairEsi)) return;\n\n\tconst result = wasmDecoder.add_repair(\n\t\tcmd.ssStart,\n\t\tcmd.ssbLength,\n\t\tcmd.rsId,\n\t\tview,\n\t\tcmd.ts,\n\t);\n\tadvanceMediaHorizon(sbn);\n\tlet repairEsis = acceptedRepairEsis.get(sbn);\n\tif (!repairEsis) {\n\t\trepairEsis = new Set<number>();\n\t\tacceptedRepairEsis.set(sbn, repairEsis);\n\t}\n\trepairEsis.add(repairEsi);\n\tconst block = getOrCreateBlock(sbn);\n\tblock.repairReceived++;\n\tblock.lastSymbolTs = performance.now();\n\trepairSymbols++;\n\t\t// If WASM returned data, it is the recovered source block: K fixed-width\n\t\t// source symbols concatenated. Split it before emitting so MmtpRouter gets\n\t\t// the same one-symbol shape as a direct source packet.\n\t\tif (result && result.byteLength > 0) {\n\t\t\tconst recovered = new Uint8Array(toOwnedArrayBuffer(result));\n\t\t\tconst recoveryMs = performance.now() - block.firstSymbolTs;\n\t\t\trecoveryTimes.push(recoveryMs);\n\t\t// Cap recovery times array at 1000 entries\n\t\tif (recoveryTimes.length > 1000) recoveryTimes.shift();\n\n\t\tif (block.state === \"collecting\") {\n\t\t\tmarkBlockTerminal(block, \"recovered\");\n\t\t\tblocksRecovered++;\n\t\t\t\temitBlockUpdate(block);\n\t\t\t}\n\t\t\temitRecoveredSymbols(sbn, recovered, block);\n\t\t}\n\t\tsynchronizeDecoderHorizon();\n\t}\n\nfunction handleRelayBlockSig(\n\tcmd: Extract<FecWorkerCommand, { type: \"relayBlockSig\" }>,\n): void {\n\t// No-op AUTH stub: store sig on block, mark as not-yet-verified\n\tconst block = blocks.get(cmd.sbn);\n\tif (block) {\n\t\t// Real verification deferred to ALTA milestone\n\t\t// For now, mark as null (not verified) \u2014 will be wired when ALTA is implemented\n\t\tblock.relayBlockSigValid = null;\n\t\temitBlockUpdate(block);\n\t}\n}\n\nfunction handleCleanup(\n\tcmd: Extract<FecWorkerCommand, { type: \"cleanup\" }>,\n): void {\n\tif (\n\t\t!Array.isArray(cmd.sbns) ||\n\t\tcmd.sbns.length === 0 ||\n\t\t!cmd.sbns.every(isUint32)\n\t) {\n\t\tthrow new Error(\"[FecWorker] cleanup: invalid SBNs\");\n\t}\n\tconst sbns = [...new Set(cmd.sbns)].sort((a, b) => a - b);\n\tconst pendingSbns = sbns.filter((sbn) => sbn > retiredSbnFrontier);\n\ttry {\n\t\tif (!wasmDecoder) {\n\t\t\tthrow new Error(\"[FecWorker] cleanup: not configured\");\n\t\t}\n\n\t\t// Call WASM cleanup only after all earlier symbol commands have drained.\n\t\t// The detailed API carries the true owner of every fill emitted by a\n\t\t// single cleanup pass; command coalescing must not infer ownership from\n\t\t// the largest timed-out SBN.\n\t\tconst cleanupRecords = pendingSbns.length > 0\n\t\t\t? wasmDecoder.cleanup_blocks_detailed(Uint32Array.from(pendingSbns))\n\t\t\t: new Uint8Array();\n\t\t// Manager deadlines are block-scoped and may expire a newer SBN while an\n\t\t// older interleaved block is still live. Only accepted media progression\n\t\t// advances the shared JS/Rust horizon; cleanup creates exact tombstones.\n\n\t\t// Rust already finalized every SBN behind the media frontier. For each\n\t\t// remaining exact request, mirror the block-scoped WASM boundary immediately\n\t\t// so JS never retains state for a decoder block that is gone, even if decoding\n\t\t// the trusted cleanup framing were to fail.\n\t\tfor (const sbn of pendingSbns) {\n\t\t\tlet currentBlock = blocks.get(sbn);\n\t\t\tif (currentBlock && isTerminalBlock(currentBlock)) {\n\t\t\t\tretireAcceptedIds(sbn);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrentBlock ??= getOrCreateBlock(sbn);\n\t\t\tif (currentBlock.sourceReceived >= currentBlock.k) {\n\t\t\t\tmarkBlockTerminal(currentBlock, \"complete\");\n\t\t\t\tblocksComplete++;\n\t\t\t} else {\n\t\t\t\tmarkBlockTerminal(currentBlock, \"failed\");\n\t\t\t\tblocksFailed++;\n\t\t\t}\n\t\t\temitBlockUpdate(currentBlock);\n\t\t}\n\n\t\tconst greenFills = decodeCleanupRecords(cleanupRecords);\n\t\tfor (const { sbn, data } of greenFills) {\n\t\t\tgreenFillFrames++;\n\t\t\temit({ type: \"greenFill\", sbn, data }, [data]);\n\t\t}\n\t} finally {\n\t\t// Message ordering makes this an acknowledgement that every source/repair\n\t\t// command posted before cleanup has completed. The main thread must not\n\t\t// commit failure accounting until it observes this event.\n\t\temit({ type: \"cleanupComplete\", sbns });\n\t}\n}\n\nfunction decodeCleanupRecords(\n\tframed: Uint8Array,\n): Array<{ sbn: number; data: ArrayBuffer }> {\n\tconst records: Array<{ sbn: number; data: ArrayBuffer }> = [];\n\tconst view = new DataView(framed.buffer, framed.byteOffset, framed.byteLength);\n\tlet offset = 0;\n\twhile (offset < framed.byteLength) {\n\t\tif (framed.byteLength - offset < 8) {\n\t\t\tthrow new Error(\"[FecWorker] cleanup_blocks_detailed: truncated record header\");\n\t\t}\n\t\tconst sbn = view.getUint32(offset, false);\n\t\tconst length = view.getUint32(offset + 4, false);\n\t\toffset += 8;\n\t\tif (length > framed.byteLength - offset) {\n\t\t\tthrow new Error(\"[FecWorker] cleanup_blocks_detailed: truncated record payload\");\n\t\t}\n\t\tconst data = toOwnedArrayBuffer(framed.subarray(offset, offset + length));\n\t\trecords.push({ sbn, data });\n\t\toffset += length;\n\t}\n\treturn records;\n}\n\nfunction handleDispose(): void {\n\t// Clear snapshot timer (MUST clear to prevent leaks)\n\tif (snapshotTimer !== null) {\n\t\tclearInterval(snapshotTimer);\n\t\tsnapshotTimer = null;\n\t}\n\n\t// Free ALTA verifier WASM object (MUST call to release WASM memory \u2014\n\t// Worker.terminate() fires immediately after dispose, so the FinalizationRegistry\n\t// callback has no chance to run and this memory would leak without explicit free)\n\tif (altaVerifier) {\n\t\ttry {\n\t\t\taltaVerifier.free();\n\t\t} catch (_e) {\n\t\t\t// Best-effort \u2014 verifier may already be freed\n\t\t}\n\t\taltaVerifier = null;\n\t}\n\n\t// Free WASM decoder (MUST call to release WASM memory)\n\tif (wasmDecoder) {\n\t\twasmDecoder.free();\n\t\twasmDecoder = null;\n\t}\n\n\t// Clear deferred-verify queue so pinned ArrayBuffers drop.\n\tpendingVerify.clear();\n\tpendingVerifyCap = 0;\n\tpendingVerifyTtlMs = 0;\n\n\tconfig = null;\n\tclearBlockTracking();\n}\n\nfunction handleReset(): void {\n\ttry {\n\t\twasmDecoder?.flush();\n\t\twasmDecoder?.reset_stats();\n\t} catch (err) {\n\t\temit({\n\t\t\ttype: \"error\",\n\t\t\tcode: \"reset-failed\",\n\t\t\tmessage:\n\t\t\t\terr instanceof Error\n\t\t\t\t\t? `[FecWorker] reset failed: ${err.message}`\n\t\t\t\t\t: `[FecWorker] reset failed: ${String(err)}`,\n\t\t});\n\t\treturn;\n\t}\n\n\tclearBlockTracking();\n\tsourceSymbols = 0;\n\trepairSymbols = 0;\n\tblocksComplete = 0;\n\tblocksRecovered = 0;\n\tblocksFailed = 0;\n\tgreenFillFrames = 0;\n\taltaVerified = 0;\n\taltaFailed = 0;\n\taltaFailedDetails.length = 0;\n\taltaPending = 0;\n\taltaPendingEvictedCap = 0;\n\taltaPendingEvictedTtl = 0;\n\taltaError = 0;\n\trelayBlocksVerified = 0;\n\trelayBlocksFailed = 0;\n\trepairSymbolSizeMismatch = 0;\n\temit({ type: \"resetComplete\" });\n\tif (config) emitSnapshot();\n}\n\n// --- Main message handler ---\n\nasync function dispatchCommand(cmd: FecWorkerCommand): Promise<void> {\n\ttry {\n\t\tswitch (cmd.type) {\n\t\t\tcase \"configure\":\n\t\t\t\t// handleConfigure is async (ALTA WASM init uses dynamic import).\n\t\t\t\t// Await it so feed/cleanup messages cannot run against a partially\n\t\t\t\t// configured decoder.\n\t\t\t\tawait handleConfigure(cmd);\n\t\t\t\tbreak;\n\t\t\tcase \"feedSource\":\n\t\t\t\thandleFeedSource(cmd);\n\t\t\t\tbreak;\n\t\t\tcase \"feedRepair\":\n\t\t\t\thandleFeedRepair(cmd);\n\t\t\t\tbreak;\n\t\t\tcase \"relayBlockSig\":\n\t\t\t\thandleRelayBlockSig(cmd);\n\t\t\t\tbreak;\n\t\t\tcase \"cleanup\":\n\t\t\t\thandleCleanup(cmd);\n\t\t\t\tbreak;\n\t\t\tcase \"reset\":\n\t\t\t\thandleReset();\n\t\t\t\tbreak;\n\t\t\tcase \"dispose\":\n\t\t\t\thandleDispose();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\temit({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tcode: \"unknown-command\",\n\t\t\t\t\tmessage: `Unknown command type: ${(cmd as Record<string, unknown>).type}`,\n\t\t\t\t});\n\t\t}\n\t} catch (err) {\n\t\temit({\n\t\t\ttype: \"error\",\n\t\t\tcode: \"command-failed\",\n\t\t\tmessage:\n\t\t\t\terr instanceof Error ? err.message : `[FecWorker] ${String(err)}`,\n\t\t});\n\t}\n}\n\nlet commandQueue: Promise<void> = Promise.resolve();\n\nself.onmessage = (e: MessageEvent<FecWorkerCommand>) => {\n\tconst cmd = e.data;\n\tcommandQueue = commandQueue.then(() => dispatchCommand(cmd));\n};\n"],
5
+ "mappings": ";;;AAOO,SAAS,mBAAmB,MAA+B;AACjE,QAAM,OAAO,IAAI,WAAW,KAAK,UAAU;AAC3C,OAAK,IAAI,IAAI;AACb,SAAO,KAAK;AACb;;;AC4DA,IAAI,cAAqC;AACzC,IAAI,SAAgC;AACpC,IAAI,cAAc;AAElB,IAAI,eAAoB;AACxB,IAAI,gBAAuD;AAG3D,IAAM,SAAS,oBAAI,IAA8B;AACjD,IAAM,qBAAqB,oBAAI,IAAyB;AACxD,IAAM,qBAAqB,oBAAI,IAAyB;AACxD,IAAM,aAAa;AACnB,IAAM,aAAa;AAEnB,IAAM,uBAAuB;AAE7B,IAAM,kBAAkB;AAExB,IAAM,uCAAuC;AAG7C,IAAI,gBAAgB;AACpB,IAAI,gBAAgB;AACpB,IAAI,iBAAiB;AACrB,IAAI,kBAAkB;AACtB,IAAI,eAAe;AACnB,IAAI,kBAAkB;AACtB,IAAI,eAAe;AACnB,IAAI,aAAa;AACjB,IAAM,oBAMD,CAAC;AACN,IAAI,cAAc;AAClB,IAAI,wBAAwB;AAC5B,IAAI,wBAAwB;AAC5B,IAAI,YAAY;AAChB,IAAI,iBAAiB;AACrB,IAAI,sBAAsB;AAC1B,IAAI,oBAAoB;AACxB,IAAI,UAAU;AAId,IAAI,qBAAqB;AACzB,IAAI,2BAA2B;AAG/B,IAAM,gBAA0B,CAAC;AA2BjC,IAAM,gBAAgB,oBAAI,IAA2B;AACrD,IAAI,mBAAmB;AACvB,IAAI,qBAAqB;AAIzB,SAAS,KAAK,OAAuB,UAAiC;AACrE,OAAK,YAAY,OAAO,YAAY,CAAC,CAAC;AACvC;AAEA,SAAS,SAAS,OAAwB;AACzC,SAAO,OAAO,UAAU,KAAK,KAAK,SAAS,KAAK,SAAS;AAC1D;AAEA,S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