LostBeard commited on
Commit
4b83a17
·
0 Parent(s):

SpawnGen Studio (only the current build is kept)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +93 -0
  2. 404.html +254 -0
  3. README.md +48 -0
  4. SpawnDev.SpawnJS.zrbbeqadpn.lib.module.js +1537 -0
  5. _content/SpawnDev.Blazor.BootRecovery/SpawnDev.Blazor.BootRecovery.7rjy3ukk5v.lib.module.js +83 -0
  6. _content/SpawnDev.ILGPU/glWorker.js +1020 -0
  7. _content/SpawnDev.ILGPU/webgpuDispatchPlan.js +408 -0
  8. _framework/ILGPU.Algorithms.ffei46c8ng.wasm.gz +3 -0
  9. _framework/ILGPU.k78gepz5ei.wasm.gz +3 -0
  10. _framework/Microsoft.AspNetCore.Components.Web.cmuc7bdjac.wasm.gz +3 -0
  11. _framework/Microsoft.AspNetCore.Components.WebAssembly.iea6k79bon.wasm.gz +3 -0
  12. _framework/Microsoft.AspNetCore.Components.irsccstbtv.wasm.gz +3 -0
  13. _framework/Microsoft.Extensions.Configuration.Abstractions.wslsrredsq.wasm.gz +3 -0
  14. _framework/Microsoft.Extensions.Configuration.Json.dmmcgk01r0.wasm.gz +3 -0
  15. _framework/Microsoft.Extensions.Configuration.rgjmp347zf.wasm.gz +3 -0
  16. _framework/Microsoft.Extensions.DependencyInjection.Abstractions.d95iifg76m.wasm.gz +3 -0
  17. _framework/Microsoft.Extensions.DependencyInjection.mvfec3p7kh.wasm.gz +3 -0
  18. _framework/Microsoft.Extensions.Logging.5w9ia7xlgq.wasm.gz +3 -0
  19. _framework/Microsoft.Extensions.Logging.Abstractions.xx3hs6cn2q.wasm.gz +3 -0
  20. _framework/Microsoft.Extensions.Options.espvvlqak1.wasm.gz +3 -0
  21. _framework/Microsoft.Extensions.Primitives.crxdkm6t9l.wasm.gz +3 -0
  22. _framework/Microsoft.JSInterop.0523xs2ej1.wasm.gz +3 -0
  23. _framework/Microsoft.JSInterop.WebAssembly.5ql0ra5mpq.wasm.gz +3 -0
  24. _framework/SpawnDev.BackgroundServices.1yeryblw74.wasm.gz +3 -0
  25. _framework/SpawnDev.Blazor.BootRecovery.wqj5nz7x99.wasm.gz +3 -0
  26. _framework/SpawnDev.Codecs.xofv24znhd.wasm.gz +3 -0
  27. _framework/SpawnDev.EBML.xdne5e0w64.wasm.gz +3 -0
  28. _framework/SpawnDev.ILGPU.6mjayrscgw.wasm.gz +3 -0
  29. _framework/SpawnDev.ILGPU.ML.2gzqxw91d8.wasm.gz +3 -0
  30. _framework/SpawnDev.ILGPU.ML.Kernels.xas971tlmk.wasm.gz +3 -0
  31. _framework/SpawnDev.MultiMedia.omfwfbvzp1.wasm.gz +3 -0
  32. _framework/SpawnDev.PatchStreams.fa7qoyfxjz.wasm.gz +3 -0
  33. _framework/SpawnDev.Phonemizer.14wgzuo4bh.wasm.gz +3 -0
  34. _framework/SpawnDev.SpawnJS.Blazor.pmbh2dtfc3.wasm.gz +3 -0
  35. _framework/SpawnDev.SpawnJS.obwsmd2ii3.wasm.gz +3 -0
  36. _framework/SpawnGen.Editor.ysklqo5dvy.wasm.gz +3 -0
  37. _framework/SpawnGen.Engine.963inzh8su.wasm.gz +3 -0
  38. _framework/SpawnGen.Glsl.gumig0hdrg.wasm.gz +3 -0
  39. _framework/SpawnGen.Nodes.Core.nefbdvknei.wasm.gz +3 -0
  40. _framework/SpawnGen.Nodes.ML.m5uycdlwtd.wasm.gz +3 -0
  41. _framework/SpawnGen.Runtime.75kyqfga9w.wasm.gz +3 -0
  42. _framework/SpawnGen.Studio.r201i5b3vg.wasm.gz +3 -0
  43. _framework/System.Collections.Concurrent.ff7cq2nm1d.wasm.gz +3 -0
  44. _framework/System.Collections.Immutable.wgf13aswj8.wasm.gz +3 -0
  45. _framework/System.Collections.NonGeneric.hsozm72ati.wasm.gz +3 -0
  46. _framework/System.Collections.Specialized.f7h3kag6r1.wasm.gz +3 -0
  47. _framework/System.Collections.aw6c0lqys1.wasm.gz +3 -0
  48. _framework/System.ComponentModel.Annotations.nftdtj3wv1.wasm.gz +3 -0
  49. _framework/System.ComponentModel.Primitives.5z48w2rdnk.wasm.gz +3 -0
  50. _framework/System.ComponentModel.TypeConverter.wyfjsyv15c.wasm.gz +3 -0
.gitattributes ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ _framework/dotnet.native.rtfjaicvhp.wasm.br filter=lfs diff=lfs merge=lfs -text
37
+ _framework/icudt_CJK.tjcz0u77k5.dat filter=lfs diff=lfs merge=lfs -text
38
+ _framework/icudt_CJK.tjcz0u77k5.dat.br filter=lfs diff=lfs merge=lfs -text
39
+ _framework/icudt_EFIGS.tptq2av103.dat filter=lfs diff=lfs merge=lfs -text
40
+ _framework/icudt_EFIGS.tptq2av103.dat.br filter=lfs diff=lfs merge=lfs -text
41
+ _framework/icudt_no_CJK.lfu7j35m59.dat filter=lfs diff=lfs merge=lfs -text
42
+ _framework/icudt_no_CJK.lfu7j35m59.dat.br filter=lfs diff=lfs merge=lfs -text
43
+ _framework/ILGPU.hh469695zc.wasm.br filter=lfs diff=lfs merge=lfs -text
44
+ _framework/SpawnDev.Codecs.4az1el8ia6.wasm.br filter=lfs diff=lfs merge=lfs -text
45
+ _framework/SpawnDev.EBML.xdne5e0w64.wasm.br filter=lfs diff=lfs merge=lfs -text
46
+ _framework/SpawnDev.ILGPU.fuxb6lz6el.wasm.br filter=lfs diff=lfs merge=lfs -text
47
+ _framework/SpawnDev.ILGPU.ML.9usgbtl1ls.wasm.br filter=lfs diff=lfs merge=lfs -text
48
+ _framework/SpawnDev.ILGPU.ML.Kernels.32rqe3oaz7.wasm.br filter=lfs diff=lfs merge=lfs -text
49
+ _framework/SpawnDev.MultiMedia.omfwfbvzp1.wasm.br filter=lfs diff=lfs merge=lfs -text
50
+ _framework/SpawnDev.Phonemizer.14wgzuo4bh.wasm.br filter=lfs diff=lfs merge=lfs -text
51
+ _framework/SpawnDev.SpawnJS.li761i2n6z.wasm.br filter=lfs diff=lfs merge=lfs -text
52
+ _framework/SpawnGen.Nodes.Core.b7k44ae8kb.wasm.br filter=lfs diff=lfs merge=lfs -text
53
+ _framework/SpawnGen.Nodes.ML.ula38wzxn6.wasm.br filter=lfs diff=lfs merge=lfs -text
54
+ _framework/SpawnGen.Studio.dobkx6cxzg.wasm.br filter=lfs diff=lfs merge=lfs -text
55
+ _framework/System.Private.CoreLib.jxzjjd418f.wasm.br filter=lfs diff=lfs merge=lfs -text
56
+ _framework/System.Private.Xml.u94bl2dvp8.wasm.br filter=lfs diff=lfs merge=lfs -text
57
+ _framework/System.Text.Json.wmn8nrdgsp.wasm.br filter=lfs diff=lfs merge=lfs -text
58
+ _framework/System.Text.RegularExpressions.5f6os8d0wv.wasm.br filter=lfs diff=lfs merge=lfs -text
59
+ examples/example.png filter=lfs diff=lfs merge=lfs -text
60
+ examples/example_inpaint.png filter=lfs diff=lfs merge=lfs -text
61
+ _framework/dotnet.native.a8ztq4aqg2.wasm.br filter=lfs diff=lfs merge=lfs -text
62
+ _framework/SpawnGen.Nodes.Core.abygs8i0pv.wasm.br filter=lfs diff=lfs merge=lfs -text
63
+ _framework/SpawnGen.Nodes.ML.rbb9gtli8o.wasm.br filter=lfs diff=lfs merge=lfs -text
64
+ _framework/SpawnGen.Studio.x6iftgse6j.wasm.br filter=lfs diff=lfs merge=lfs -text
65
+ _framework/dotnet.native.mm6f5lm5eg.wasm.br filter=lfs diff=lfs merge=lfs -text
66
+ _framework/SpawnGen.Nodes.Core.dxdnt8bcer.wasm.br filter=lfs diff=lfs merge=lfs -text
67
+ _framework/SpawnGen.Nodes.ML.c1dhxhtvmm.wasm.br filter=lfs diff=lfs merge=lfs -text
68
+ _framework/SpawnGen.Studio.q24o3uygaw.wasm.br filter=lfs diff=lfs merge=lfs -text
69
+ _framework/dotnet.native.81lj8ak7g0.wasm.br filter=lfs diff=lfs merge=lfs -text
70
+ _framework/SpawnGen.Nodes.Core.euk05e5wt9.wasm.br filter=lfs diff=lfs merge=lfs -text
71
+ _framework/SpawnGen.Nodes.ML.shgf6ekwmw.wasm.br filter=lfs diff=lfs merge=lfs -text
72
+ _framework/SpawnGen.Studio.o9zz1ggm9e.wasm.br filter=lfs diff=lfs merge=lfs -text
73
+ _framework/dotnet.native.6948hfs75e.wasm.br filter=lfs diff=lfs merge=lfs -text
74
+ _framework/ILGPU.lbeymlaqbz.wasm.br filter=lfs diff=lfs merge=lfs -text
75
+ _framework/SpawnDev.Codecs.hf0tdrr42b.wasm.br filter=lfs diff=lfs merge=lfs -text
76
+ _framework/SpawnDev.ILGPU.ML.j1zfb2mr3k.wasm.br filter=lfs diff=lfs merge=lfs -text
77
+ _framework/SpawnDev.ILGPU.ML.Kernels.391q7al9vs.wasm.br filter=lfs diff=lfs merge=lfs -text
78
+ _framework/SpawnDev.ILGPU.v7r0292kmo.wasm.br filter=lfs diff=lfs merge=lfs -text
79
+ _framework/SpawnDev.SpawnJS.7rauvzflz1.wasm.br filter=lfs diff=lfs merge=lfs -text
80
+ _framework/SpawnGen.Nodes.Core.i10j5fm6p6.wasm.br filter=lfs diff=lfs merge=lfs -text
81
+ _framework/SpawnGen.Nodes.ML.jwcp2dhqic.wasm.br filter=lfs diff=lfs merge=lfs -text
82
+ _framework/SpawnGen.Studio.sgcz28bkwh.wasm.br filter=lfs diff=lfs merge=lfs -text
83
+ _framework/dotnet.native.qa5b69bgaq.wasm.br filter=lfs diff=lfs merge=lfs -text
84
+ _framework/ILGPU.obaeemdvxg.wasm.br filter=lfs diff=lfs merge=lfs -text
85
+ _framework/SpawnDev.Codecs.9u5l43fglr.wasm.br filter=lfs diff=lfs merge=lfs -text
86
+ _framework/SpawnDev.ILGPU.17m3tmnaun.wasm.br filter=lfs diff=lfs merge=lfs -text
87
+ _framework/SpawnDev.ILGPU.ML.Kernels.hdha89l645.wasm.br filter=lfs diff=lfs merge=lfs -text
88
+ _framework/SpawnDev.ILGPU.ML.pdvwzvdu6e.wasm.br filter=lfs diff=lfs merge=lfs -text
89
+ _framework/SpawnDev.SpawnJS.686kwtpghu.wasm.br filter=lfs diff=lfs merge=lfs -text
90
+ _framework/SpawnGen.Nodes.Core.johaj1vmk0.wasm.br filter=lfs diff=lfs merge=lfs -text
91
+ _framework/SpawnGen.Nodes.ML.a38jpktpf1.wasm.br filter=lfs diff=lfs merge=lfs -text
92
+ _framework/SpawnGen.Studio.gq9yb704d0.wasm.br filter=lfs diff=lfs merge=lfs -text
93
+ _framework/System.Private.CoreLib.fha1ivutny.wasm.br filter=lfs diff=lfs merge=lfs -text
404.html ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta charset="utf-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>SpawnGen Studio</title>
8
+ <base href="/" />
9
+ <link rel="icon" href="data:," />
10
+ <link rel="stylesheet" href="css/app.css" />
11
+ </head>
12
+
13
+ <body>
14
+ <div id="app">
15
+ <div class="boot">Loading SpawnGen Studio...</div>
16
+ </div>
17
+ <div id="blazor-error-ui">
18
+ An unhandled error has occurred.
19
+ <a href="." class="reload">Reload</a>
20
+ <span class="dismiss">x</span>
21
+ </div>
22
+ <script>
23
+ // A node dragged out of the library carries its class name.
24
+ document.addEventListener("dragstart", e => {
25
+ const n = e.target.closest && e.target.closest("[data-node]");
26
+ if (n) { e.dataTransfer.setData("text/spawngen-node", n.dataset.node); e.dataTransfer.effectAllowed = "copy"; }
27
+ });
28
+ // The mask editor: paint over a picture, get it back as a PNG whose painted pixels are transparent (what Load Image turns into its mask).
29
+ // Resolves with the PNG as a Blob (it stays in JS), or null when cancelled or the picture cannot be read.
30
+ window.spawngenMaskEditor = function (imageUrl) {
31
+ return new Promise(async resolve => {
32
+ const img = new Image();
33
+ img.src = imageUrl;
34
+ try { await img.decode(); } catch (e) { resolve(null); return; }
35
+ const w = img.naturalWidth, h = img.naturalHeight;
36
+ if (!w || !h) { resolve(null); return; }
37
+ const root = document.createElement("div");
38
+ root.className = "maskeditor";
39
+ root.innerHTML = '<div class="me-bar"><span>Mask editor</span>' +
40
+ '<label>Brush <input class="me-size" type="range" min="2" max="200" value="40"></label>' +
41
+ '<button class="me-mode" data-mode="paint">Paint</button><button class="me-mode" data-mode="erase">Erase</button>' +
42
+ '<button class="me-clear">Clear</button><button class="me-invert">Invert</button>' +
43
+ '<span class="me-spacer"></span><button class="me-cancel">Cancel</button><button class="me-save">Save</button></div>' +
44
+ '<div class="me-stage"><div class="me-stack"><canvas class="me-base"></canvas><canvas class="me-mask"></canvas></div></div>';
45
+ document.body.appendChild(root);
46
+ const base = root.querySelector(".me-base"), mask = root.querySelector(".me-mask");
47
+ base.width = mask.width = w; base.height = mask.height = h;
48
+ const bctx = base.getContext("2d"), mctx = mask.getContext("2d");
49
+ bctx.drawImage(img, 0, 0);
50
+ // An existing mask (transparent pixels of the picture) comes back as paint.
51
+ const pix = bctx.getImageData(0, 0, w, h);
52
+ const init = mctx.createImageData(w, h);
53
+ for (let i = 0; i < pix.data.length; i += 4) {
54
+ if (pix.data[i + 3] < 128) { init.data[i] = 255; init.data[i + 1] = 59; init.data[i + 2] = 59; init.data[i + 3] = 255; }
55
+ pix.data[i + 3] = 255;
56
+ }
57
+ bctx.putImageData(pix, 0, 0);
58
+ mctx.putImageData(init, 0, 0);
59
+ let mode = "paint", drawing = false, last = null;
60
+ const modes = root.querySelectorAll(".me-mode");
61
+ const setMode = m => { mode = m; modes.forEach(b => b.classList.toggle("on", b.dataset.mode === m)); };
62
+ setMode("paint");
63
+ modes.forEach(b => b.onclick = () => setMode(b.dataset.mode));
64
+ const size = root.querySelector(".me-size");
65
+ const at = e => { const r = mask.getBoundingClientRect(); return { x: (e.clientX - r.left) * w / r.width, y: (e.clientY - r.top) * h / r.height }; };
66
+ const stroke = (a, b) => {
67
+ mctx.globalCompositeOperation = mode === "erase" ? "destination-out" : "source-over";
68
+ mctx.strokeStyle = "#ff3b3b"; mctx.fillStyle = "#ff3b3b";
69
+ mctx.lineWidth = +size.value; mctx.lineCap = "round"; mctx.lineJoin = "round";
70
+ mctx.beginPath(); mctx.moveTo(a.x, a.y); mctx.lineTo(b.x + 0.01, b.y); mctx.stroke();
71
+ };
72
+ mask.onpointerdown = e => { drawing = true; mask.setPointerCapture(e.pointerId); last = at(e); stroke(last, last); };
73
+ mask.onpointermove = e => { if (!drawing) return; const p = at(e); stroke(last, p); last = p; };
74
+ mask.onpointerup = mask.onpointercancel = () => { drawing = false; };
75
+ root.querySelector(".me-clear").onclick = () => mctx.clearRect(0, 0, w, h);
76
+ root.querySelector(".me-invert").onclick = () => {
77
+ const d = mctx.getImageData(0, 0, w, h);
78
+ for (let i = 0; i < d.data.length; i += 4) { const on = d.data[i + 3] > 127; d.data[i] = 255; d.data[i + 1] = 59; d.data[i + 2] = 59; d.data[i + 3] = on ? 0 : 255; }
79
+ mctx.putImageData(d, 0, 0);
80
+ };
81
+ const finish = result => { document.removeEventListener("keydown", onKey); root.remove(); resolve(result); };
82
+ const onKey = e => { if (e.key === "Escape") { e.preventDefault(); finish(null); } };
83
+ document.addEventListener("keydown", onKey);
84
+ root.querySelector(".me-cancel").onclick = () => finish(null);
85
+ root.querySelector(".me-save").onclick = async () => {
86
+ const out = document.createElement("canvas"); out.width = w; out.height = h;
87
+ const octx = out.getContext("2d");
88
+ octx.drawImage(base, 0, 0);
89
+ octx.globalCompositeOperation = "destination-out";
90
+ // Anything painted by more than half counts as masked: the soft edge of a stroke is not a half-transparent hole.
91
+ const d = mctx.getImageData(0, 0, w, h);
92
+ for (let i = 0; i < d.data.length; i += 4) d.data[i + 3] = d.data[i + 3] > 127 ? 255 : 0;
93
+ const tmp = document.createElement("canvas"); tmp.width = w; tmp.height = h;
94
+ tmp.getContext("2d").putImageData(d, 0, 0);
95
+ octx.drawImage(tmp, 0, 0);
96
+ out.toBlob(blob => finish(blob || null), "image/png");
97
+ };
98
+ });
99
+ };
100
+ // Browser storage for the open workflows (tabs, autosave). It can be missing or full: every call is allowed to fail quietly.
101
+ window.spawngenStoreGet = function (key) { try { return localStorage.getItem(key); } catch (e) { return null; } };
102
+ window.spawngenSetTheme = function (id) { document.documentElement.dataset.theme = id === 'light' ? 'light' : 'dark'; };
103
+ // Applied before the app boots, so a light page does not flash dark first.
104
+ try { window.spawngenSetTheme(JSON.parse(localStorage.getItem('spawngen.settings') || '{}').Palette); } catch (e) { }
105
+ window.spawngenStoreSet = function (key, value) { try { localStorage.setItem(key, value); return true; } catch (e) { return false; } };
106
+ // The workflow library when no server serves the Studio: files in IndexedDB (database spawngen-userdata, store files, {path, text, modified,
107
+ // created}). Each call is one transaction; results are strings ("done", "exists", "missing") or JSON text.
108
+ window.spawngenFiles = (function () {
109
+ let db = null;
110
+ function open() {
111
+ return db ??= new Promise((resolve, reject) => {
112
+ const r = indexedDB.open("spawngen-userdata", 1);
113
+ r.onupgradeneeded = () => r.result.createObjectStore("files", { keyPath: "path" });
114
+ r.onsuccess = () => resolve(r.result);
115
+ r.onerror = () => { db = null; reject(r.error); };
116
+ });
117
+ }
118
+ async function run(mode, body) {
119
+ const store = (await open()).transaction("files", mode).objectStore("files");
120
+ return new Promise((resolve, reject) => {
121
+ store.transaction.onerror = () => reject(store.transaction.error);
122
+ body(store, resolve);
123
+ });
124
+ }
125
+ const get = (store, path, then) => { const r = store.get(path); r.onsuccess = () => then(r.result ?? null); };
126
+ return {
127
+ list: () => run("readonly", (s, done) => {
128
+ const r = s.getAll();
129
+ r.onsuccess = () => done(JSON.stringify(r.result.map(f => ({ path: f.path, size: new Blob([f.text]).size, modified: f.modified }))));
130
+ }),
131
+ read: path => run("readonly", (s, done) => get(s, path, f => done(f ? f.text : null))),
132
+ write: (path, text, overwrite) => run("readwrite", (s, done) => get(s, path, old => {
133
+ if (old && !overwrite) { done("exists"); return; }
134
+ const now = Date.now();
135
+ s.put({ path, text, modified: now, created: old ? old.created : now }).onsuccess = () => done("done");
136
+ })),
137
+ move: (from, to, overwrite) => run("readwrite", (s, done) => get(s, from, f => {
138
+ if (!f) { done("missing"); return; }
139
+ if (from === to) { done("done"); return; }
140
+ get(s, to, old => {
141
+ if (old && !overwrite) { done("exists"); return; }
142
+ s.put({ ...f, path: to });
143
+ s.delete(from).onsuccess = () => done("done");
144
+ });
145
+ })),
146
+ remove: path => run("readwrite", (s, done) => get(s, path, f => {
147
+ if (!f) { done("missing"); return; }
148
+ s.delete(path).onsuccess = () => done("done");
149
+ })),
150
+ };
151
+ })();
152
+ // Ctrl+O: the toolbar's Open file picker (called while the key press still counts as the user's action).
153
+ window.spawngenOpenWorkflowFile = function () {
154
+ const input = document.querySelector('.toolbar input[type=file][accept=".json,.png"]');
155
+ if (input) input.click();
156
+ };
157
+ // Plays an animated picture (Save Animated WEBP / PNG, a GIF) on a canvas of its own, which the node canvas draws every frame: a canvas
158
+ // drawImage of an animated <img> shows only its first frame (the HTML spec's rule; TJ 2026-11-19: the LTX example's WEBP sat still).
159
+ // WebCodecs' ImageDecoder decodes one frame at a time, so only one frame is held. Returns null where ImageDecoder is missing; the canvas
160
+ // stays 0 x 0 for a still picture or a type the browser cannot decode (the caller then shows the <img> as before).
161
+ window.spawngenAnimate = function (url) {
162
+ if (typeof ImageDecoder === "undefined") return null;
163
+ const canvas = document.createElement("canvas");
164
+ canvas.width = 0; canvas.height = 0;
165
+ (async () => {
166
+ const blob = await (await fetch(url)).blob();
167
+ if (!blob.type || !(await ImageDecoder.isTypeSupported(blob.type))) return;
168
+ const decoder = new ImageDecoder({ data: blob.stream(), type: blob.type });
169
+ try {
170
+ await decoder.tracks.ready;
171
+ const track = decoder.tracks.selectedTrack;
172
+ if (!track || !track.animated) return;
173
+ await decoder.completed;
174
+ const ctx = canvas.getContext("2d");
175
+ for (let index = 0; !canvas.spawngenStop; index = (index + 1) % track.frameCount) {
176
+ const frame = (await decoder.decode({ frameIndex: index })).image;
177
+ if (canvas.width !== frame.displayWidth || canvas.height !== frame.displayHeight) { canvas.width = frame.displayWidth; canvas.height = frame.displayHeight; }
178
+ ctx.drawImage(frame, 0, 0);
179
+ const ms = frame.duration ? frame.duration / 1000 : 100;
180
+ frame.close();
181
+ await new Promise(r => setTimeout(r, Math.max(16, ms)));
182
+ }
183
+ } finally { decoder.close(); }
184
+ })().catch(e => console.warn("spawngenAnimate", e));
185
+ return canvas;
186
+ };
187
+ window.spawngenAnimateStop = function (canvas) { if (canvas) canvas.spawngenStop = true; };
188
+ // Saves a picture (a data, blob or same-origin URL) as a file download.
189
+ window.spawngenDownloadUrl = function (name, url) {
190
+ const a = document.createElement("a");
191
+ a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove();
192
+ };
193
+ // Saves text as a file download (the workflow JSON).
194
+ window.spawngenDownload = function (name, text) {
195
+ const url = URL.createObjectURL(new Blob([text], { type: "application/json" }));
196
+ const a = document.createElement("a");
197
+ a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove();
198
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
199
+ };
200
+ </script>
201
+ <script src="js/glbviewer.js"></script>
202
+ <script src="_framework/blazor.webassembly.js" autostart="false"></script>
203
+ <script>
204
+ // The site ships ONE copy of each file. gzboot.json (written at deploy time by tools/gzboot.sh; the source's copy lists nothing) says
205
+ // which runtime files exist only as <name>.gz: all of them on a host that sends files uncompressed (the Hugging Face Space: the AOT
206
+ // runtime is 91 MB raw, 24 MB gzipped), or the few over a host's file size limit. Those are fetched as .gz and inflated by the
207
+ // browser's own DecompressionStream; everything else loads the default way (GitHub Pages gzips what it serves by itself).
208
+ (async function () {
209
+ let gz = null;
210
+ try { const r = await fetch('gzboot.json', { cache: 'no-cache' }); if (r.ok) gz = await r.json(); } catch (e) { }
211
+ const listed = name => !!gz && typeof DecompressionStream !== 'undefined'
212
+ && (gz.all ? !/\.(js|json)$/.test(name) : (gz.files || []).indexOf(name) >= 0);
213
+ Blazor.start({
214
+ loadBootResource: function (type, name, defaultUri, integrity) {
215
+ if (type === 'dotnetjs' || type === 'configuration' || type === 'manifest' || !listed(name)) return null;
216
+ // Our own fetch of a <name>.gz copy, held to what the runtime's own loader gives the other files:
217
+ // - cache: 'force-cache', the runtime's mode for its fingerprinted files. A wrong answer the browser stored for the
218
+ // URL (a host's 503 page during an outage) would otherwise be served again on every load; a failed force-cache
219
+ // request is sent once more past the cache by SpawnDev.Blazor.BootRecovery (dotnet/runtime#135090), which the
220
+ // Studio references: it covers the runtime's own fetches, and this one because it asks the same way.
221
+ // - the integrity check, which the runtime's fetch does and a hand-made Response would skip: the inflated bytes
222
+ // must hash to the file's integrity value. Bytes that do not inflate or do not match (an error page answered
223
+ // with 200, a damaged upload) are asked for once more, past the cache, and then fail the start as they should.
224
+ return (async function () {
225
+ const contentType = type === 'dotnetwasm' ? 'application/wasm' : 'application/octet-stream';
226
+ const load = async function (cacheMode) {
227
+ const r = await fetch(defaultUri + '.gz', { cache: cacheMode });
228
+ if (r.status === 404) return null; // no compressed copy after all
229
+ if (!r.ok) throw new Error('HTTP ' + r.status);
230
+ // a server that already sent it with Content-Encoding: gzip had the browser inflate it
231
+ const body = r.headers.get('content-encoding') ? r.body : r.body.pipeThrough(new DecompressionStream('gzip'));
232
+ const bytes = await new Response(body).arrayBuffer();
233
+ if (integrity && integrity.indexOf('sha256-') === 0 && window.crypto && crypto.subtle) {
234
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
235
+ let text = ''; for (let i = 0; i < hash.length; i++) text += String.fromCharCode(hash[i]);
236
+ if ('sha256-' + btoa(text) !== integrity) throw new Error('the file does not match its integrity value');
237
+ }
238
+ return new Response(bytes, { headers: { 'content-type': contentType } });
239
+ };
240
+ let response;
241
+ try { response = await load('force-cache'); }
242
+ catch (e) {
243
+ console.warn('[boot] ' + name + '.gz did not load (' + (e && e.message) + '): asking again, past the cache');
244
+ response = await load('reload');
245
+ }
246
+ return response || fetch(defaultUri, { cache: 'force-cache', integrity: integrity }); // the original
247
+ })();
248
+ }
249
+ });
250
+ })();
251
+ </script>
252
+ </body>
253
+
254
+ </html>
README.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: SpawnGen
3
+ emoji: 🧩
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: static
7
+ app_file: index.html
8
+ pinned: false
9
+ license: mit
10
+ short_description: ComfyUI-style node graphs, run on your GPU in the browser
11
+ tags:
12
+ - webgpu
13
+ - comfyui
14
+ - node-graph
15
+ - text-to-image
16
+ - text-to-video
17
+ - image-to-video
18
+ - image-to-3d
19
+ - blazor
20
+ models:
21
+ - stabilityai/sd-turbo
22
+ - stabilityai/sdxl-turbo
23
+ - LostBeard/FLUX.2-klein-4B-q4-ILGPU
24
+ - LostBeard/flux-3-image-klein-q4-ILGPU
25
+ - Lightricks/LTX-2
26
+ - Comfy-Org/Z-Image-Turbo
27
+ - Comfy-Org/ltx-2
28
+ - onnx-community/depth-anything-v2-small
29
+ - onnx-community/Kokoro-82M-v1.0-ONNX
30
+ - istupakov/parakeet-tdt-0.6b-v3-onnx
31
+ - briaai/RMBG-1.4
32
+ - Xenova/movenet-singlepose-lightning
33
+ - salim4n/yolov8n-detect-onnx
34
+ - Qwen/Qwen3-4B
35
+ ---
36
+
37
+ # SpawnGen
38
+
39
+ A ComfyUI-class node-graph studio written in C#, running **entirely in your browser on your GPU** (WebGPU): no server does the inference.
40
+ ComfyUI workflows and templates open and run as they do in ComfyUI; models download on first use (from Hugging Face) and stay cached in
41
+ the browser.
42
+
43
+ - **Examples**: text to image (SD-Turbo, SD 1.5, FLUX.2 / FLUX 3 Klein), image to image, inpainting, text to video and picture to video
44
+ (LTX-Video 2B), image to 3D (TRELLIS.2), depth, pose and object detection, background removal, speech.
45
+ - **Templates**: ComfyUI's template catalog, each marked with what this browser can run.
46
+ - Needs a browser with WebGPU (Chrome or Edge). Large models need a GPU with enough memory; the first run downloads the weights.
47
+
48
+ Source: [github.com/LostBeard/SpawnGen](https://github.com/LostBeard/SpawnGen) (MIT). Built on SpawnDev.ILGPU and SpawnDev.ILGPU.ML.
SpawnDev.SpawnJS.zrbbeqadpn.lib.module.js ADDED
@@ -0,0 +1,1537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'strict';
2
+
3
+ // SpawnJSInterop - the Javascript half of SpawnJS.
4
+ //
5
+ // Architecture: every JS value that .Net needs to reference is kept in an id-keyed table
6
+ // (spawnJSObjects) and addressed from .Net by that numeric id. .Net never receives a live JS object
7
+ // handle (no Microsoft JSObject), only ids and primitives - which is what lets the .Net side avoid
8
+ // JSObject and its disposal quirk entirely. .Net "holds" a value (spawnJSObjectHold -> id) and later
9
+ // "releases" it (spawnJSObjectRelease) so it can be garbage-collected.
10
+ //
11
+ // Negative ids are reserved sentinels resolved without a table lookup:
12
+ // -1 globalThis, -2 undefined, -3 null, -4 the spawnJSObjects table, SpawnJSInterop.
13
+ //
14
+ // Calls flow through _spawnJSInteropCall (sync) / _spawnJSInteropCallAsync (async). The whole call - which static
15
+ // method here, the returnType code (see ReturnType.cs), every argument - is written by .Net onto its call tape
16
+ // (JSTape.cs) in .Net memory and crosses ONCE: the call reads it straight off the WASM heap and writes the result
17
+ // back over the same frame. Each call carries its dotnetId and frame address, so nothing here is shared between
18
+ // .Net instances beyond this class.
19
+ (function () {
20
+ if (globalThis.SpawnJSInterop) return;
21
+ class SpawnJSInterop {
22
+ // enables verbose logging
23
+ static verbose = globalThis.spawnJSInteropVerbose;
24
+ // ArrayBufferView constructors
25
+ static HeapViewCtors = [
26
+ globalThis.BigInt64Array, // 0: BigInt64Array
27
+ globalThis.BigUint64Array, // 1: BigUInt64Array
28
+ globalThis.Float16Array, // 2: Float16Array
29
+ globalThis.Float32Array, // 3: Float32Array
30
+ globalThis.Float64Array, // 4: Float64Array
31
+ globalThis.Int16Array, // 5: Int16Array
32
+ globalThis.Int32Array, // 6: Int32Array
33
+ globalThis.Int8Array, // 7: Int8Array
34
+ globalThis.Uint16Array, // 8: Uint16Array
35
+ globalThis.Uint32Array, // 9: Uint32Array
36
+ globalThis.Uint8Array, // 10: Uint8Array
37
+ globalThis.Uint8ClampedArray, // 11: Uint8ClampedArray
38
+ globalThis.DataView // 12: DataView
39
+ ];
40
+ static _revivers = [];
41
+ static _replacers = [];
42
+ // method names for index based calling as an alternative to string
43
+ static _methodMapNames = [];
44
+ // methods mapped by index for index based calling as an alternative to string
45
+ static _methodMap = [];
46
+ // The id -> JS value table. Holds every value .Net currently references.
47
+ static spawnJSObjects = {};
48
+ // Monotonic id source; never reused, so a stale .Net id can never collide with a live value.
49
+ static _sjsObjectIdNext = 0;
50
+ // .Net Wasm app instance infos
51
+ static _instances = {};
52
+ // .Net callbacks
53
+ static _callbacks = {};
54
+ static _detachedSentinelId = null;
55
+ // static constructor
56
+ static {
57
+ // SpawnJSInterop.registerReviver('__reviverTest', (key, value) => {
58
+ // if (SpawnJSInterop.verbose) console.log('[SpawnJSInterop] reviver test', key, value);
59
+ // return value;
60
+ // });
61
+ // SpawnJSInterop.registerReplacer('__replacerTest', (key, value) => {
62
+ // if (SpawnJSInterop.verbose) console.log('[SpawnJSInterop] replacer test', key, value);
63
+ // return value;
64
+ // });
65
+ SpawnJSInterop.refreshMethodMap();
66
+ // detachedHeap sentinel
67
+ this._detachedSentinelId = setInterval(() => SpawnJSInterop.detachedEventCheck(), 500);
68
+ }
69
+
70
+ // JSImports
71
+ // Methods accessed via JSImport only send and recieve basic
72
+ // data types and are used to support the marshalling framework
73
+ // that allows working with much more advanced data types.
74
+
75
+ // JSImport
76
+ // double _registerInstance(
77
+ // JSObject dotnetInstance,
78
+ // [JSMarshalAs<JSType.Function>] Action onMethodAdded,
79
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.String>>] Action<double, string> onAsyncResolvedVoid,
80
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number, JSType.String>>] Action<double, double, string> onAsyncResolvedDouble,
81
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Boolean, JSType.String>>] Action<double, bool, string> onAsyncResolvedBool,
82
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.String, JSType.String>>] Action<double, string, string> onAsyncResolvedString,
83
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Any, JSType.String>>] Action<double, object, string> onAsyncResolvedDoubleNullable,
84
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Any, JSType.String>>] Action<double, object, string> onAsyncResolvedBooleanNullable,
85
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number, JSType.String>>] Action<double, int, string> onAsyncResolvedInt32,
86
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Any, JSType.String>>] Action<double, object, string> onAsyncResolvedInt32Nullable,
87
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number>>] Action<long, long> onDetachedHeap,
88
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number, JSType.Number>>] Action<double, double, double> onCallback,
89
+ // [JSMarshalAs<JSType.Function<JSType.Number, JSType.Number, JSType.String>>] Action<double, int, string> onAsyncResolvedTape)
90
+ static _registerInstance(
91
+ dotnet,
92
+ onMethodAdded,
93
+ resolveVoid,
94
+ resolveDouble,
95
+ resolveBoolean,
96
+ resolveString,
97
+ resolveDoubleNullable,
98
+ resolveBooleanNullable,
99
+ resolveInt32,
100
+ resolveInt32Nullable,
101
+ onDetachedHeap,
102
+ handleCallback,
103
+ resolveTape
104
+ ) {
105
+ if (!dotnet) throw new Error('dotnet not set');
106
+ var instanceInfo = SpawnJSInterop._getInstaceFromDotNet(dotnet);
107
+ if (instanceInfo) return instanceInfo.dotnetId;
108
+
109
+ var dotnetId = SpawnJSInterop.spawnJSObjectHold(dotnet);
110
+
111
+ // attach the heap buffer to instanceInfo so it can be monitored for detach events
112
+ var heapBuffer = SpawnJSInterop.wasmMemoryBuffer(dotnet);
113
+
114
+ var instanceInfo = { heapBuffer, dotnet, dotnetId, onMethodAdded, resolveVoid, resolveDouble, resolveBoolean, resolveString, resolveDoubleNullable, resolveBooleanNullable, resolveInt32, resolveInt32Nullable, handleCallback, onDetachedHeap, resolveTape };
115
+ SpawnJSInterop._instances[dotnetId] = instanceInfo;
116
+
117
+ instanceInfo.heapBufferSize = heapBuffer.byteLength;
118
+ instanceInfo.getHeap = () => {
119
+ if (instanceInfo.heapBuffer.detached) {
120
+ if (SpawnJSInterop.verbose) console.log(`Detached heap detected for: ${dotnetId}`);
121
+ // get the new heap buffer
122
+ instanceInfo.heapBuffer = SpawnJSInterop.wasmMemoryBuffer(dotnet);
123
+ const oldSize = instanceInfo.heapBufferSize;
124
+ instanceInfo.heapBufferSize = instanceInfo.heapBuffer.byteLength;
125
+ // notify the instance
126
+ instanceInfo.onDetachedHeap(oldSize, instanceInfo.heapBuffer.byteLength);
127
+ }
128
+ return instanceInfo.heapBuffer;
129
+ };
130
+
131
+ if (SpawnJSInterop.verbose) console.log('[SpawnJSInterop] Instance registered', instanceInfo);
132
+ return dotnetId;
133
+ }
134
+ // Call tape value tags - JSTape.Tag* in JSTape.cs must match
135
+ static TapeTag = { Undefined: 0, Null: 1, Number: 2, Boolean: 3, String: 4, Ref: 5, Callback: 6, Absent: 8, Object: 9, Shape: 10, Array: 11, Numbers: 12, HeapView: 13, Record: 14, Revive: 15 };
136
+ // TagNumbers kinds - JSTape.NumberKind must match
137
+ static TapeNumberCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
138
+ // what a member written as TagAbsent reads as: the property is not assigned
139
+ static _tapeAbsent = Object.freeze({});
140
+
141
+ // Main .Net to JS entrypoint (synchronous)
142
+ // The frame at address holds the whole call (see JSTape.cs). The result is written back over the frame and
143
+ // the return value is its byte length - or minus the bytes it needs when it does not fit in capacity, in
144
+ // which case it is kept on the instance for _spawnJSInteropCallResult.
145
+ // JSImport
146
+ // int _spawnJSInteropCall(double dotnetId, double address, int length, int capacity);
147
+ static _spawnJSInteropCall(dotnetId, address, length, capacity) {
148
+ // no detachedEventCheck(): _tapeViews checks this instance's heap, and walking every OTHER instance on
149
+ // every call was redundant - each is checked on its own calls and by the 500 ms timer
150
+ var instance = SpawnJSInterop.getInstace(dotnetId);
151
+ var call = SpawnJSInterop._tapeReadCall(instance, address, length, dotnetId);
152
+ var ret = call.target(...call.args);
153
+ ret = SpawnJSInterop.replaceValue(null, ret, false);
154
+ return SpawnJSInterop._tapeWriteResult(instance, call.returnType, ret, address, capacity);
155
+ }
156
+ // The result that did not fit behind its frame
157
+ // JSImport
158
+ // int _spawnJSInteropCallResult(double dotnetId, double address, int capacity);
159
+ static _spawnJSInteropCallResult(dotnetId, address, capacity) {
160
+ var instance = SpawnJSInterop.getInstace(dotnetId);
161
+ var bytes = instance.tapePendingResult;
162
+ instance.tapePendingResult = undefined;
163
+ if (!bytes) throw new Error('SpawnJSInterop: no tape result is being held');
164
+ if (bytes.byteLength > capacity) throw new Error(`SpawnJSInterop: a held tape result of ${bytes.byteLength} bytes does not fit in ${capacity}`);
165
+ var views = SpawnJSInterop._tapeViews(instance, address + bytes.byteLength);
166
+ new Uint8Array(views.buffer, address, bytes.byteLength).set(bytes);
167
+ return bytes.byteLength;
168
+ }
169
+ // Main .Net to JS entrypoint (asynchronous)
170
+ // Reads the frame and starts the call before returning, because .Net releases the frame as soon as this returns.
171
+ // Returns 1 when the frame was read and the call started, 0 when it could not be read - that failure has already
172
+ // gone to the resolver, so the awaiting Task fails rather than hanging.
173
+ // JSImport
174
+ // int _spawnJSInteropCallAsync(double dotnetId, double asyncCallId, double address, int length);
175
+ static _spawnJSInteropCallAsync(dotnetId, asyncCallId, address, length) {
176
+ var instance = SpawnJSInterop.getInstace(dotnetId);
177
+ var returnType = SpawnJSInterop._tapeViews(instance, address + length).f64[(address >>> 3) + 1];
178
+ var call;
179
+ try {
180
+ call = SpawnJSInterop._tapeReadCall(instance, address, length, dotnetId);
181
+ } catch (ex) {
182
+ SpawnJSInterop._resolveAsync(instance, returnType, asyncCallId, null, SpawnJSInterop.errorToString(ex));
183
+ return 0;
184
+ }
185
+ SpawnJSInterop._runAsync(instance, returnType, asyncCallId, call);
186
+ return 1;
187
+ }
188
+ static async _runAsync(instance, returnType, asyncCallId, call) {
189
+ var error = null;
190
+ var ret = null;
191
+ var heldBytes = -1;
192
+ try {
193
+ ret = call.target(...call.args);
194
+ ret = await ret;
195
+ ret = SpawnJSInterop.replaceValue(null, ret, false);
196
+ if (returnType > 10) {
197
+ // a composite schema: encoded here and held; .Net fetches it with _spawnJSInteropCallResult
198
+ heldBytes = SpawnJSInterop._tapeHoldResult(instance, SpawnJSInterop._tapeSchema(instance, returnType), ret);
199
+ } else {
200
+ // prepare using returnType
201
+ ret = SpawnJSInterop._serializeToNet(returnType, ret);
202
+ }
203
+ } catch (ex) {
204
+ error = SpawnJSInterop.errorToString(ex);
205
+ ret = null;
206
+ }
207
+ if (heldBytes >= 0) instance.resolveTape(asyncCallId, heldBytes, null);
208
+ else SpawnJSInterop._resolveAsync(instance, returnType, asyncCallId, ret, error);
209
+ }
210
+ static _resolveAsync(instance, returnType, asyncCallId, ret, error) {
211
+ if (returnType > 10) {
212
+ // a composite schema that failed: nothing is held
213
+ instance.resolveTape(asyncCallId, 0, error ?? 'SpawnJSInterop: the call produced no result');
214
+ return;
215
+ }
216
+ switch (returnType) {
217
+ case 0: // void
218
+ instance.resolveVoid(asyncCallId, error);
219
+ break;
220
+ case 1: // Double
221
+ instance.resolveDouble(asyncCallId, ret, error);
222
+ break;
223
+ case 2: // Boolean
224
+ instance.resolveBoolean(asyncCallId, ret, error);
225
+ break;
226
+ case 3: // DoubleNullable
227
+ instance.resolveDoubleNullable(asyncCallId, ret, error);
228
+ break;
229
+ case 4: // BooleanNullable
230
+ instance.resolveBooleanNullable(asyncCallId, ret, error);
231
+ break;
232
+ case 5: // String
233
+ instance.resolveString(asyncCallId, ret, error);
234
+ break;
235
+ case 6: // SpawnJSObject
236
+ instance.resolveDouble(asyncCallId, ret, error);
237
+ break;
238
+ case 7: // SpawnJSObjectNonNullable
239
+ instance.resolveDouble(asyncCallId, ret, error);
240
+ break;
241
+ case 8: // Json
242
+ instance.resolveString(asyncCallId, ret, error);
243
+ break;
244
+ case 9: // Int32
245
+ instance.resolveInt32(asyncCallId, ret, error);
246
+ break;
247
+ case 10: // Int32Nullable
248
+ instance.resolveInt32Nullable(asyncCallId, ret, error);
249
+ break;
250
+ default:
251
+ throw new Error(`Unsupported returnType ${returnType}`);
252
+ break;
253
+ }
254
+ }
255
+ // The heap views a tape is read through. Kept on the instance - never a page global - and rebuilt when the
256
+ // heap buffer changes: growth detaches it, and a shared (threaded) heap's buffer does not detach but can be
257
+ // shorter than the memory, so end is checked too.
258
+ static _tapeViews(instance, end) {
259
+ var buffer = instance.getHeap();
260
+ if (buffer.byteLength < end) {
261
+ buffer = instance.heapBuffer = SpawnJSInterop.wasmMemoryBuffer(instance.dotnet);
262
+ instance.heapBufferSize = buffer.byteLength;
263
+ }
264
+ var views = instance.tapeViews;
265
+ if (!views || views.buffer !== buffer) {
266
+ views = instance.tapeViews = { buffer, f64: new Float64Array(buffer), i32: new Int32Array(buffer), u16: new Uint16Array(buffer) };
267
+ }
268
+ return views;
269
+ }
270
+ // Reads a call frame: header, then one tagged value per argument, each passed through the revivers as the
271
+ // v2 argument array was.
272
+ static _tapeReadCall(instance, address, length, dotnetId) {
273
+ var views = SpawnJSInterop._tapeViews(instance, address + length);
274
+ var f64 = views.f64;
275
+ var p = address >>> 3;
276
+ var methodIndex = f64[p];
277
+ var returnType = f64[p + 1];
278
+ var argCount = f64[p + 2];
279
+ // one reader per call: a nested call (a reviver can run .Net) gets its own
280
+ var reader = { instance, dotnetId, address, length, views, p: p + 3 };
281
+ var args = new Array(argCount);
282
+ for (var i = 0; i < argCount; i++) {
283
+ var value = SpawnJSInterop._tapeRead(reader);
284
+ args[i] = SpawnJSInterop.reviveValue(i, value === SpawnJSInterop._tapeAbsent ? undefined : value, false);
285
+ }
286
+ // then the definitions of any schema the result is written by (JSTape.WriteSchemaDefinitions)
287
+ var end = (address + length) >>> 3;
288
+ while (reader.p < end) SpawnJSInterop._tapeReadSchemaDefinition(reader);
289
+ var target = SpawnJSInterop._methodMap[methodIndex];
290
+ if (!target) throw new Error(`SpawnJSInterop: no method at index ${methodIndex}`);
291
+ return { target, returnType, args };
292
+ }
293
+ // Reads one tagged value at reader.p and advances it. Object members and array elements go through the
294
+ // revivers with their key, as v2's per-property set did.
295
+ static _tapeRead(reader) {
296
+ // a reviver can run .Net (a heap view refresh reports the detach), which can grow the heap
297
+ if (reader.views.buffer.detached) reader.views = SpawnJSInterop._tapeViews(reader.instance, reader.address + reader.length);
298
+ var f64 = reader.views.f64;
299
+ var tag = f64[reader.p++];
300
+ switch (tag) {
301
+ case 0: return undefined;
302
+ case 1: return null;
303
+ case 2: return f64[reader.p++];
304
+ case 3: return f64[reader.p++] !== 0;
305
+ case 4: return SpawnJSInterop._tapeReadChars(reader);
306
+ case 5: return SpawnJSInterop.spawnJSObjectGet(f64[reader.p++]);
307
+ case 6: {
308
+ var callbackId = f64[reader.p++];
309
+ var once = f64[reader.p++] !== 0;
310
+ // the schemas its arguments are written by (defined after this frame's arguments when new)
311
+ var argumentCount = f64[reader.p++];
312
+ var argumentSchemas = new Array(argumentCount);
313
+ for (var i = 0; i < argumentCount; i++) argumentSchemas[i] = f64[reader.p++];
314
+ return SpawnJSInterop._callbackFunction(reader.dotnetId, callbackId, once, argumentSchemas);
315
+ }
316
+ case 8: return SpawnJSInterop._tapeAbsent;
317
+ case 9: {
318
+ var names = reader.instance.tapeShapes?.[f64[reader.p]];
319
+ if (!names) throw new Error(`SpawnJSInterop: unknown tape shape ${f64[reader.p]}`);
320
+ reader.p++;
321
+ var obj = {};
322
+ for (var i = 0; i < names.length; i++) {
323
+ var value = SpawnJSInterop._tapeRead(reader);
324
+ if (value !== SpawnJSInterop._tapeAbsent) obj[names[i]] = SpawnJSInterop.reviveValue(names[i], value, false);
325
+ }
326
+ return obj;
327
+ }
328
+ case 10: {
329
+ // a shape definition - kept per instance, since each runtime numbers its own - then the value it
330
+ // precedes. The same definition can arrive again until .Net knows a call carrying it completed.
331
+ var shapeId = f64[reader.p++];
332
+ var count = f64[reader.p++];
333
+ var names = new Array(count);
334
+ for (var i = 0; i < count; i++) names[i] = SpawnJSInterop._tapeReadChars(reader);
335
+ (reader.instance.tapeShapes ??= [])[shapeId] = names;
336
+ return SpawnJSInterop._tapeRead(reader);
337
+ }
338
+ case 11: {
339
+ var count = f64[reader.p++];
340
+ var array = new Array(count);
341
+ for (var i = 0; i < count; i++) {
342
+ var value = SpawnJSInterop._tapeRead(reader);
343
+ array[i] = SpawnJSInterop.reviveValue(i, value === SpawnJSInterop._tapeAbsent ? undefined : value, false);
344
+ }
345
+ return array;
346
+ }
347
+ case 12: {
348
+ var ctor = SpawnJSInterop.TapeNumberCtors[f64[reader.p++]];
349
+ var count = f64[reader.p++];
350
+ var view = new ctor(reader.views.buffer, reader.p * 8, count);
351
+ reader.p += (count * ctor.BYTES_PER_ELEMENT + 7) >>> 3;
352
+ // a plain Array, as element-by-element writing produced; a TypedArray stays opt in
353
+ return Array.from(view);
354
+ }
355
+ case 14: {
356
+ var count = reader.views.f64[reader.p++];
357
+ var record = {};
358
+ for (var i = 0; i < count; i++) {
359
+ var key = SpawnJSInterop._tapeReadChars(reader);
360
+ var value = SpawnJSInterop._tapeRead(reader);
361
+ record[key] = SpawnJSInterop.reviveValue(key, value === SpawnJSInterop._tapeAbsent ? undefined : value, false);
362
+ }
363
+ return record;
364
+ }
365
+ case 15: {
366
+ var reviver = SpawnJSInterop._methodMap[reader.views.f64[reader.p++]];
367
+ if (!reviver) throw new Error('SpawnJSInterop: tape reviver not found');
368
+ // (key, value, directCall) - the v2 property reviver convention; there is no property key here
369
+ return reviver(null, SpawnJSInterop._tapeRead(reader), true);
370
+ }
371
+ case 13: {
372
+ var f = reader.views.f64;
373
+ var viewType = f[reader.p], offset = f[reader.p + 1], count = f[reader.p + 2], copy = f[reader.p + 3] !== 0;
374
+ reader.p += 4;
375
+ return SpawnJSInterop._heapView(reader.dotnetId, viewType, offset, count, copy);
376
+ }
377
+ default: throw new Error(`SpawnJSInterop: unknown tape tag ${tag} at cell ${reader.p - 1}`);
378
+ }
379
+ }
380
+ // length, then UTF-16 code units padded to a cell
381
+ static _tapeReadChars(reader) {
382
+ var length = reader.views.f64[reader.p++];
383
+ var value = SpawnJSInterop._tapeString(reader.views.u16, reader.p * 4, length);
384
+ reader.p += (length + 3) >>> 2;
385
+ return value;
386
+ }
387
+ // String.fromCharCode keeps every UTF-16 code unit exactly - a lone surrogate included, which a TextDecoder
388
+ // would replace. Chunked, because apply() has an argument count limit.
389
+ static _tapeString(u16, index, length) {
390
+ if (length <= 1024) return String.fromCharCode.apply(null, u16.subarray(index, index + length));
391
+ var parts = [];
392
+ for (var i = 0; i < length; i += 1024) {
393
+ parts.push(String.fromCharCode.apply(null, u16.subarray(index + i, index + Math.min(i + 1024, length))));
394
+ }
395
+ return parts.join('');
396
+ }
397
+ // ---- results: written back by the schema .Net reads them with (JSSchema.cs, JSTapeReader.cs) ----
398
+ // Ids 0-10 are the built-in ReturnType kinds; composite schemas are defined per instance, after a call's arguments.
399
+ static _builtinSchemas = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(kind => Object.freeze({ kind }));
400
+ // thrown by a writer over .Net memory that is out of room (only a string can be; it is written again)
401
+ static _tapeOverflow = Object.freeze({ tapeOverflow: true });
402
+ static _tapeSchema(instance, id) {
403
+ if (id <= 10) return SpawnJSInterop._builtinSchemas[id];
404
+ var schema = instance.tapeSchemas?.[id];
405
+ if (!schema) throw new Error(`SpawnJSInterop: unknown tape schema ${id}`);
406
+ return schema;
407
+ }
408
+ // TagSchema, id, kind, then per kind - member / element schemas are ids, resolved when a value is written, so a
409
+ // schema can refer to one defined after it, or to itself
410
+ static _tapeReadSchemaDefinition(reader) {
411
+ if (reader.views.buffer.detached) reader.views = SpawnJSInterop._tapeViews(reader.instance, reader.address + reader.length);
412
+ var f64 = reader.views.f64;
413
+ var tag = f64[reader.p++];
414
+ if (tag !== 16) throw new Error(`SpawnJSInterop: expected a tape schema definition, found tag ${tag}`);
415
+ var id = f64[reader.p++];
416
+ var schema = { kind: f64[reader.p++] };
417
+ switch (schema.kind) {
418
+ case 16: {
419
+ var count = f64[reader.p++];
420
+ schema.names = new Array(count);
421
+ for (var i = 0; i < count; i++) schema.names[i] = SpawnJSInterop._tapeReadChars(reader);
422
+ schema.members = new Array(count);
423
+ for (var i = 0; i < count; i++) schema.members[i] = reader.views.f64[reader.p++];
424
+ break;
425
+ }
426
+ case 20: {
427
+ var count = f64[reader.p++];
428
+ schema.members = new Array(count);
429
+ for (var i = 0; i < count; i++) schema.members[i] = f64[reader.p++];
430
+ break;
431
+ }
432
+ case 17: case 19: schema.element = f64[reader.p++]; break;
433
+ case 18: schema.numberKind = f64[reader.p++]; break;
434
+ }
435
+ (reader.instance.tapeSchemas ??= [])[id] = schema;
436
+ }
437
+ // Writes a call's result back over its own frame. A built-in kind goes straight into .Net memory (only a string
438
+ // can outgrow the frame's segment); a composite is written into Javascript memory first, then copied - it can
439
+ // hold references and run getters, so it is written exactly once. A result that does not fit is held for
440
+ // _spawnJSInteropCallResult, and the return value is minus its size.
441
+ static _tapeWriteResult(instance, schemaId, ret, address, capacity) {
442
+ var schema = SpawnJSInterop._tapeSchema(instance, schemaId);
443
+ if (schema.kind === 0) return 0;
444
+ if (schemaId <= 10) {
445
+ var views = SpawnJSInterop._tapeViews(instance, address + capacity);
446
+ var w = { buffer: views.buffer, f64: views.f64, i32: views.i32, u16: views.u16, p: address >>> 3, end: (address + capacity) >>> 3, scratch: false };
447
+ try {
448
+ SpawnJSInterop._tapeEncode(instance, w, schema, ret);
449
+ return (w.p - (address >>> 3)) * 8;
450
+ } catch (ex) {
451
+ if (ex !== SpawnJSInterop._tapeOverflow) throw ex;
452
+ }
453
+ }
454
+ var s = SpawnJSInterop._tapeScratchWriter(instance);
455
+ try {
456
+ SpawnJSInterop._tapeEncode(instance, s, schema, ret);
457
+ var bytes = s.p * 8;
458
+ if (bytes <= capacity) {
459
+ var heap = SpawnJSInterop._tapeViews(instance, address + bytes);
460
+ new Uint8Array(heap.buffer, address, bytes).set(new Uint8Array(s.buffer, 0, bytes));
461
+ return bytes;
462
+ }
463
+ instance.tapePendingResult = new Uint8Array(s.buffer.slice(0, bytes));
464
+ return -bytes;
465
+ } finally {
466
+ SpawnJSInterop._tapeScratchRelease(instance, s);
467
+ }
468
+ }
469
+ // encodes a result and holds it for _spawnJSInteropCallResult; returns its size
470
+ static _tapeHoldResult(instance, schema, value) {
471
+ var s = SpawnJSInterop._tapeScratchWriter(instance);
472
+ try {
473
+ SpawnJSInterop._tapeEncode(instance, s, schema, value);
474
+ instance.tapePendingResult = new Uint8Array(s.buffer.slice(0, s.p * 8));
475
+ return s.p * 8;
476
+ } finally {
477
+ SpawnJSInterop._tapeScratchRelease(instance, s);
478
+ }
479
+ }
480
+ // Javascript-side result buffers, pooled per instance (a nested call's result uses its own)
481
+ static _tapeScratchWriter(instance) {
482
+ var w = instance.tapeScratch?.pop();
483
+ if (!w) {
484
+ w = { scratch: true, p: 0 };
485
+ SpawnJSInterop._tapeScratchResize(w, 512);
486
+ }
487
+ w.p = 0;
488
+ return w;
489
+ }
490
+ static _tapeScratchRelease(instance, w) {
491
+ // a very large one is dropped rather than kept for the life of the page
492
+ if (w.end <= 1 << 20) (instance.tapeScratch ??= []).push(w);
493
+ }
494
+ static _tapeScratchResize(w, cells) {
495
+ var buffer = new ArrayBuffer(cells * 8);
496
+ if (w.buffer) new Uint8Array(buffer).set(new Uint8Array(w.buffer, 0, w.p * 8));
497
+ w.buffer = buffer;
498
+ w.f64 = new Float64Array(buffer);
499
+ w.i32 = new Int32Array(buffer);
500
+ w.u16 = new Uint16Array(buffer);
501
+ w.end = cells;
502
+ }
503
+ static _tapeNeed(w, cells) {
504
+ if (w.p + cells <= w.end) return;
505
+ if (!w.scratch) throw SpawnJSInterop._tapeOverflow;
506
+ SpawnJSInterop._tapeScratchResize(w, Math.max(w.end * 2, w.p + cells));
507
+ }
508
+ // One value by its schema. The built-in kinds convert exactly as v2's typed returns did: null/undefined read
509
+ // as 0 / false, a number is stored through a Float64Array (ToNumber) and an int through an Int32Array (ToInt32).
510
+ // A composite reads each member / element with that member's schema - what v2's per-property Get<T> read.
511
+ static _tapeEncode(instance, w, schema, v) {
512
+ var isNull = v === null || v === undefined;
513
+ switch (schema.kind) {
514
+ case 0: return;
515
+ case 1:
516
+ SpawnJSInterop._tapeNeed(w, 1);
517
+ w.f64[w.p++] = isNull ? 0 : v;
518
+ return;
519
+ case 2:
520
+ SpawnJSInterop._tapeNeed(w, 1);
521
+ w.f64[w.p++] = v ? 1 : 0;
522
+ return;
523
+ case 3:
524
+ if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; }
525
+ SpawnJSInterop._tapeNeed(w, 2);
526
+ w.f64[w.p++] = 2;
527
+ w.f64[w.p++] = v;
528
+ return;
529
+ case 4:
530
+ if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; }
531
+ SpawnJSInterop._tapeNeed(w, 2);
532
+ w.f64[w.p++] = 3;
533
+ w.f64[w.p++] = v ? 1 : 0;
534
+ return;
535
+ case 5:
536
+ if (!isNull && typeof v !== 'string') v = Object(v).toString();
537
+ SpawnJSInterop._tapeEncodeString(w, isNull ? null : v);
538
+ return;
539
+ case 6: case 7:
540
+ SpawnJSInterop._tapeNeed(w, 1);
541
+ w.f64[w.p++] = SpawnJSInterop.spawnJSObjectHold(v);
542
+ return;
543
+ case 8:
544
+ SpawnJSInterop._tapeEncodeString(w, JSON.stringify(v));
545
+ return;
546
+ case 9:
547
+ SpawnJSInterop._tapeNeed(w, 1);
548
+ w.i32[w.p * 2] = isNull ? 0 : v;
549
+ w.p++;
550
+ return;
551
+ case 10:
552
+ if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; }
553
+ SpawnJSInterop._tapeNeed(w, 2);
554
+ w.f64[w.p] = 2;
555
+ w.i32[(w.p + 1) * 2] = v;
556
+ w.p += 2;
557
+ return;
558
+ case 16: {
559
+ if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; }
560
+ SpawnJSInterop._tapeNeed(w, 1);
561
+ w.f64[w.p++] = 9;
562
+ var names = schema.names, members = schema.members;
563
+ for (var i = 0; i < names.length; i++) SpawnJSInterop._tapeEncode(instance, w, SpawnJSInterop._tapeSchema(instance, members[i]), v[names[i]]);
564
+ return;
565
+ }
566
+ case 17: {
567
+ if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; }
568
+ var count = Number(v.length) || 0;
569
+ SpawnJSInterop._tapeNeed(w, 2);
570
+ w.f64[w.p++] = 11;
571
+ w.f64[w.p++] = count;
572
+ var element = SpawnJSInterop._tapeSchema(instance, schema.element);
573
+ for (var i = 0; i < count; i++) SpawnJSInterop._tapeEncode(instance, w, element, v[i]);
574
+ return;
575
+ }
576
+ case 18: {
577
+ if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; }
578
+ var count = Number(v.length) || 0;
579
+ var int32 = schema.numberKind === 9;
580
+ var cells = int32 ? (count + 1) >>> 1 : count;
581
+ SpawnJSInterop._tapeNeed(w, 2 + cells);
582
+ w.f64[w.p++] = 12;
583
+ w.f64[w.p++] = count;
584
+ // element by element, not typedArray.set(): an undefined element must read as 0, as Get<T> read it
585
+ if (int32) {
586
+ var view = new Int32Array(w.buffer, w.p * 8, count);
587
+ for (var i = 0; i < count; i++) { var e = v[i]; view[i] = e === null || e === undefined ? 0 : e; }
588
+ } else {
589
+ var view = new Float64Array(w.buffer, w.p * 8, count);
590
+ for (var i = 0; i < count; i++) { var e = v[i]; view[i] = e === null || e === undefined ? 0 : e; }
591
+ }
592
+ w.p += cells;
593
+ return;
594
+ }
595
+ case 19: {
596
+ if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; }
597
+ // own enumerable keys - inherited ones belong to the prototype chain, not the record
598
+ var keys = Object.keys(v);
599
+ SpawnJSInterop._tapeNeed(w, 2);
600
+ w.f64[w.p++] = 14;
601
+ w.f64[w.p++] = keys.length;
602
+ var element = SpawnJSInterop._tapeSchema(instance, schema.element);
603
+ for (var i = 0; i < keys.length; i++) {
604
+ SpawnJSInterop._tapeEncodeChars(w, keys[i]);
605
+ SpawnJSInterop._tapeEncode(instance, w, element, v[keys[i]]);
606
+ }
607
+ return;
608
+ }
609
+ case 20: {
610
+ if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; }
611
+ var members = schema.members;
612
+ SpawnJSInterop._tapeNeed(w, 2);
613
+ w.f64[w.p++] = 11;
614
+ w.f64[w.p++] = members.length;
615
+ for (var i = 0; i < members.length; i++) SpawnJSInterop._tapeEncode(instance, w, SpawnJSInterop._tapeSchema(instance, members[i]), v[i]);
616
+ return;
617
+ }
618
+ case 21: {
619
+ if (isNull) { SpawnJSInterop._tapeNeed(w, 1); w.f64[w.p++] = 1; return; }
620
+ var bytes = v instanceof ArrayBuffer ? new Uint8Array(v)
621
+ : ArrayBuffer.isView(v) ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength)
622
+ : null;
623
+ if (!bytes) throw new TypeError('SpawnJSInterop: expected an ArrayBuffer or ArrayBufferView');
624
+ var cells = (bytes.length + 7) >>> 3;
625
+ SpawnJSInterop._tapeNeed(w, 2 + cells);
626
+ w.f64[w.p++] = 12;
627
+ w.f64[w.p++] = bytes.length;
628
+ new Uint8Array(w.buffer, w.p * 8, bytes.length).set(bytes);
629
+ w.p += cells;
630
+ return;
631
+ }
632
+ }
633
+ throw new Error(`SpawnJSInterop: unsupported tape schema kind ${schema.kind}`);
634
+ }
635
+ // null, or tag, length, UTF-16 code units
636
+ static _tapeEncodeString(w, value) {
637
+ if (value === null || value === undefined) {
638
+ SpawnJSInterop._tapeNeed(w, 1);
639
+ w.f64[w.p++] = 1;
640
+ return;
641
+ }
642
+ SpawnJSInterop._tapeNeed(w, 1);
643
+ w.f64[w.p++] = 4;
644
+ SpawnJSInterop._tapeEncodeChars(w, value);
645
+ }
646
+ // length, UTF-16 code units padded to a cell
647
+ static _tapeEncodeChars(w, value) {
648
+ var length = value.length;
649
+ SpawnJSInterop._tapeNeed(w, 1 + ((length + 3) >>> 2));
650
+ w.f64[w.p++] = length;
651
+ var u16 = w.u16;
652
+ var index = w.p * 4;
653
+ for (var i = 0; i < length; i++) u16[index + i] = value.charCodeAt(i);
654
+ w.p += (length + 3) >>> 2;
655
+ }
656
+ // refreshes the method map by looking for any new methods and adds them
657
+ // JSImport
658
+ // string[] _refreshMethodMap();
659
+ static refreshMethodMap() {
660
+ var changed = false;
661
+ var keys = Reflect.ownKeys(SpawnJSInterop);
662
+ for (const pName of keys) {
663
+ if (SpawnJSInterop._methodMapNames.indexOf(pName) !== -1) continue;
664
+ var propVal = SpawnJSInterop[pName];
665
+ if (typeof propVal === 'function') {
666
+ var fn = propVal.bind(SpawnJSInterop);
667
+ changed = true;
668
+ SpawnJSInterop._methodMap.push(fn);
669
+ SpawnJSInterop._methodMapNames.push(pName);
670
+ if (pName.indexOf('__reviver') === 0) {
671
+ SpawnJSInterop._revivers.push(fn);
672
+ } else if (pName.indexOf('__replacer') === 0) {
673
+ SpawnJSInterop._replacers.push(fn);
674
+ }
675
+ }
676
+ }
677
+ if (changed) {
678
+ // notify existing instances
679
+ for (const dotnetIdExisting in SpawnJSInterop._instances) {
680
+ if (Object.hasOwn(SpawnJSInterop._instances, dotnetIdExisting)) {
681
+ var existingInfo = SpawnJSInterop._instances[dotnetIdExisting];
682
+ try {
683
+ existingInfo.onMethodAdded();
684
+ } catch { }
685
+ }
686
+ }
687
+ }
688
+ return SpawnJSInterop._methodMapNames;
689
+ }
690
+ // JSImport
691
+ // void _releaseCallback(double dotnetId, double callbackId);
692
+ static releaseCallback(dotnetId, callbackId) {
693
+ var callbackIdPair = `${dotnetId}_${callbackId}`;
694
+ delete SpawnJSInterop._callbacks[callbackIdPair];
695
+ }
696
+ // removes the object from the hold and returns it
697
+ // JSImport
698
+ // void SpawnJSObjectRelease(double sjsId);
699
+ // bool SpawnJSObjectReleaseBoolean(double sjsId);
700
+ // double SpawnJSObjectReleaseDouble(double sjsId);
701
+ // int SpawnJSObjectReleaseInt32(double sjsId);
702
+ // bool? SpawnJSObjectReleaseBooleanNullable(double sjsId);
703
+ // int? SpawnJSObjectReleaseInt32Nullable(double sjsId);
704
+ // double? SpawnJSObjectReleaseDoubleNullable(double sjsId);
705
+ static spawnJSObjectRelease(sjsId) {
706
+ var ret = SpawnJSInterop.spawnJSObjectGet(sjsId);
707
+ delete SpawnJSInterop.spawnJSObjects[sjsId];
708
+ if (SpawnJSInterop.verbose) console.log('spawnJSObjectRelease. Count:', Object.keys(SpawnJSInterop.spawnJSObjects).length, 'Id:', sjsId);
709
+ return ret;
710
+ }
711
+ // removes the object from the hold, JSON.stringifies it and returns it
712
+ // JSImport
713
+ // string SpawnJSObjectReleaseJson(double sjsId);
714
+ static spawnJSObjectReleaseAsJson(sjsId) {
715
+ var ret = SpawnJSInterop.spawnJSObjectGet(sjsId);
716
+ delete SpawnJSInterop.spawnJSObjects[sjsId];
717
+ return JSON.stringify(ret);
718
+ }
719
+ // returns true if the item id exists in the hold
720
+ // JSImport
721
+ // bool SpawnJSObjectHoldExists(double sjsId);
722
+ static spawnJSObjectHoldExists(sjsId) {
723
+ switch (sjsId) {
724
+ case -1: return true;
725
+ case -2: return true;
726
+ case -3: return true;
727
+ case -4: return true;
728
+ case -5: return true;
729
+ }
730
+ return sjsId in SpawnJSInterop.spawnJSObjects;
731
+ }
732
+ // returns string
733
+ // JSImport
734
+ // string _getTypeInfo(double sjsId);
735
+ static getTypeInfo(sjsId) {
736
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
737
+ var jsClass = Object.prototype.toString.call(obj).split(' ')[1].slice(0, -1);
738
+ var jsType = typeof (obj);
739
+ return `${jsType} ${jsClass}`;
740
+ }
741
+
742
+ // **************************************************************************************
743
+ // SpawnJSObjectReference imports
744
+ // Note: only `string key` imports shown. Also exists: `double key`, `int key`
745
+ // **************************************************************************************
746
+
747
+ // property info
748
+ // returns string or null if the property was not found
749
+ // JSImport
750
+ // string _propertyTypeInfo(double sjsId, string key);
751
+ static propertyTypeInfo(sjsId, key) {
752
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
753
+ var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key);
754
+ if (shortCircuit) return null;
755
+ if (!SpawnJSInterop._in(propertyName, parent)) return null;
756
+ var value = parent[propertyName];
757
+ var jsClass = Object.prototype.toString.call(value).split(' ')[1].slice(0, -1);
758
+ var jsType = typeof (value);
759
+ return `${jsType} ${jsClass}`;
760
+ }
761
+ // deletes property
762
+ // JSImport
763
+ // bool _propertyDelete(double sjsId, string key);
764
+ static propertyDelete(sjsId, key) {
765
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
766
+ if (obj === void 0 || obj === null) throw new Error('obj null or undefined');
767
+ var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key);
768
+ if (shortCircuit) return true;
769
+ return delete parent[propertyName];
770
+ }
771
+ // returns bool if the key is in the target
772
+ // JSImport
773
+ // bool _propertyIn(double sjsId, string key);
774
+ static propertyIn(sjsId, key) {
775
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
776
+ if (obj === void 0 || obj === null) throw new Error('obj null or undefined');
777
+ var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key);
778
+ if (shortCircuit) return false;
779
+ return SpawnJSInterop._in(propertyName, parent);
780
+ }
781
+ // get a property
782
+ // InteropCall (dispatched through the call tape)
783
+ static propertyGet(sjsId, key) {
784
+ var ret = undefined;
785
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
786
+ var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key);
787
+ if (pathInfo.shortCircuit) return ret;
788
+ if (typeof pathInfo.target === 'function') {
789
+ ret = pathInfo.target.bind(pathInfo.parent);
790
+ } else {
791
+ ret = pathInfo.target;
792
+ }
793
+ return ret;
794
+ }
795
+ // set property
796
+ // InteropCall (dispatched through the call tape)
797
+ static propertySet(sjsId, key, value) {
798
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
799
+ if (obj === void 0 || obj === null) throw new Error('obj null or undefined');
800
+ var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key);
801
+ if (shortCircuit) return;
802
+ // revivers
803
+ value = SpawnJSInterop.reviveValue(propertyName, value, false);
804
+ parent[propertyName] = value;
805
+ }
806
+ // A view of - or with copy, a copy of - .Net memory. A live view carries its _heapViewInfo so the heap view
807
+ // reviver can rebuild it after the heap grows. Built when the tape reads a TagHeapView.
808
+ static _heapView(dotnetId, viewType, offset, length, copy) {
809
+ // create the heapView meta data
810
+ var heapViewInfo = { dotnetId, viewType, offset, length, copy };
811
+ // viewType is an INDEX into HeapViewCtors, and index 0 (BigInt64Array) is a real value - a
812
+ // falsy check would read it as "missing" and silently rewrite it. The default is the
813
+ // Uint8Array index, not its name: this value is used as an index, never as a lookup key.
814
+ if (heapViewInfo.viewType === undefined || heapViewInfo.viewType === null) heapViewInfo.viewType = 10;
815
+ heapViewInfo.instance = SpawnJSInterop.getInstace(heapViewInfo.dotnetId);
816
+ heapViewInfo.dotnet = SpawnJSInterop.spawnJSObjectGet(heapViewInfo.dotnetId);
817
+ heapViewInfo.sizeHistory = [];
818
+ heapViewInfo.ctor = SpawnJSInterop.getArrayBufferViewConstructor(heapViewInfo.viewType);
819
+ // refresh the heapView
820
+ return SpawnJSInterop.heapViewRefresh(heapViewInfo);
821
+ }
822
+ // The Javascript function that invokes a .Net Callback, created once per callback and reused
823
+ // .Net gives each instance a pinned buffer that a callback's arguments are written into before it calls .Net
824
+ // JSImport
825
+ // void _registerInbound(double dotnetId, double address, int cells);
826
+ static _registerInbound(dotnetId, address, cells) {
827
+ // cell 0 carries the offset of the arguments of the callback being called
828
+ SpawnJSInterop.getInstace(dotnetId).inbound = { address, cells, top: 1 };
829
+ }
830
+ // Writes a callback's arguments by their schemas into the instance's inbound buffer, as a stack (a callback can
831
+ // run inside another), and puts their offset in cell 0. Arguments too large for the space left are held for
832
+ // _spawnJSInteropCallResult instead, and cell 0 is minus their size. Returns the top to restore afterwards.
833
+ static _tapeWriteInbound(instance, argumentSchemas, args) {
834
+ var inbound = instance.inbound;
835
+ var top = inbound.top;
836
+ var s = SpawnJSInterop._tapeScratchWriter(instance);
837
+ try {
838
+ for (var i = 0; i < argumentSchemas.length; i++) {
839
+ SpawnJSInterop._tapeEncode(instance, s, SpawnJSInterop._tapeSchema(instance, argumentSchemas[i]), args[i]);
840
+ }
841
+ var views = SpawnJSInterop._tapeViews(instance, inbound.address + inbound.cells * 8);
842
+ var offset;
843
+ if (top + s.p <= inbound.cells) {
844
+ new Uint8Array(views.buffer, inbound.address + top * 8, s.p * 8).set(new Uint8Array(s.buffer, 0, s.p * 8));
845
+ offset = top;
846
+ inbound.top = top + s.p;
847
+ } else {
848
+ instance.tapePendingResult = new Uint8Array(s.buffer.slice(0, s.p * 8));
849
+ offset = -(s.p * 8);
850
+ }
851
+ views.f64[inbound.address >>> 3] = offset;
852
+ } finally {
853
+ SpawnJSInterop._tapeScratchRelease(instance, s);
854
+ }
855
+ return top;
856
+ }
857
+ static _callbackFunction(dotnetId, callbackId, once, argumentSchemas) {
858
+ if (!callbackId || !dotnetId) {
859
+ return null;
860
+ }
861
+ // get callback id that is globally unique
862
+ var callbackIdPair = `${dotnetId}_${callbackId}`;
863
+ // check if it exists and createa new function if not
864
+ var value = SpawnJSInterop._callbacks[callbackIdPair];
865
+ if (!value) {
866
+ value = function (...args) {
867
+ // check if the callback has been removed
868
+ if (!SpawnJSInterop._callbacks[callbackIdPair]) {
869
+ return;
870
+ }
871
+ // get the SpawnJSRuntime instance's method that is used to report the callback
872
+ var instance = SpawnJSInterop.getInstace(dotnetId);
873
+ var { handleCallback } = instance;
874
+ // get argsCnt because after when we call handleCallback .Net will write
875
+ // the return value to at the end of the array after the last argument (index argsCnt)
876
+ // unless the return value should be undefined
877
+ var argsCnt = args.length;
878
+ // get a temporary hold of the args (released after we notify SpawnJSRuntime)
879
+ var argsId = SpawnJSInterop.spawnJSObjectHold(args);
880
+ // ⚠️ try/finally, NOT straight-line. .Net deliberately does not release this slot
881
+ // itself - that would cost an extra crossing per callback - so the ONLY release is
882
+ // here. If handleCallback throws (any exception escaping the .Net handler crosses
883
+ // back through here) a straight-line release is SKIPPED and the args array is
884
+ // stranded in spawnJSObjects for the life of the page. Same for the `once` cleanup:
885
+ // a one-shot callback that threw would never be removed and would keep firing.
886
+ // MEASURED 2026-09-02: dumping the table mid-run in the ML demo showed ~30 stranded
887
+ // empty arrays alongside the retained adapters.
888
+ // the arguments go to .Net memory now, so the call below is the only crossing they need
889
+ var inboundTop = SpawnJSInterop._tapeWriteInbound(instance, argumentSchemas ?? [], args);
890
+ try {
891
+ // notify SpawnJSRuntime with the argsId and the cnt
892
+ handleCallback(callbackId, argsId, argsCnt);
893
+ } finally {
894
+ instance.inbound.top = inboundTop;
895
+ // release the args
896
+ SpawnJSInterop.spawnJSObjectRelease(argsId);
897
+ // if it was a 1 time use callback, release it
898
+ if (once) delete SpawnJSInterop._callbacks[callbackIdPair];
899
+ }
900
+ // return what is in index argsCnt (the designated place .Net will write to if there is a return value)
901
+ return args[argsCnt];
902
+ };
903
+ SpawnJSInterop._callbacks[callbackIdPair] = value;
904
+ }
905
+ return value;
906
+ }
907
+
908
+ // Interop Calls
909
+ // Interop calls are calls made indirectly via _spawnJSInteropCall and _spawnJSInteropCallAsync.
910
+ // Because they go through those methods they can return and recieve any data type the marshallers support
911
+
912
+ // call a property constructor
913
+ // InteropCall
914
+ // SpawnJSObjectReference
915
+ // <double, string, object?[]?, SpawnJSObjectReference>
916
+ static propertyNewApply(sjsId, key, args) {
917
+ var ret = undefined;
918
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
919
+ var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key);
920
+ if (pathInfo.shortCircuit) return ret;
921
+ var ret = !args ? new pathInfo.target() : new pathInfo.target(...args);
922
+ return ret;
923
+ }
924
+ // call a property constructor
925
+ // InteropCall
926
+ // SpawnJSObjectReference
927
+ // <double, string, ..., T>
928
+ static propertyNew(sjsId, key, ...args) {
929
+ var ret = undefined;
930
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
931
+ var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key);
932
+ if (pathInfo.shortCircuit) return ret;
933
+ var ret = !args ? new pathInfo.target() : new pathInfo.target(...args);
934
+ return ret;
935
+ }
936
+ // call a property
937
+ // InteropCall
938
+ // SpawnJSObjectReference
939
+ // <double, string, object?[]?, T>
940
+ static propertyCallApply(sjsId, key, args) {
941
+ var ret = undefined;
942
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
943
+ var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key);
944
+ if (pathInfo.shortCircuit) return ret;
945
+ var ret = pathInfo.target.apply(pathInfo.parent, args);
946
+ if (typeof ret === 'function') {
947
+ ret = ret.bind(pathInfo.parent);
948
+ }
949
+ return ret;
950
+ }
951
+ // call a property
952
+ // InteropCall
953
+ // SpawnJSObjectReference
954
+ // <double, string, ..., T>
955
+ static propertyCall(sjsId, key, ...args) {
956
+ var ret = undefined;
957
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
958
+ var pathInfo = SpawnJSInterop.pathObjectInfo(obj, key);
959
+ if (pathInfo.shortCircuit) return ret;
960
+ var ret = pathInfo.target.apply(pathInfo.parent, args);
961
+ if (typeof ret === 'function') {
962
+ ret = ret.bind(pathInfo.parent);
963
+ }
964
+ return ret;
965
+ }
966
+ // useful when .Net Wasm wants to clonme a JSObjectReference or simply convert from one type to another
967
+ // InteropCall
968
+ // SpawnJSObjectReference
969
+ // <TIn, TResult>
970
+ static returnMe(value) {
971
+ return value;
972
+ }
973
+ // InteropCall
974
+ // ByteArrayMarshaller
975
+ // <double, SpawnJSObjectReference, double, double, double, VoidType>
976
+ static writeArrayBufferViewToHeap(dotnetId, arrayBufferView, srcOffset, destOffset, byteLength) {
977
+ if (!arrayBufferView) throw new Error('writeArrayBufferViewToHeap arrayBufferView is required');
978
+ if (byteLength === 0) return 0;
979
+ var srcLength = arrayBufferView.byteLength;
980
+ if (byteLength == -1) byteLength = srcLength;
981
+ if (byteLength < -1) throw new Error('Invalid byteLength');
982
+ // get the .Net heap
983
+ var instance = SpawnJSInterop.getInstace(dotnetId);
984
+ var buffer = instance.getHeap();
985
+ var bufferView = new Uint8Array(buffer, destOffset, byteLength);
986
+ // get a view of the exact source we want
987
+ var offset = arrayBufferView.byteOffset + srcOffset;
988
+ var sourceView = new Uint8Array(arrayBufferView.buffer, offset, byteLength);
989
+ // copy to the .Net heap
990
+ bufferView.set(sourceView);
991
+ // return the bytes copied
992
+ return byteLength;
993
+ }
994
+ // called using Call<>
995
+ // InteropCall
996
+ // TaskMarshaller
997
+ // <double, int, SpawnJSObjectReference>
998
+ static propertySetNewPromise(sjsId, key) {
999
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
1000
+ if (obj === void 0 || obj === null) throw new Error('obj null or undefined');
1001
+ var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key);
1002
+ if (shortCircuit) return;
1003
+ var promise = SpawnJSInterop.newEasyPromise();
1004
+ parent[propertyName] = promise;
1005
+ return promise;
1006
+ }
1007
+ // called using Call<>
1008
+ // InteropCall
1009
+ // TaskMarshaller
1010
+ // <double, string, VoidType>
1011
+ static propertySetResolvedPromise(sjsId, key, value) {
1012
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
1013
+ if (obj === void 0 || obj === null) throw new Error('obj null or undefined');
1014
+ var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key);
1015
+ if (shortCircuit) return;
1016
+ parent[propertyName] = Promise.resolve(value);
1017
+ }
1018
+ // called using Call<>
1019
+ // InteropCall
1020
+ // TaskMarshaller
1021
+ // <double, string, string, VoidType>
1022
+ static propertySetRejectedPromise(sjsId, key, value) {
1023
+ var obj = SpawnJSInterop.spawnJSObjectGet(sjsId);
1024
+ if (obj === void 0 || obj === null) throw new Error('obj null or undefined');
1025
+ var { parent, propertyName, shortCircuit } = SpawnJSInterop.pathObjectInfo(obj, key);
1026
+ if (shortCircuit) return;
1027
+ parent[propertyName] = Promise.reject(value);
1028
+ }
1029
+ // InteropCall
1030
+ // SpawnJSRuntime
1031
+ // <double, long>
1032
+ static getHeapSize(dotnetId) {
1033
+ var instance = SpawnJSInterop.getInstace(dotnetId);
1034
+ var buffer = instance.getHeap();
1035
+ return buffer.byteLength;
1036
+ }
1037
+ // full ? strict equality : loose equality
1038
+ // InteropCall
1039
+ // SpawnJSRuntime
1040
+ // <T1, T2, bool, bool>
1041
+ static objectEquals(obj1, obj2, full) {
1042
+ return full ? obj1 === obj2 : obj1 == obj2;
1043
+ }
1044
+
1045
+ static detachedEventCheck() {
1046
+ for (const dotnetIdExisting in SpawnJSInterop._instances) {
1047
+ if (Object.hasOwn(SpawnJSInterop._instances, dotnetIdExisting)) {
1048
+ var instanceInfo = SpawnJSInterop._instances[dotnetIdExisting];
1049
+ instanceInfo.getHeap();
1050
+ }
1051
+ }
1052
+ }
1053
+ static getInstace(dotnetId) {
1054
+ return SpawnJSInterop._instances[dotnetId];
1055
+ }
1056
+ static _getInstaceFromDotNet(dotnet) {
1057
+ for (const dotnetIdExisting in SpawnJSInterop._instances) {
1058
+ if (Object.hasOwn(SpawnJSInterop._instances, dotnetIdExisting)) {
1059
+ var existingInfo = SpawnJSInterop._instances[dotnetIdExisting];
1060
+ if (existingInfo.dotnet == dotnet) {
1061
+ return existingInfo;
1062
+ }
1063
+ }
1064
+ }
1065
+ }
1066
+ static __replacerJson(key, value, directCall) {
1067
+ if (directCall) value = JSON.stringify(value);
1068
+ return value;
1069
+ }
1070
+ static __reviverJson(key, value, directCall) {
1071
+ if (directCall) value = JSON.parse(value);
1072
+ return value;
1073
+ }
1074
+ static _unregisterInstance(dotnetId) {
1075
+ delete SpawnJSInterop._instances[dotnetId];
1076
+ }
1077
+ static _getMappedMethodNames() {
1078
+ return SpawnJSInterop._methodMapNames;
1079
+ }
1080
+ // array of { name, reviver }
1081
+ static registerReplacers(replacers) {
1082
+ var cnt = 0;
1083
+ if (!replacers) return cnt;
1084
+ for (var replacerObj of replacers) {
1085
+ var succ = SpawnJSInterop.registerReplacer(replacerObj.name, replacerObj.replacer);
1086
+ if (succ) cnt++;
1087
+ }
1088
+ return cnt;
1089
+ }
1090
+ static registerReplacer(name, replacer) {
1091
+ if (name.indexOf('__replacer') !== 0) throw new Error('Replacer names must start with __replacer');
1092
+ if (SpawnJSInterop[name]) {
1093
+ // already exists. fail quitely as it could just mean another app loaded that uses the same replacers
1094
+ return false;
1095
+ }
1096
+ SpawnJSInterop[name] = replacer;
1097
+ SpawnJSInterop.refreshMethodMap();
1098
+ return true;
1099
+ }
1100
+ // array of { name, reviver }
1101
+ static registerRevivers(revivers) {
1102
+ var cnt = 0;
1103
+ if (!revivers) return cnt;
1104
+ for (var reviverObj of revivers) {
1105
+ var succ = SpawnJSInterop.registerReviver(reviverObj.name, reviverObj.reviver);
1106
+ if (succ) cnt++;
1107
+ }
1108
+ return cnt;
1109
+ }
1110
+ static registerReviver(name, reviver) {
1111
+ if (name.indexOf('__reviver') !== 0) throw new Error('Reviver names must start with __reviver');
1112
+ if (SpawnJSInterop[name]) {
1113
+ // already exists. fail quitely as it could just mean another app loaded that uses the same revivers
1114
+ return false;
1115
+ }
1116
+ SpawnJSInterop[name] = reviver;
1117
+ SpawnJSInterop.refreshMethodMap();
1118
+ return true;
1119
+ }
1120
+ // puts objectToHold (value of ANY type) into spawnJSObjects and returns the id
1121
+ // the object will stay held until released and it must be released to prevent memory leaks
1122
+ static spawnJSObjectHold(objectToHold) {
1123
+ if (objectToHold === globalThis) return -1;
1124
+ if (objectToHold === undefined) return -2;
1125
+ if (objectToHold === null) return -3;
1126
+ if (objectToHold === SpawnJSInterop.spawnJSObjects) return -4;
1127
+ if (objectToHold === SpawnJSInterop) return -5;
1128
+ var sjsId = ++SpawnJSInterop._sjsObjectIdNext;
1129
+ SpawnJSInterop.spawnJSObjects[sjsId] = objectToHold;
1130
+ if (SpawnJSInterop.verbose) console.log('spawnJSObjectHold. Count:', Object.keys(SpawnJSInterop.spawnJSObjects).length, 'Id:', sjsId, 'Object:', objectToHold);
1131
+ return sjsId;
1132
+ }
1133
+ // get an object from the hold
1134
+ static spawnJSObjectGet(sjsId) {
1135
+ switch (sjsId) {
1136
+ case -1: return globalThis;
1137
+ case -2: return undefined;
1138
+ case -3: return null;
1139
+ case -4: return SpawnJSInterop.spawnJSObjects;
1140
+ case -5: return SpawnJSInterop;
1141
+ }
1142
+ if (!SpawnJSInterop.spawnJSObjectHoldExists(sjsId)) {
1143
+ throw new Error('SpawnJSObjectGet object not found.');
1144
+ }
1145
+ var ret = SpawnJSInterop.spawnJSObjects[sjsId];
1146
+ // passive revive (allows things like refreshing heap views)
1147
+ ret = SpawnJSInterop.reviveValue(null, ret, false);
1148
+ return ret;
1149
+ }// get an obejct from the hold and replace it with a new one
1150
+ static spawnJSObjectGetAndReplace(sjsId, newValue) {
1151
+ switch (sjsId) {
1152
+ case -1: return globalThis;
1153
+ case -2: return undefined;
1154
+ case -3: return null;
1155
+ case -4: return SpawnJSInterop.spawnJSObjects;
1156
+ case -5: return SpawnJSInterop;
1157
+ }
1158
+ if (!SpawnJSInterop.spawnJSObjectHoldExists(sjsId)) {
1159
+ throw new Error('SpawnJSObjectGet object not found.');
1160
+ }
1161
+ var ret = SpawnJSInterop.spawnJSObjects[sjsId];
1162
+ SpawnJSInterop.spawnJSObjects[sjsId] = newValue;
1163
+ return ret;
1164
+ }
1165
+ static heapViewRefresh(heapViewInfo) {
1166
+ var needsCreate = !heapViewInfo.buffer;
1167
+ var needsRefresh = !heapViewInfo.buffer || heapViewInfo.buffer.detached;
1168
+ if (needsRefresh) {
1169
+ var instance = SpawnJSInterop.getInstace(heapViewInfo.dotnetId);
1170
+ heapViewInfo.buffer = instance.getHeap();
1171
+ var value = null;
1172
+ var length = heapViewInfo.length === -1 ? /* entire buffer */ heapViewInfo.buffer.byteLength - heapViewInfo.offset : heapViewInfo.length;
1173
+ if (heapViewInfo.viewType === 13) {
1174
+ // ArrayBuffer requested
1175
+ if (heapViewInfo.copy) {
1176
+ // create a copy
1177
+ value = heapViewInfo.buffer.slice(heapViewInfo.offset, heapViewInfo.offset + length);
1178
+ } else {
1179
+ // can't use offet and length when not copying the heap asn ArrayBuffer view
1180
+ if (heapViewInfo.offset != 0) throw new Error('Offset and length not supported creating an ArrayBuffer heap view without a copy');
1181
+ value = heapViewInfo.buffer;
1182
+ }
1183
+ } else if (heapViewInfo.viewType === 14) {
1184
+ // SharedArrayBuffer requested
1185
+ if (heapViewInfo.copy) {
1186
+ // create a copy
1187
+ var uint8ArrayHeap = new Uint8Array(heapViewInfo.buffer, heapViewInfo.offset, length);
1188
+ value = new globalThis.SharedArrayBuffer(length);
1189
+ var uint8ArrayDest = new Uint8Array(value);
1190
+ value.set(uint8ArrayHeap);
1191
+ } else {
1192
+ // can't get a live SharedArrayBuffer view of the heap
1193
+ throw new Error('Cannot get a live SharedArrayBuffer view of the heap');
1194
+ }
1195
+ } else {
1196
+ // ArrayBufferView (TypedArray or DataView)
1197
+ var liveView = new heapViewInfo.ctor(heapViewInfo.buffer, heapViewInfo.offset, length);
1198
+ value = heapViewInfo.copy ? liveView.slice() : liveView;
1199
+ }
1200
+ // copies do not get (or need) their view refreshed as it will not detach
1201
+ if (!heapViewInfo.copy) value._heapViewInfo = heapViewInfo;
1202
+ heapViewInfo.bufferLength = heapViewInfo.buffer.byteLength;
1203
+ heapViewInfo.sizeHistory.push(heapViewInfo.bufferLength);
1204
+ heapViewInfo.value = value;
1205
+ if (SpawnJSInterop.verbose) {
1206
+ if (!needsCreate) console.log('Heapview refreshed:', heapViewInfo);
1207
+ else console.log('Heapview created:', heapViewInfo);
1208
+ }
1209
+ }
1210
+ return heapViewInfo.value;
1211
+ }
1212
+ static getArrayBufferViewConstructor(viewType) {
1213
+ var ctor = SpawnJSInterop.HeapViewCtors[viewType];
1214
+ if (viewType === 13 || viewType === 14) return null; // ArrayBuffer
1215
+ if (!ctor) throw new Error(`Unsupported or missing ArrayBufferView constructor for enum index: ${viewType}`);
1216
+ return ctor;
1217
+ }
1218
+ static __replacerHeapView(key, value, directCall, reviverConfig) {
1219
+ if (directCall) {
1220
+ if (value && typeof value === 'object' && SpawnJSInterop._in('_heapViewInfo', value)) {
1221
+ // .Net wants HeapViewDescriptor
1222
+ //SpawnJSInterop.heapViewRefresh(heapViewInfo);
1223
+ }
1224
+ }
1225
+ return value;
1226
+ }
1227
+ static __reviverHeapView(key, value, directCall, reviverConfig) {
1228
+ if (!directCall && value && typeof value === 'object' && SpawnJSInterop._in('_heapViewInfo', value)) {
1229
+ // auto-reattach if needed
1230
+ // this allows creating a fresh HeapView if needed on `set` and `call` (with the exception of call reattach only working if the view is in teh root args list. no object walking is done)
1231
+ var heapViewInfo = value._heapViewInfo;
1232
+ value = SpawnJSInterop.heapViewRefresh(heapViewInfo);
1233
+ }
1234
+ return value;
1235
+ }
1236
+ // tape revivers (JSTape.WriteRevived) for a Task that completed before it was written
1237
+ static promiseResolved(key, value) { return Promise.resolve(value); }
1238
+ static promiseRejected(key, value) { return Promise.reject(value); }
1239
+ // create a new Promsie with the resolve and reject methods attached to the promise for easy calling from .Net
1240
+ static newEasyPromise() {
1241
+ var _resolve = null;
1242
+ var _reject = null;
1243
+ var promise = new Promise((resolve, reject) => {
1244
+ _resolve = resolve;
1245
+ _reject = reject;
1246
+ });
1247
+ promise.resolve = _resolve;
1248
+ promise.reject = _reject;
1249
+ return promise
1250
+ }
1251
+ // Reviver used by BigIntegerMarshaller: a BigInteger crosses as its decimal string, because a JS
1252
+ // number cannot hold one exactly, and is revived into a real BigInt here.
1253
+ // Revivers are called as (key, value, directCall) by the tape (TagRevive, JSTape.WriteRevived) - a plain
1254
+ // (value) signature would silently revive the PROPERTY NAME instead of the value.
1255
+ static stringToBigInt(key, value) {
1256
+ if (!globalThis.BigInt) throw new Error('BigInt not supported on this platform');
1257
+ return value === undefined || value === null ? null : globalThis.BigInt(value);
1258
+ }
1259
+ // object constructor names
1260
+ // returns string[]
1261
+ static getConstructorNames(obj) {
1262
+ var constructorNames = [];
1263
+ if (obj === void 0 || obj === null) return constructorNames;
1264
+ var o = obj;
1265
+ var cName;
1266
+ while (1) {
1267
+ o = Object.getPrototypeOf(o);
1268
+ cName = o?.constructor?.name;
1269
+ if (!cName) break;
1270
+ if (constructorNames.indexOf(cName) !== -1) continue;
1271
+ constructorNames.push(cName);
1272
+ }
1273
+ return constructorNames;
1274
+ }
1275
+ // returns string[] of the target's property names.
1276
+ // hasOwnProperty true restricts to the object's own enumerable keys (Object.keys); false walks the
1277
+ // prototype chain too, which is what you need to enumerate a DOM object's API rather than just the
1278
+ // handful of own properties it happens to carry.
1279
+ static objectKeys(target, hasOwnProperty) {
1280
+ if (target === void 0 || target === null) return [];
1281
+ if (hasOwnProperty) return Object.keys(target);
1282
+ var keys = [];
1283
+ for (var key in target) {
1284
+ if (keys.indexOf(key) === -1) keys.push(key);
1285
+ }
1286
+ return keys;
1287
+ }
1288
+ // Pipe the value through each reviver sequentially; a reviver that drops the value (undefined) skips the rest.
1289
+ // A plain loop: this runs for every argument of every call, and reduce() allocated a closure each time.
1290
+ static reviveValue(key, value, directCall) {
1291
+ var revivers = SpawnJSInterop._revivers;
1292
+ for (var i = 0; i < revivers.length && value !== undefined; i++) {
1293
+ value = revivers[i](key, value, directCall); // directCall tells the reviver this is a call revive as opposed to a propertySet revive
1294
+ }
1295
+ return value;
1296
+ }
1297
+ static replaceValue(key, value, directCall) {
1298
+ var replacers = SpawnJSInterop._replacers;
1299
+ for (var i = 0; i < replacers.length && value !== undefined; i++) {
1300
+ value = replacers[i](key, value, directCall);
1301
+ }
1302
+ return value;
1303
+ }
1304
+ // returns the types the object inherits from
1305
+ // returns string[]
1306
+ static getPropertyConstructorNames(parent, key) {
1307
+ return SpawnJSInterop.getConstructorNames(parent[key]);
1308
+ }
1309
+ // converts to an error string or returns a generic error string.
1310
+ // A NAMED error (Error subclasses, DOMException - NotFoundError, NotAllowedError, AbortError ... -
1311
+ // and OverconstrainedError, which often has an EMPTY message) is sent as
1312
+ // "\u0001" + name + "\u0002" + message so .Net can rebuild a JSException with its Name
1313
+ // (JSException.FromInteropError). Only the message used to be sent: the name was lost, and an
1314
+ // empty-message OverconstrainedError from getUserMedia arrived as a blank exception.
1315
+ static errorToString(error) {
1316
+ if (!error) return "Unknown error";
1317
+ if (typeof error === 'string') return error;
1318
+ let name = null;
1319
+ let message = null;
1320
+ if (typeof error === 'object') {
1321
+ try { if (typeof error.name === 'string' && error.name) name = error.name; } catch { }
1322
+ try { if (typeof error.message === 'string') message = error.message; } catch { }
1323
+ if (message === null && !(error instanceof Error)) {
1324
+ try { message = JSON.stringify(error); } catch { message = String(error); }
1325
+ }
1326
+ // OverconstrainedError reports the failing constraint separately
1327
+ try { if (typeof error.constraint === 'string' && error.constraint) message = (message ? message + ' ' : '') + '(constraint: ' + error.constraint + ')'; } catch { }
1328
+ }
1329
+ else {
1330
+ message = String(error);
1331
+ }
1332
+ if (!message) message = name ? '' : 'Unknown error';
1333
+ return name ? '\u0001' + name + '\u0002' + message : message;
1334
+ }
1335
+ // Main .Net to JS entrypoint
1336
+ static async _spawnJSInteropLoadExportsAsync(dotnetId, assemblyName) {
1337
+ var dotnet = SpawnJSInterop.spawnJSObjectGet(dotnetId);
1338
+ var assemblyExports = await dotnet.getAssemblyExports(assemblyName);
1339
+ var spawnJSExports = assemblyName.split('.').reduce((acc, key) => acc[key], assemblyExports);
1340
+ dotnet.spawnJSExports = spawnJSExports;
1341
+ }
1342
+ // prepares the variable for .Net based on returnType
1343
+ static _serializeToNet(returnType, ret) {
1344
+ switch (returnType) {
1345
+ case 0: // void
1346
+ return;
1347
+ case 6: // SpawnJSObject - Number
1348
+ case 7: // SpawnJSObjectNonNullable - Number
1349
+ return SpawnJSInterop.spawnJSObjectHold(ret);
1350
+ case 8: // Json
1351
+ return JSON.stringify(ret);
1352
+ case 1: // Double
1353
+ case 2: // Boolean
1354
+ case 3: // DoubleNullable
1355
+ case 4: // BooleanNullable
1356
+ case 9: // Int32
1357
+ case 10: // Int32Nullable
1358
+ return ret;
1359
+ case 5: // String
1360
+ if (ret && typeof ret !== 'string') {
1361
+ ret = Object(ret).toString();
1362
+ }
1363
+ return ret;
1364
+ }
1365
+ // the default is to return as is
1366
+ return ret;
1367
+ }
1368
+ static wasmMemoryBuffer(dotnet) {
1369
+ var found = SpawnJSInterop.#findWasmMemory(dotnet);
1370
+ if (!found) throw new Error('SpawnJSInterop: could not reach the WebAssembly memory buffer');
1371
+ return found.buffer;
1372
+ }
1373
+ // returns the name of the path the memory buffer was found under, or '' if it was not found
1374
+ static wasmMemoryBufferSource(dotnet) {
1375
+ var found = SpawnJSInterop.#findWasmMemory(dotnet);
1376
+ return found ? found.source : '';
1377
+ }
1378
+ static #findWasmMemory(dotnet) {
1379
+ var rt = dotnet;
1380
+ if (!rt) return null;
1381
+ var candidates = [
1382
+ ['Module.HEAPU8.buffer', () => rt.Module?.HEAPU8?.buffer],
1383
+ ['Module.wasmMemory.buffer', () => rt.Module?.wasmMemory?.buffer],
1384
+ ['localHeapViewU8().buffer', () => rt.localHeapViewU8?.()?.buffer],
1385
+ ['getHeapU8().buffer', () => rt.getHeapU8?.()?.buffer],
1386
+ ];
1387
+ for (var i = 0; i < candidates.length; i++) {
1388
+ var buffer;
1389
+ try { buffer = candidates[i][1](); } catch (ex) { continue; }
1390
+ if (buffer && typeof buffer.byteLength === 'number' && buffer.byteLength > 0) {
1391
+ return { buffer: buffer, source: candidates[i][0] };
1392
+ }
1393
+ }
1394
+ return null;
1395
+ }
1396
+ // safely checks for a property existence
1397
+ // safely means will not throw, which is needed as simply checking for a
1398
+ // a proeprty can throw an exception (notably on cross-origin windows)
1399
+ static _in(key, obj) {
1400
+ if (obj === null || obj === void 0) return false;
1401
+ try {
1402
+ return key in Object(obj);
1403
+ } catch { }
1404
+ return false;
1405
+ }
1406
+ // returns the path info based on a base object and a property path: `window?.location.href`
1407
+ static pathObjectInfo(rootObject, path) {
1408
+ if (rootObject === null || rootObject === void 0) {
1409
+ // callers must call with the globalThis if they wish to use it as the rootObject.
1410
+ throw new Error('spawnJSInterop.pathObjectInfo error: rootObject cannot be null');
1411
+ }
1412
+ var parent = rootObject;
1413
+ var target;
1414
+ var propertyName;
1415
+ var shortCircuit = false;
1416
+ if (typeof path === 'string' && !(SpawnJSInterop._in(path, parent))) {
1417
+ var parts = path.split('.');
1418
+ propertyName = parts[parts.length - 1];
1419
+ var part;
1420
+ for (var i = 0; i < parts.length - 1; i++) {
1421
+ part = parts[i];
1422
+ if (part[part.length - 1] === '?') {
1423
+ // ? null conditonal found
1424
+ // if parent does not exist allow undefined/null parent instead of throwing exception
1425
+ part = part.substring(0, part.length - 1);
1426
+ parent = parent[part];
1427
+ if (parent === void 0 || parent === null) {
1428
+ shortCircuit = true;
1429
+ break;
1430
+ }
1431
+ }
1432
+ else {
1433
+ parent = parent[part];
1434
+ }
1435
+ }
1436
+ if (!shortCircuit) {
1437
+ target = parent[propertyName];
1438
+ }
1439
+ }
1440
+ else {
1441
+ propertyName = path;
1442
+ target = parent[propertyName];
1443
+ }
1444
+ return {
1445
+ shortCircuit, // bool - true if the pathfinding short circuited due to a null-conditional
1446
+ parent, // any - only null or undefined if short circuited due to a null-conditional
1447
+ propertyName, // any
1448
+ target, // any
1449
+ };
1450
+ }
1451
+
1452
+ // The URL this app was LOADED from - the origin of its own main.* / _framework, NOT the host
1453
+ // page's document.baseURI. Under a CDN load the page and the app live at different URLs, and every
1454
+ // worker entry (main.classic.js / main.module.js / _framework/*) must resolve against the APP's
1455
+ // origin. document.baseURI is a page-coupled Blazor-ism that hands back the page root instead.
1456
+ //
1457
+ // Derived per-runtime from THIS app's OWN dotnetRuntime, so two SpawnJS apps loaded from different
1458
+ // origins on one page each get their own base - a module-scope import.meta.url could not, because
1459
+ // the class-definition guard means app B's lib.module.js body never re-runs.
1460
+ //
1461
+ // Fail-loud multi-candidate, the same shape as #findWasmMemory: the runtime exposes its origin
1462
+ // under different shapes across scopes/versions, so every known shape is tried and the one that
1463
+ // worked is reportable via appBaseUriSource(). Returns '' if none resolve, so the caller can fall
1464
+ // back rather than silently build worker URLs against a wrong base.
1465
+ static appBaseUri(dotnet) {
1466
+ var found = this.#findAppBaseUri(dotnet);
1467
+ return found ? found.uri : '';
1468
+ }
1469
+ // Which candidate produced appBaseUri(), or '' - diagnostic, mirrors wasmMemoryBufferSource().
1470
+ static appBaseUriSource(dotnet) {
1471
+ var found = this.#findAppBaseUri(dotnet);
1472
+ return found ? found.source : '';
1473
+ }
1474
+ static import(src) {
1475
+ return import(src);
1476
+ }
1477
+ // The app-root normalizer, exposed so it is diagnosable and testable directly. The test suite
1478
+ // drives THIS function rather than a copy of the logic, so the production path is what is covered.
1479
+ static appRootFromLoadUrl(raw) {
1480
+ return this.#appRootFromLoadUrl(raw);
1481
+ }
1482
+ // Normalizes a URL some runtime artifact was loaded from into the app root, with a trailing slash.
1483
+ //
1484
+ // Every boot artifact - the runtime entry (dotnet.js / dotnet.<fingerprint>.js) and every resource
1485
+ // in the boot manifest (.wasm/.dll assemblies, ICU .dat/.blat, .pdb symbols) - lives in the app's
1486
+ // framework folder, so the app root is that folder's PARENT. Anything else was loaded from the app
1487
+ // root itself: a bundled entrypoint (main.classic.js / main.module.js) sits beside index.html, and
1488
+ // that is what SpawnDev.SpawnJS.WebWorkers bundles before 2.1.9 reported here.
1489
+ //
1490
+ // The framework folder is identified by WHAT was loaded, never by what the folder is NAMED. It is
1491
+ // "_framework" in a normal publish, but a published app may rename it - WebWorkers'
1492
+ // SpawnJSWebWorkersFrameworkFolderName does exactly that, because a browser extension may not have
1493
+ // a root folder starting with '_'. Matching the literal name returned the framework folder itself
1494
+ // as the app root there, and every URL built on it (worker entrypoints above all) resolved one
1495
+ // level too deep.
1496
+ static #appRootFromLoadUrl(raw) {
1497
+ if (typeof raw !== 'string' || raw.length === 0) return '';
1498
+ if (raw.startsWith('blob:')) return '';
1499
+ var url;
1500
+ try { url = new URL(raw, self?.location?.href); } catch (ex) { return ''; }
1501
+ var segments = url.pathname.split('/'); // leading '' from the root slash
1502
+ var file = segments.pop(); // '' when the url already names a directory
1503
+ // A boot artifact is one level below the app root, whatever its folder is called. Guarded on
1504
+ // length so an artifact served from the origin root cannot walk above it.
1505
+ if (file && this.#isBootArtifact(file) && segments.length > 1) segments.pop();
1506
+ return url.origin + segments.join('/') + '/';
1507
+ }
1508
+ // True for the runtime entry and for boot-manifest resources - the files that only ever live in
1509
+ // the app's framework folder. Deliberately does NOT match a bundled entrypoint (main.*.js), which
1510
+ // sits at the app root.
1511
+ static #isBootArtifact(fileName) {
1512
+ return /^dotnet(\..+)?\.m?js$/i.test(fileName)
1513
+ || /\.(wasm|dll|dat|blat|pdb)$/i.test(fileName);
1514
+ }
1515
+ static #findAppBaseUri(dotnet) {
1516
+ if (!dotnet) return null;
1517
+ var candidates = [
1518
+ // PROVEN primary (measured across scopes): dotnet.js's own module URL, i.e.
1519
+ // appRoot/_framework/dotnet.<fp>.js - itself import.meta-derived, so it is the real CDN
1520
+ // origin under a CDN load, not the host page. Can be a blob: URL in some worker configs,
1521
+ // which #appRootFromLoadUrl rejects so the resolver falls through to the next candidate.
1522
+ ['Module.mainScriptUrlOrBlob', () => dotnet.Module?.mainScriptUrlOrBlob],
1523
+ // Robust backup: every boot resource carries an absolute resolvedUrl (appRoot/_framework/*),
1524
+ // always populated even when mainScriptUrlOrBlob is a blob.
1525
+ ['getConfig().resources.assembly[0].resolvedUrl', () => dotnet.getConfig?.()?.resources?.assembly?.[0]?.resolvedUrl],
1526
+ ];
1527
+ for (var i = 0; i < candidates.length; i++) {
1528
+ var raw;
1529
+ try { raw = candidates[i][1](); } catch (ex) { continue; }
1530
+ var uri = this.#appRootFromLoadUrl(raw);
1531
+ if (uri) return { uri: uri, source: candidates[i][0] };
1532
+ }
1533
+ return null;
1534
+ }
1535
+ }
1536
+ globalThis.SpawnJSInterop = SpawnJSInterop;
1537
+ })();
_content/SpawnDev.Blazor.BootRecovery/SpawnDev.Blazor.BootRecovery.7rjy3ukk5v.lib.module.js ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // SpawnDev.Blazor.BootRecovery
2
+ //
3
+ // WORKAROUND: dotnet/runtime#135090 (https://github.com/dotnet/runtime/issues/135090). TEMPORARY: remove this package once the
4
+ // .NET runtime retries failed boot resources with cache: "reload" itself.
5
+ //
6
+ // THE BUG: the .NET WebAssembly loader fetches every fingerprinted boot resource (assemblies, dotnet.native.wasm, ICU, pdb) with
7
+ // fetch(url, { cache: "force-cache", integrity }). If the browser's HTTP cache ever stored an error for one of those URLs (a 503 from
8
+ // the host during a deploy or outage, a 404, an empty 200), "force-cache" returns that stored response on every later load, without
9
+ // asking the server again. The integrity check rejects it, the app fails to boot, and it keeps failing after the server is healthy:
10
+ // a hard reload does not help (the explicit cache mode wins over the reload's cache bypass), and Blazor sets
11
+ // enableDownloadRetry: false, so nothing retries. A visitor is stuck until the browser evicts the entry.
12
+ //
13
+ // THE FIX: while this initializer is loaded, a fetch that was sent with cache: "force-cache" and failed (rejected, e.g. the
14
+ // integrity check, or answered with a non-2xx status) is sent ONCE more with cache: "reload". Everything else the runtime chose
15
+ // (integrity, credentials, headers) is kept, so a resource is still verified against its hash. "reload" goes to the network and
16
+ // replaces the bad cache entry, so the next load is a normal cache hit again. A healthy cached start does not change at all: a
17
+ // successful force-cache response is returned untouched. If the retry fails too (the server really is down) its result is
18
+ // returned and the app fails exactly as it would have.
19
+ //
20
+ // HOW IT LOADS: Blazor imports every referenced package's <AssemblyName>.lib.module.js ("JS initializer") from onConfigLoaded,
21
+ // before the runtime starts downloading its boot resources, and the runtime calls globalThis.fetch at call time. So referencing
22
+ // this package is enough: no Program.cs or index.html change. The wrapper is installed when this module is evaluated, and the
23
+ // initializer hooks below only make sure of it.
24
+
25
+ const STATE_KEY = Symbol.for('SpawnDev.Blazor.BootRecovery');
26
+
27
+ function urlOf(input) {
28
+ if (typeof input === 'string') return input;
29
+ if (input && typeof input.url === 'string') return input.url; // Request
30
+ return String(input); // URL or anything with toString()
31
+ }
32
+
33
+ // ⚠️ The installer is a plain, NON-exported function declaration, and nothing in this module calls an exported function by name.
34
+ // SpawnDev.BlazorJS.WebWorkers (when a worker cannot use dynamic import, or the app has an import map, i.e. every .NET 10 template app)
35
+ // rewrites this module's source: `export function X()` becomes `_exportsOverride.X = function X()`, a function EXPRESSION, which
36
+ // leaves no `X` binding in the module scope. 1.0.0 called its exported installBootRecovery() at the top level, so in such a worker the
37
+ // module threw "ReferenceError: installBootRecovery is not defined" and the worker failed to boot (found by Data, 2026-11-22). A
38
+ // plain declaration is not rewritten and stays hoisted, so this works with that patcher and without it.
39
+ function install() {
40
+ const g = globalThis;
41
+ if (g[STATE_KEY]) return g[STATE_KEY];
42
+ const originalFetch = g.fetch;
43
+ if (typeof originalFetch !== 'function') return null;
44
+ const state = { originalFetch, recovered: [] };
45
+
46
+ const recoveringFetch = async function (input, init) {
47
+ // Only requests that explicitly asked for "force-cache" can be pinned to a stored error. Everything else goes straight
48
+ // through, unchanged (same arguments, same this-binding as a plain fetch call).
49
+ if (!init || init.cache !== 'force-cache') return originalFetch.call(g, input, init);
50
+ let reason;
51
+ try {
52
+ const response = await originalFetch.call(g, input, init);
53
+ if (response.ok) return response;
54
+ reason = `HTTP ${response.status}`;
55
+ } catch (e) {
56
+ reason = (e && e.message) || String(e); // integrity mismatch / network failure: TypeError "Failed to fetch"
57
+ }
58
+ const url = urlOf(input);
59
+ // One retry, from the network, keeping every other option (integrity included). Its outcome is final either way.
60
+ const retried = await originalFetch.call(g, input, { ...init, cache: 'reload' });
61
+ state.recovered.push({ url, reason, status: retried.status });
62
+ if (retried.ok)
63
+ console.warn(`[SpawnDev.Blazor.BootRecovery] recovered '${url}' (cached response failed: ${reason}); re-fetched with cache: "reload" (dotnet/runtime#135090).`);
64
+ return retried;
65
+ };
66
+ g.fetch = recoveringFetch;
67
+ g[STATE_KEY] = state;
68
+ return state;
69
+ }
70
+
71
+ /**
72
+ * Installs the recovering fetch wrapper on globalThis once (idempotent, also across copies of this module).
73
+ * @returns {{ originalFetch: Function, recovered: Array<{url: string, reason: string, status: number}> } | null}
74
+ */
75
+ export function installBootRecovery() { return install(); }
76
+
77
+ // Install as soon as Blazor imports this module.
78
+ install();
79
+
80
+ // Blazor initializer hooks. Blazor calls the WebAssembly-specific hook when present, the classic one otherwise; both only ensure
81
+ // the wrapper is installed (for example if something replaced fetch between the import and the start).
82
+ export function beforeWebAssemblyStart() { install(); }
83
+ export function beforeStart() { install(); }
_content/SpawnDev.ILGPU/glWorker.js ADDED
@@ -0,0 +1,1020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ let gl = null;
3
+ let canvas = null;
4
+ const programCache = {};
5
+ // programId -> the compile or link error of a program that failed. The accelerator sends a program's source and
6
+ // varying names with its FIRST dispatch only, so a later dispatch of a failed program must repeat that error.
7
+ const failedPrograms = {};
8
+
9
+ // ---- GPU-resident buffer registry ----
10
+ // Maps bufferId → { texture, width, height, glslType, byteSize, data: Uint8Array }
11
+ const bufferRegistry = {};
12
+
13
+ // ---- float scalar uniform decode ----
14
+ // float/double scalar uniforms arrive as their int32 BIT PATTERN (WebGLAccelerator.EncodeUniformScalarValue):
15
+ // the .NET→JS dispatch message is JSON-marshaled and System.Text.Json rejects float ±inf/NaN, so the bits
16
+ // travel as a JSON-safe int and we reconstruct the exact float here. ±inf/NaN round-trip bit-perfectly.
17
+ const _f32rein = new Float32Array(1);
18
+ const _i32rein = new Int32Array(_f32rein.buffer);
19
+ function _bitsToFloat(bits) { _i32rein[0] = bits | 0; return _f32rein[0]; }
20
+
21
+ // ---- Cached GL objects (reused across dispatches) ----
22
+ let cachedTFBuffer = null;
23
+ let cachedTFBufferSize = 0;
24
+ let cachedTFObject = null;
25
+ let cachedDummyVBO = null;
26
+ let cachedDummyVBOSize = 0;
27
+ let cachedDummyVAO = null;
28
+
29
+ self.onmessage = function (e) {
30
+ const msg = e.data;
31
+ switch (msg.type) {
32
+ case 'init':
33
+ canvas = msg.canvas;
34
+ if (!canvas) {
35
+ console.error('[GLWorker] INIT FAILED: No canvas received');
36
+ return;
37
+ }
38
+ gl = canvas.getContext('webgl2');
39
+ if (!gl) {
40
+ console.error('[GLWorker] INIT FAILED: Could not create WebGL2 context');
41
+ } else {
42
+ // Required to render to R32F/RGBA32F color attachments (GPGPU scatter of float buffers).
43
+ // Integer formats (R32I/R32UI) are color-renderable in core WebGL2 without this.
44
+ gl.getExtension('EXT_color_buffer_float');
45
+ }
46
+ // Monitor context loss/restoration
47
+ canvas.addEventListener('webglcontextlost', function (ev) {
48
+ ev.preventDefault(); // allows potential context restoration
49
+ self.postMessage({ type: 'contextlost' });
50
+ });
51
+ canvas.addEventListener('webglcontextrestored', function () {
52
+ gl = canvas.getContext('webgl2');
53
+ // programs and the cached GL objects belonged to the lost context; the accelerator re-sends sources
54
+ for (const id in programCache) delete programCache[id];
55
+ for (const id in failedPrograms) delete failedPrograms[id];
56
+ for (const t in scatterPrograms) delete scatterPrograms[t];
57
+ scatterFBO = null;
58
+ maxTexSizeCache = 0;
59
+ cachedTFBuffer = null;
60
+ cachedTFBufferSize = 0;
61
+ cachedTFObject = null;
62
+ cachedDummyVBO = null;
63
+ cachedDummyVBOSize = 0;
64
+ cachedDummyVAO = null;
65
+ self.postMessage({ type: 'contextrestored' });
66
+ });
67
+ break;
68
+
69
+ case 'allocBuffer':
70
+ handleAllocBuffer(msg);
71
+ break;
72
+
73
+ case 'uploadBuffer':
74
+ handleUploadBuffer(msg);
75
+ break;
76
+
77
+ case 'readbackBuffer':
78
+ handleReadbackBuffer(msg);
79
+ break;
80
+
81
+ case 'freeBuffer':
82
+ handleFreeBuffer(msg);
83
+ break;
84
+
85
+ case 'copyBuffer':
86
+ handleCopyBuffer(msg);
87
+ break;
88
+
89
+ case 'retypeBuffer':
90
+ handleRetypeBuffer(msg);
91
+ break;
92
+
93
+ case 'dispatch':
94
+ try {
95
+ const result = dispatchKernel(msg);
96
+ self.postMessage(result.message, result.transferList);
97
+ } catch (err) {
98
+ console.error('[GLWorker] dispatch error:', err.message, err.stack);
99
+ self.postMessage({
100
+ done: false, dispatchId: msg.dispatchId,
101
+ error: err.message + '\n' + err.stack
102
+ });
103
+ }
104
+ break;
105
+
106
+ case 'blitBuffer':
107
+ handleBlitBuffer(msg);
108
+ break;
109
+
110
+ case 'scatter':
111
+ try {
112
+ handleScatter(msg);
113
+ } catch (err) {
114
+ console.error('[GLWorker] scatter error:', err.message, err.stack);
115
+ self.postMessage({ done: false, dispatchId: msg.dispatchId, error: err.message + '\n' + err.stack });
116
+ }
117
+ break;
118
+ }
119
+ };
120
+
121
+ // ---- GPGPU scatter (render points to a texture; dst[destIdx[i]] = src[i]) ----
122
+ // WebGL2 transform feedback is gather-only (an invocation writes only its own output slot).
123
+ // Scatter writes to a COMPUTED position by rasterizing one GL_POINT per element at the dest texel
124
+ // and letting the fragment shader write the value to the dst texture (the render target). This stays
125
+ // GPU-side: the result lives in the dst buffer's texture; we mark the CPU mirror stale and read it
126
+ // back lazily only if the host actually reads the buffer (handleReadbackBuffer).
127
+ const scatterPrograms = {}; // glslType -> { program, locs }
128
+ let scatterFBO = null;
129
+
130
+ function getOrCompileScatterProgram(glslType) {
131
+ if (scatterPrograms[glslType]) return scatterPrograms[glslType];
132
+ const isInt = glslType === 'int';
133
+ const isUint = glslType === 'uint';
134
+ const samp = isInt ? 'isampler2D' : isUint ? 'usampler2D' : 'sampler2D';
135
+ const valType = isInt ? 'int' : isUint ? 'uint' : 'float';
136
+ const vs = `#version 300 es
137
+ precision highp float; precision highp int;
138
+ uniform highp ${samp} u_src;
139
+ uniform highp isampler2D u_dest;
140
+ uniform int u_srcTileW; uniform int u_destTileW; uniform int u_dstW; uniform int u_dstH; uniform int u_cpe;
141
+ flat out ${valType} v_val;
142
+ void main() {
143
+ // i is the int-SLOT index (0..n*cpe-1). cpe=1 -> one texel per element (32-bit). cpe=2 -> two
144
+ // texels per element (i64/f64 stored as [lo,hi] pairs): element = i/cpe, component = i%cpe.
145
+ int i = gl_VertexID;
146
+ int sx = i % u_srcTileW; int sy = i / u_srcTileW;
147
+ ${valType} val = texelFetch(u_src, ivec2(sx, sy), 0).r;
148
+ int element = i / u_cpe;
149
+ int comp = i - element * u_cpe;
150
+ int di = element % u_destTileW; int dj = element / u_destTileW;
151
+ int destElem = texelFetch(u_dest, ivec2(di, dj), 0).r;
152
+ int dest = destElem * u_cpe + comp;
153
+ int tx = dest % u_dstW; int ty = dest / u_dstW;
154
+ float ndcx = (float(tx) + 0.5) / float(u_dstW) * 2.0 - 1.0;
155
+ float ndcy = (float(ty) + 0.5) / float(u_dstH) * 2.0 - 1.0;
156
+ gl_Position = vec4(ndcx, ndcy, 0.0, 1.0);
157
+ gl_PointSize = 1.0;
158
+ v_val = val;
159
+ }`;
160
+ const vec4Type = isInt ? 'ivec4' : isUint ? 'uvec4' : 'vec4';
161
+ const zero = isInt ? '0' : isUint ? '0u' : '0.0';
162
+ const fs = `#version 300 es
163
+ precision highp float; precision highp int;
164
+ flat in ${valType} v_val;
165
+ layout(location = 0) out highp ${vec4Type} o_val;
166
+ void main() { o_val = ${vec4Type}(v_val, ${zero}, ${zero}, ${zero}); }`;
167
+
168
+ function compile(type, src) {
169
+ const s = gl.createShader(type);
170
+ gl.shaderSource(s, src); gl.compileShader(s);
171
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS))
172
+ throw new Error('[scatter ' + glslType + '] shader compile: ' + gl.getShaderInfoLog(s) + '\n' + src);
173
+ return s;
174
+ }
175
+ const program = gl.createProgram();
176
+ gl.attachShader(program, compile(gl.VERTEX_SHADER, vs));
177
+ gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fs));
178
+ gl.linkProgram(program);
179
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS))
180
+ throw new Error('[scatter ' + glslType + '] link: ' + gl.getProgramInfoLog(program));
181
+ const locs = {
182
+ u_src: gl.getUniformLocation(program, 'u_src'),
183
+ u_dest: gl.getUniformLocation(program, 'u_dest'),
184
+ u_srcTileW: gl.getUniformLocation(program, 'u_srcTileW'),
185
+ u_destTileW: gl.getUniformLocation(program, 'u_destTileW'),
186
+ u_dstW: gl.getUniformLocation(program, 'u_dstW'),
187
+ u_dstH: gl.getUniformLocation(program, 'u_dstH'),
188
+ u_cpe: gl.getUniformLocation(program, 'u_cpe'),
189
+ };
190
+ const entry = { program, locs };
191
+ scatterPrograms[glslType] = entry;
192
+ return entry;
193
+ }
194
+
195
+ function handleScatter(msg) {
196
+ const { dstBufferId, srcBufferId, destBufferId, n } = msg;
197
+ const cpe = msg.cpe || 1; // texels per element: 1 for 32-bit, 2 for i64/f64
198
+ while (gl.getError() !== 0) { }
199
+ const dst = bufferRegistry[dstBufferId];
200
+ const src = bufferRegistry[srcBufferId];
201
+ const dest = bufferRegistry[destBufferId];
202
+ if (!dst || !src || !dest) throw new Error('scatter: unknown buffer(s)');
203
+
204
+ const glslType = dst.glslType || 'float';
205
+ const sp = getOrCompileScatterProgram(glslType);
206
+ gl.useProgram(sp.program);
207
+
208
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, src.texture); gl.uniform1i(sp.locs.u_src, 0);
209
+ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, dest.texture); gl.uniform1i(sp.locs.u_dest, 1);
210
+ gl.uniform1i(sp.locs.u_srcTileW, src.width);
211
+ gl.uniform1i(sp.locs.u_destTileW, dest.width);
212
+ gl.uniform1i(sp.locs.u_dstW, dst.width);
213
+ gl.uniform1i(sp.locs.u_dstH, dst.height);
214
+ gl.uniform1i(sp.locs.u_cpe, cpe);
215
+
216
+ // Render directly into the dst buffer's texture (the next op reads this — zero-copy).
217
+ if (!scatterFBO) scatterFBO = gl.createFramebuffer();
218
+ gl.bindFramebuffer(gl.FRAMEBUFFER, scatterFBO);
219
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dst.texture, 0);
220
+ const fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
221
+ if (fbStatus !== gl.FRAMEBUFFER_COMPLETE) {
222
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
223
+ throw new Error('scatter: incomplete FBO status=' + fbStatus + ' glslType=' + glslType +
224
+ ' (R32F render targets need EXT_color_buffer_float; R32I/R32UI are core-renderable)');
225
+ }
226
+ gl.drawBuffers([gl.COLOR_ATTACHMENT0]);
227
+ gl.viewport(0, 0, dst.width, dst.height);
228
+ gl.disable(gl.RASTERIZER_DISCARD);
229
+ gl.disable(gl.BLEND); // blending is illegal for integer color buffers
230
+ gl.disable(gl.DEPTH_TEST);
231
+ gl.disable(gl.SCISSOR_TEST);
232
+ gl.disable(gl.CULL_FACE);
233
+ gl.colorMask(true, true, true, true);
234
+ gl.drawArrays(gl.POINTS, 0, n * cpe); // n*cpe int-slots (one point per texel)
235
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
236
+
237
+ // Result lives in dst.texture (zero-copy); refresh the CPU mirror lazily on host readback.
238
+ dst.dataStale = true;
239
+ }
240
+
241
+ // ---- Buffer Registry Operations ----
242
+
243
+ // The widest texture this device takes (gl.MAX_TEXTURE_SIZE), at most 16384. It was a fixed 16384: on a device whose limit is
244
+ // lower every buffer over that many texels got an illegal texture (INVALID_VALUE) and no kernel could read it - Chrome with
245
+ // --disable-gpu (SwiftShader, MAX_TEXTURE_SIZE 8192), SD-Turbo in SpawnGen (Lore, 2026-11-20). Kernels take the width as the
246
+ // u_paramN_tileW uniform, so any width works. Reset on context restore.
247
+ let maxTexSizeCache = 0;
248
+ function maxTextureSize() {
249
+ if (!maxTexSizeCache) {
250
+ const reported = gl ? gl.getParameter(gl.MAX_TEXTURE_SIZE) : 0;
251
+ maxTexSizeCache = Math.min(16384, reported > 0 ? reported : 4096); // 4096: WebGL2's guaranteed minimum is 2048, 4096 is universal
252
+ }
253
+ return maxTexSizeCache;
254
+ }
255
+
256
+ function computeTiling(byteSize) {
257
+ const texelCount = Math.ceil(byteSize / 4);
258
+ const maxTexSize = maxTextureSize();
259
+ let width, height;
260
+ if (texelCount > maxTexSize) {
261
+ width = maxTexSize;
262
+ height = Math.ceil(texelCount / width);
263
+ } else {
264
+ width = texelCount;
265
+ height = 1;
266
+ }
267
+ return { width, height, totalTexels: width * height };
268
+ }
269
+
270
+ function createTextureForEntry(entry) {
271
+ const tex = gl.createTexture();
272
+ gl.bindTexture(gl.TEXTURE_2D, tex);
273
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
274
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
275
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
276
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
277
+ uploadTextureData(tex, entry);
278
+ return tex;
279
+ }
280
+
281
+ // GL error codes by name, for messages a person can act on.
282
+ function glErrorName(e) {
283
+ switch (e) {
284
+ case 0x0500: return 'INVALID_ENUM';
285
+ case 0x0501: return 'INVALID_VALUE';
286
+ case 0x0502: return 'INVALID_OPERATION';
287
+ case 0x0505: return 'OUT_OF_MEMORY';
288
+ case 0x0506: return 'INVALID_FRAMEBUFFER_OPERATION';
289
+ case 0x9242: return 'CONTEXT_LOST_WEBGL';
290
+ default: return '0x' + e.toString(16);
291
+ }
292
+ }
293
+
294
+ // Every pending GL error, as names (empty when there are none). getError returns one flag per call until none is left.
295
+ function drainGlErrors() {
296
+ const names = [];
297
+ for (let e = gl.getError(), guard = 0; e !== 0 && guard < 16; e = gl.getError(), guard++) names.push(glErrorName(e));
298
+ return names;
299
+ }
300
+
301
+ function uploadTextureData(tex, entry) {
302
+ gl.bindTexture(gl.TEXTURE_2D, tex);
303
+ const totalTexels = entry.width * entry.height;
304
+ if (entry.glslType === 'int') {
305
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32I, entry.width, entry.height, 0,
306
+ gl.RED_INTEGER, gl.INT, new Int32Array(entry.data.buffer, 0, totalTexels));
307
+ } else if (entry.glslType === 'uint') {
308
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32UI, entry.width, entry.height, 0,
309
+ gl.RED_INTEGER, gl.UNSIGNED_INT, new Uint32Array(entry.data.buffer, 0, totalTexels));
310
+ } else {
311
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, entry.width, entry.height, 0,
312
+ gl.RED, gl.FLOAT, new Float32Array(entry.data.buffer, 0, totalTexels));
313
+ }
314
+ // A failed upload (OUT_OF_MEMORY when many large textures are alive) leaves the texture without valid contents, and nothing used to
315
+ // say so: the error flag was discarded by the next dispatch's drain and kernels read the texture as if it were the buffer
316
+ // (DeviceVectorIndex after growth, 2026-11-01). Record it on the buffer; a dispatch that binds the buffer throws with it.
317
+ const errs = drainGlErrors();
318
+ entry.glError = errs.length > 0 ? errs.join(', ') + ' uploading its ' + entry.width + 'x' + entry.height + ' ' + (entry.glslType || 'float') + ' texture' +
319
+ (entry.height > maxTextureSize()
320
+ ? ' (taller than the MAX_TEXTURE_SIZE of this device, ' + maxTextureSize() + ': one buffer holds at most ' + (maxTextureSize() * maxTextureSize() * 4) + ' bytes on it)'
321
+ : '') : null;
322
+ }
323
+
324
+ function handleAllocBuffer(msg) {
325
+ const { bufferId, byteSize, glslType } = msg;
326
+ const { width, height, totalTexels } = computeTiling(byteSize);
327
+ const data = new Uint8Array(totalTexels * 4); // zero-filled
328
+ const entry = { texture: null, width, height, glslType: glslType || 'float', byteSize, data };
329
+ entry.texture = createTextureForEntry(entry);
330
+ bufferRegistry[bufferId] = entry;
331
+ }
332
+
333
+ function handleUploadBuffer(msg) {
334
+ const { bufferId, buffer, byteOffset, byteLength, dstByteOffset } = msg;
335
+ const entry = bufferRegistry[bufferId];
336
+ if (!entry) {
337
+ console.error('[GLWorker] uploadBuffer: unknown bufferId', bufferId);
338
+ return;
339
+ }
340
+ const srcData = new Uint8Array(buffer, byteOffset || 0, byteLength || buffer.byteLength);
341
+ if (dstByteOffset !== undefined && dstByteOffset !== null) {
342
+ // PARTIAL host write (MemSet / CopyFromCPU / CopyFromJS on a range) into a buffer that already lives
343
+ // here. Only that range changes: the rest of entry.data is the post-kernel state, which the host's
344
+ // own mirror does not have. A whole-buffer upload of the host mirror is what used to wipe it.
345
+ ensureCpuFresh(entry);
346
+ entry.data.set(srcData, dstByteOffset);
347
+ uploadTextureData(entry.texture, entry);
348
+ entry.dataStale = false;
349
+ return;
350
+ }
351
+ entry.data.set(srcData);
352
+ // Zero-fill padding
353
+ if (srcData.length < entry.data.length) {
354
+ entry.data.fill(0, srcData.length);
355
+ }
356
+ uploadTextureData(entry.texture, entry);
357
+ entry.dataStale = false; // CPU mirror + GPU texture now consistent
358
+ }
359
+
360
+ // Lazily refresh the CPU mirror (entry.data) from the GPU texture when it was last written by a
361
+ // scatter (render-to-texture) and not yet read back. This is the ONLY readPixels — intermediate
362
+ // scatter results stay GPU-side and are never read back.
363
+ // A buffer created before any kernel bound it (by a device copy, a scatter, a memset) got the default 'float' texture; a kernel that
364
+ // then reads it as int / uint binds an isampler2D / usampler2D to an R32F texture, and the draw fails with INVALID_OPERATION, which used
365
+ // to read back as "nothing stored" (DeviceVectorIndex's grown valid buffer, 2026-11-01). Re-create the texture in the type the kernel
366
+ // declares, from the same raw bytes: entry.data holds the 32-bit words whatever the format, so no value changes.
367
+ function handleRetypeBuffer(msg) {
368
+ const entry = bufferRegistry[msg.bufferId];
369
+ if (!entry) { console.error('[GLWorker] retypeBuffer: unknown bufferId', msg.bufferId); return; }
370
+ if (entry.glslType === msg.glslType) return;
371
+ ensureCpuFresh(entry); // a scatter may have left the newest bytes only in the texture
372
+ entry.glslType = msg.glslType;
373
+ uploadTextureData(entry.texture, entry);
374
+ }
375
+
376
+ function ensureCpuFresh(entry) {
377
+ if (!entry || !entry.dataStale) return;
378
+ if (!scatterFBO) scatterFBO = gl.createFramebuffer();
379
+ gl.bindFramebuffer(gl.FRAMEBUFFER, scatterFBO);
380
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, entry.texture, 0);
381
+ const total = entry.width * entry.height;
382
+ let format, type, view;
383
+ if (entry.glslType === 'int') { format = gl.RED_INTEGER; type = gl.INT; view = new Int32Array(entry.data.buffer, 0, total); }
384
+ else if (entry.glslType === 'uint') { format = gl.RED_INTEGER; type = gl.UNSIGNED_INT; view = new Uint32Array(entry.data.buffer, 0, total); }
385
+ else { format = gl.RED; type = gl.FLOAT; view = new Float32Array(entry.data.buffer, 0, total); }
386
+ gl.readPixels(0, 0, entry.width, entry.height, format, type, view);
387
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
388
+ entry.dataStale = false;
389
+ }
390
+
391
+ function handleReadbackBuffer(msg) {
392
+ const { bufferId, requestId } = msg;
393
+ const entry = bufferRegistry[bufferId];
394
+ if (!entry) {
395
+ self.postMessage({ type: 'readbackResult', requestId, bufferId, error: 'unknown bufferId' });
396
+ return;
397
+ }
398
+ ensureCpuFresh(entry); // pull a scattered result back to the CPU mirror only when actually read
399
+ // Create a copy of the data to transfer back
400
+ const copy = new ArrayBuffer(entry.byteSize);
401
+ new Uint8Array(copy).set(new Uint8Array(entry.data.buffer, 0, entry.byteSize));
402
+ self.postMessage({ type: 'readbackResult', requestId, bufferId, buffer: copy }, [copy]);
403
+ }
404
+
405
+ function handleFreeBuffer(msg) {
406
+ const { bufferId } = msg;
407
+ const entry = bufferRegistry[bufferId];
408
+ if (entry) {
409
+ if (entry.texture) gl.deleteTexture(entry.texture);
410
+ delete bufferRegistry[bufferId];
411
+ }
412
+ }
413
+
414
+ // Worker-side GPU->GPU copy. The CPU-side _backingArray is never refreshed
415
+ // after a kernel TF write (only the worker's entry.data is), so routing
416
+ // CopyTo/CopyFrom GPU->GPU through the main thread reads stale zeros from
417
+ // _backingArray and produces a destination of zeros. By doing the copy
418
+ // here (worker's entry.data -> worker's entry.data) the canonical
419
+ // post-kernel state is preserved, then we re-upload the destination
420
+ // texture so subsequent dispatches see the new data.
421
+ function handleCopyBuffer(msg) {
422
+ const { srcBufferId, srcByteOffset, dstBufferId, dstByteOffset, byteLength } = msg;
423
+ const srcEntry = bufferRegistry[srcBufferId];
424
+ const dstEntry = bufferRegistry[dstBufferId];
425
+ if (!srcEntry || !dstEntry) {
426
+ console.error('[GLWorker] copyBuffer: unknown bufferId(s)', srcBufferId, dstBufferId);
427
+ return;
428
+ }
429
+ ensureCpuFresh(srcEntry); // a scattered source must be pulled back before a CPU-side copy
430
+ const srcOff = srcByteOffset | 0;
431
+ const dstOff = dstByteOffset | 0;
432
+ const len = byteLength | 0;
433
+ // Bounds clamp - never overrun either typed array.
434
+ const srcEnd = Math.min(srcOff + len, srcEntry.data.length);
435
+ const copyLen = Math.max(0, srcEnd - srcOff);
436
+ if (copyLen <= 0) return;
437
+ if (dstOff + copyLen > dstEntry.data.length) {
438
+ console.error('[GLWorker] copyBuffer: destination overrun', dstOff, copyLen, dstEntry.data.length);
439
+ return;
440
+ }
441
+ dstEntry.data.set(srcEntry.data.subarray(srcOff, srcOff + copyLen), dstOff);
442
+ // Push the new bytes to the destination texture so subsequent kernel
443
+ // dispatches reading via texelFetch see the updated values.
444
+ uploadTextureData(dstEntry.texture, dstEntry);
445
+ dstEntry.dataStale = false; // CPU mirror + GPU texture now consistent
446
+ }
447
+
448
+ // ---- Shader Compilation ----
449
+
450
+ // source / varyingNames are null after a program's first dispatch: the cached entry (or the cached error) answers.
451
+ function getOrCompileProgram(programId, source, varyingNames) {
452
+ const cached = programCache[programId];
453
+ if (cached && !cached.disposed && (source == null || cached.source === source)) {
454
+ return cached;
455
+ }
456
+ if (source == null) {
457
+ if (programId in failedPrograms) throw new Error(failedPrograms[programId]);
458
+ throw new Error('GL worker: program ' + programId + ' is not compiled and its source was not sent');
459
+ }
460
+ try {
461
+ return compileProgram(programId, source, varyingNames || []);
462
+ } catch (e) {
463
+ failedPrograms[programId] = e.message;
464
+ throw e;
465
+ }
466
+ }
467
+
468
+ function compileProgram(programId, source, varyingNames) {
469
+ const cached = programCache[programId];
470
+ if (cached && !cached.disposed) {
471
+ gl.deleteProgram(cached.program);
472
+ gl.deleteShader(cached.vs);
473
+ gl.deleteShader(cached.fs);
474
+ cached.disposed = true;
475
+ }
476
+
477
+ const vs = gl.createShader(gl.VERTEX_SHADER);
478
+ gl.shaderSource(vs, source);
479
+ gl.compileShader(vs);
480
+ if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
481
+ const log = gl.getShaderInfoLog(vs);
482
+ gl.deleteShader(vs);
483
+ throw new Error('Vertex shader compile error: ' + log);
484
+ }
485
+
486
+ const fsSource = '#version 300 es\nprecision mediump float;\nvoid main() {}\n';
487
+ const fs = gl.createShader(gl.FRAGMENT_SHADER);
488
+ gl.shaderSource(fs, fsSource);
489
+ gl.compileShader(fs);
490
+ if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
491
+ const log = gl.getShaderInfoLog(fs);
492
+ gl.deleteShader(vs);
493
+ gl.deleteShader(fs);
494
+ throw new Error('Fragment shader compile error: ' + log);
495
+ }
496
+
497
+ const program = gl.createProgram();
498
+ gl.attachShader(program, vs);
499
+ gl.attachShader(program, fs);
500
+
501
+ if (varyingNames && varyingNames.length > 0) {
502
+ gl.transformFeedbackVaryings(program, varyingNames, gl.INTERLEAVED_ATTRIBS);
503
+ }
504
+
505
+ gl.linkProgram(program);
506
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
507
+ const log = gl.getProgramInfoLog(program);
508
+ gl.deleteShader(vs);
509
+ gl.deleteShader(fs);
510
+ gl.deleteProgram(program);
511
+ throw new Error('Program link error: ' + log);
512
+ }
513
+
514
+ const entry = { program, vs, fs, uniformCache: {}, disposed: false, source, varyingNames };
515
+ programCache[programId] = entry;
516
+ return entry;
517
+ }
518
+
519
+ function getUniformLoc(cached, name) {
520
+ if (name in cached.uniformCache) return cached.uniformCache[name];
521
+ const loc = gl.getUniformLocation(cached.program, name);
522
+ cached.uniformCache[name] = loc;
523
+ return loc;
524
+ }
525
+
526
+ // ---- Kernel Dispatch ----
527
+
528
+ function dispatchKernel(msg) {
529
+ const { dispatchId, programId, source, varyingNames, totalVertices, dimX, dimY, dimZ, strides, outputs } = msg;
530
+ const kernelParams = msg.params;
531
+
532
+ // Errors left by earlier GL calls: they used to be discarded here without a trace. A failed texture upload is recorded on its buffer
533
+ // (and refuses the dispatch that binds it, below); anything else is reported so it cannot hide.
534
+ const staleErrors = drainGlErrors();
535
+ if (staleErrors.length > 0) console.error('[GLWorker] GL error(s) pending before dispatch ' + dispatchId + ': ' + staleErrors.join(', '));
536
+
537
+ // ---- Step 1: Get or compile program ----
538
+ const cached = getOrCompileProgram(programId, source, varyingNames);
539
+ gl.useProgram(cached.program);
540
+
541
+ // ---- ANGLE f64 workaround: set u_one = 1.0 ----
542
+ const uOneLoc = getUniformLoc(cached, 'u_one');
543
+ if (uOneLoc !== null) gl.uniform1f(uOneLoc, 1.0);
544
+
545
+ // ---- Loop guard: every generated loop runs `_loopN < u_loopLimit` (GLSLCodeGenerator). A uniform so
546
+ // D3D's FXC cannot see a trip count (its loop analysis is superlinear in the body); int max so no
547
+ // real loop is ever cut short. Absent (null) when the shader has no loops.
548
+ const uLoopLimitLoc = getUniformLoc(cached, 'u_loopLimit');
549
+ if (uLoopLimitLoc !== null) gl.uniform1i(uLoopLimitLoc, 2147483647);
550
+
551
+ // ---- Step 2: Dimension uniforms ----
552
+ const dimWLoc = getUniformLoc(cached, 'u_dimWidth');
553
+ if (dimWLoc) gl.uniform1i(dimWLoc, dimX);
554
+ const dimHLoc = getUniformLoc(cached, 'u_dimHeight');
555
+ if (dimHLoc) gl.uniform1i(dimHLoc, dimY);
556
+
557
+ // Grid/group dimension uniforms (for Grid.IdxX/Y, Group.IdxX, Group.DimX)
558
+ const groupDimXLoc = getUniformLoc(cached, 'u_groupDimX');
559
+ if (groupDimXLoc) gl.uniform1i(groupDimXLoc, msg.groupDimX || 1);
560
+ const gridDimXLoc = getUniformLoc(cached, 'u_gridDimX');
561
+ if (gridDimXLoc) gl.uniform1i(gridDimXLoc, msg.gridDimX || 1);
562
+ const gridDimYLoc = getUniformLoc(cached, 'u_gridDimY');
563
+ if (gridDimYLoc) gl.uniform1i(gridDimYLoc, msg.gridDimY || 1);
564
+
565
+ // ---- Step 3: Bind parameters ----
566
+ let textureUnit = 0;
567
+ const bufferParamMap = []; // Track which params map to which bufferIds
568
+
569
+ // Resolve a param index to its uniform-name prefix.
570
+ // Direct param: paramIndex < 1000 -> "u_param{N}".
571
+ // Body-struct synthetic field: paramIndex >= 1000 -> "u_param{realN}_f{fi}"
572
+ // where realN = floor(paramIndex/1000)-1 and fi = paramIndex % 1000. Matches
573
+ // GLSLKernelFunctionGenerator.GetParamBindingName.
574
+ function resolveParamPrefix(paramIndex) {
575
+ if (paramIndex >= 1000) {
576
+ const realN = Math.floor(paramIndex / 1000) - 1;
577
+ const fi = paramIndex % 1000;
578
+ return 'u_param' + realN + '_f' + fi;
579
+ }
580
+ return 'u_param' + paramIndex;
581
+ }
582
+
583
+ for (const p of kernelParams) {
584
+ if (p.kind === 'buffer_ref') {
585
+ // GPU-resident buffer — bind existing texture from registry
586
+ const entry = bufferRegistry[p.bufferId];
587
+ if (!entry) throw new Error('Unknown bufferId: ' + p.bufferId);
588
+ if (entry.glError)
589
+ throw new Error('WebGL: buffer ' + p.bufferId + ' (kernel parameter ' + p.paramIndex + ') has no valid GPU texture (' + entry.glError
590
+ + '), so this kernel cannot read it. Too many large buffers alive at once? Dispose buffers that are no longer needed.');
591
+
592
+ const texUnit = textureUnit++;
593
+ const uniformPrefix = resolveParamPrefix(p.paramIndex);
594
+ const uniformLoc = getUniformLoc(cached, uniformPrefix);
595
+
596
+ if (uniformLoc !== null) {
597
+ gl.activeTexture(gl.TEXTURE0 + texUnit);
598
+ gl.bindTexture(gl.TEXTURE_2D, entry.texture);
599
+ gl.uniform1i(uniformLoc, texUnit);
600
+
601
+ // Tile width uniform
602
+ const tileWLoc = getUniformLoc(cached, uniformPrefix + '_tileW');
603
+ if (tileWLoc) gl.uniform1i(tileWLoc, entry.width);
604
+ }
605
+
606
+ // Element count uniform for GetViewLength support
607
+ if (p.elementCount !== undefined) {
608
+ const lenLoc = getUniformLoc(cached, uniformPrefix + '_length');
609
+ if (lenLoc !== null) gl.uniform1i(lenLoc, p.elementCount | 0);
610
+ }
611
+
612
+ // SubView element offset — added to texelFetch indices when buffer is a SubView.
613
+ // Always set the uniform (including 0) so a prior dispatch's non-zero value
614
+ // doesn't leak across dispatches. WebGL uniforms persist on the program object
615
+ // across draw calls; if the previous dispatch with the same kernel had
616
+ // elementOffset=N (non-zero), the next dispatch with elementOffset=0 would
617
+ // read at offset N. Surfaced 2026-05-04 by Data's StyleMosaic Gather
618
+ // first-divergent-node trace where node 55 Gather output was 0 on WebGL while
619
+ // matching WebGPU exactly through node 54 (which read SubView(0, ...) and
620
+ // set the offset uniform to 0 implicitly via default; subsequent ops that
621
+ // read SubView(non-zero, ...) leaked their offset back into Gather's read).
622
+ const offsetLoc = getUniformLoc(cached, uniformPrefix + '_offset');
623
+ if (offsetLoc !== null) gl.uniform1i(offsetLoc, (p.elementOffset | 0));
624
+
625
+ // Stride uniforms for ArrayView2D/3D
626
+ if (strides && strides[p.paramIndex]) {
627
+ const dims = strides[p.paramIndex];
628
+ const strideLoc = getUniformLoc(cached, uniformPrefix + '_stride[0]');
629
+ if (strideLoc !== null) {
630
+ gl.uniform1iv(strideLoc, new Int32Array(dims));
631
+ }
632
+ }
633
+
634
+ bufferParamMap.push({ bufferId: p.bufferId, paramIndex: p.paramIndex });
635
+
636
+ } else if (p.kind === 'scalar') {
637
+ const uniformName = resolveParamPrefix(p.paramIndex);
638
+ const loc = getUniformLoc(cached, uniformName);
639
+ if (loc !== null) {
640
+ if (p.scalarType === 'int' || p.scalarType === 'bool' || p.scalarType === 'byte'
641
+ || p.scalarType === 'sbyte' || p.scalarType === 'short' || p.scalarType === 'ushort'
642
+ || p.scalarType === 'long') {
643
+ gl.uniform1i(loc, p.value | 0);
644
+ } else if (p.scalarType === 'uint' || p.scalarType === 'ulong') {
645
+ gl.uniform1ui(loc, p.value >>> 0);
646
+ } else if (p.scalarType === 'float' || p.scalarType === 'double') {
647
+ gl.uniform1f(loc, _bitsToFloat(p.value)); // value is the float's int32 bit pattern
648
+ } else {
649
+ console.warn('[GLWorker] Unknown scalar type:', p.scalarType, 'param:', p.paramIndex);
650
+ }
651
+ }
652
+ } else if (p.kind === 'scalar_emu64') {
653
+ const emuPrefix = resolveParamPrefix(p.paramIndex);
654
+ const loLoc = getUniformLoc(cached, emuPrefix + '_lo');
655
+ const hiLoc = getUniformLoc(cached, emuPrefix + '_hi');
656
+ if (loLoc !== null) gl.uniform1ui(loLoc, p.lo >>> 0);
657
+ if (hiLoc !== null) gl.uniform1ui(hiLoc, p.hi >>> 0);
658
+ } else if (p.kind === 'struct') {
659
+ for (const f of p.fields) {
660
+ const fieldLoc = getUniformLoc(cached, 'u_param' + p.paramIndex + '.' + f.path);
661
+ if (fieldLoc !== null) {
662
+ if (f.scalarType === 'int' || f.scalarType === 'bool') {
663
+ gl.uniform1i(fieldLoc, f.value | 0);
664
+ } else if (f.scalarType === 'uint') {
665
+ gl.uniform1ui(fieldLoc, f.value >>> 0);
666
+ } else {
667
+ gl.uniform1f(fieldLoc, _bitsToFloat(f.value)); // float field: int32 bit pattern
668
+ }
669
+ }
670
+ }
671
+ }
672
+ }
673
+
674
+ // ---- Step 4: Transform Feedback setup ----
675
+ let tfBuffer = null;
676
+ let transformFeedback = null;
677
+ // from the program cache: the message carries varying names with the program's first dispatch only
678
+ const vNames = cached.varyingNames || [];
679
+
680
+ if (vNames.length > 0) {
681
+ const tfFloatCount = totalVertices * vNames.length;
682
+ const tfByteSize = tfFloatCount * 4;
683
+
684
+ if (!cachedTFBuffer || cachedTFBufferSize < tfByteSize) {
685
+ if (cachedTFBuffer) gl.deleteBuffer(cachedTFBuffer);
686
+ cachedTFBuffer = gl.createBuffer();
687
+ cachedTFBufferSize = tfByteSize;
688
+ gl.bindBuffer(gl.TRANSFORM_FEEDBACK_BUFFER, cachedTFBuffer);
689
+ gl.bufferData(gl.TRANSFORM_FEEDBACK_BUFFER, tfByteSize, gl.DYNAMIC_READ);
690
+ } else {
691
+ gl.bindBuffer(gl.TRANSFORM_FEEDBACK_BUFFER, cachedTFBuffer);
692
+ }
693
+ tfBuffer = cachedTFBuffer;
694
+
695
+ if (!cachedTFObject) {
696
+ cachedTFObject = gl.createTransformFeedback();
697
+ }
698
+ transformFeedback = cachedTFObject;
699
+ gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, transformFeedback);
700
+ gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, tfBuffer);
701
+ }
702
+
703
+ // ---- Step 5: Dispatch via DrawArrays ----
704
+ if (!cachedDummyVAO) {
705
+ cachedDummyVAO = gl.createVertexArray();
706
+ }
707
+ gl.bindVertexArray(cachedDummyVAO);
708
+
709
+ if (!cachedDummyVBO || cachedDummyVBOSize < totalVertices * 4) {
710
+ if (cachedDummyVBO) gl.deleteBuffer(cachedDummyVBO);
711
+ cachedDummyVBO = gl.createBuffer();
712
+ cachedDummyVBOSize = totalVertices * 4;
713
+ gl.bindBuffer(gl.ARRAY_BUFFER, cachedDummyVBO);
714
+ gl.bufferData(gl.ARRAY_BUFFER, cachedDummyVBOSize, gl.STATIC_DRAW);
715
+ gl.enableVertexAttribArray(0);
716
+ gl.vertexAttribPointer(0, 1, gl.FLOAT, false, 0, 0);
717
+ } else {
718
+ gl.bindBuffer(gl.ARRAY_BUFFER, cachedDummyVBO);
719
+ }
720
+
721
+ gl.enable(gl.RASTERIZER_DISCARD);
722
+ if (transformFeedback) gl.beginTransformFeedback(gl.POINTS);
723
+ gl.drawArrays(gl.POINTS, 0, totalVertices);
724
+ if (transformFeedback) gl.endTransformFeedback();
725
+ gl.disable(gl.RASTERIZER_DISCARD);
726
+ // A draw that FAILED wrote nothing, and its transform feedback buffer reads back as "no store site stored", so every output kept
727
+ // its old value and the dispatch looked successful (DeviceVectorIndex scores: all the fresh buffer's zeros, 2026-11-01).
728
+ const drawErrors = drainGlErrors();
729
+
730
+ // Unbind TF before readback (WebGL2 spec requirement)
731
+ if (transformFeedback) {
732
+ gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, null);
733
+ gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
734
+ }
735
+
736
+ // ---- Step 6: TF Readback → update GPU-resident buffers ----
737
+ // A readback that refuses the dispatch (a store site with two elements, an address out of bounds) must still
738
+ // finish the GL state below: the error used to skip it, the TF buffer stayed bound, and the NEXT dispatch read this
739
+ // dispatch's records (StoreAddress_OffSlotStore after StoreAddress_OneSiteManyElements).
740
+ let readbackError = null;
741
+ if (drawErrors.length > 0) {
742
+ const src = cached.source || '';
743
+ const bound = bufferParamMap.map(function (b) {
744
+ const e = bufferRegistry[b.bufferId];
745
+ const m = src.match(new RegExp('uniform\\s+(?:highp\\s+|mediump\\s+|lowp\\s+)?(\\w*sampler2D)\\s+' + resolveParamPrefix(b.paramIndex) + '\\s*;'));
746
+ return resolveParamPrefix(b.paramIndex) + ': ' + (m ? m[1] : '?') + ' over ' + (e ? (e.glslType || 'float') + ' ' + e.width + 'x' + e.height : 'no buffer');
747
+ });
748
+ readbackError = new Error('WebGL: the kernel draw failed (' + drawErrors.join(', ') + ' over ' + totalVertices + ' vertices); its results were not written. '
749
+ + 'Bound buffers (shader sampler over texture format): ' + bound.join('; '));
750
+ }
751
+ if (!readbackError && tfBuffer && vNames.length > 0 && outputs && outputs.length > 0) {
752
+ // gl.finish() blocks until all submitted GL commands (including TF) complete.
753
+ // Note: ANGLE emits a cosmetic "READ-usage buffer" warning here because it
754
+ // doesn't track gl.finish() as a fence. This warning is harmless — the GPU
755
+ // has completed all writes before we read. Using async fenceSync would
756
+ // eliminate the warning but adds unacceptable scheduling overhead for
757
+ // real-time rendering (~4-50ms per dispatch).
758
+ gl.finish();
759
+
760
+ gl.bindBuffer(gl.TRANSFORM_FEEDBACK_BUFFER, tfBuffer);
761
+ const tfElemCount = totalVertices * vNames.length;
762
+ // Read as raw bytes via Uint8Array — passing Float32Array as the destination
763
+ // makes Chrome canonicalize specific bit patterns through the float view
764
+ // (observed 2026-05-04: writing 0x80000000u via TF reads back as 0x80000001
765
+ // when getBufferSubData destination is Float32Array; Uint8Array preserves
766
+ // the bit pattern exactly). Tests23_BareUintShift / NormalizeShape_BareCondition
767
+ // surfaced this — see _DevComms/SpawnDev.ILGPU.
768
+ const readbackBytes = new Uint8Array(tfElemCount * 4);
769
+ gl.getBufferSubData(gl.TRANSFORM_FEEDBACK_BUFFER, 0, readbackBytes);
770
+ const readbackFloat = new Float32Array(readbackBytes.buffer);
771
+ const varyingCount = vNames.length;
772
+ const strideBytes = varyingCount * 4;
773
+
774
+ // Set of bufferIds that were modified (need texture re-upload)
775
+ const modifiedBufferIds = new Set();
776
+
777
+ // The element vertex v's store of output `out` targets, or -1 when that store site did not store in v. A store
778
+ // site's value lands at its group base + siteConst (GLSLKernelFunctionGenerator.EmitStoreAddressVaryings); a
779
+ // varying without a base (baseIndex < 0) is the vertex's own element (slot within a positional record).
780
+ // Plans/webgl-store-addresses-2026-10-26.md: before this every value landed at the vertex's own element.
781
+ const int32All = new Int32Array(readbackBytes.buffer);
782
+ const strideWords = varyingCount;
783
+ // Elements a dispatch does not store keep the values in the CPU mirror, which is then re-uploaded whole: a
784
+ // mirror a scatter left stale must be read back first, or that upload would revert the scatter's results.
785
+ for (let oi = 0; oi < outputs.length; oi++) {
786
+ if (!outputs[oi].isAtomicVote) ensureCpuFresh(bufferRegistry[outputs[oi].bufferId]);
787
+ }
788
+ function storeElement(out, v, elemCount) {
789
+ if (out.baseIndex < 0) {
790
+ const own = v * (out.storeCount || 1) + (out.storeSlot >= 0 ? out.storeSlot : 0);
791
+ return own < elemCount ? own : -1;
792
+ }
793
+ if ((int32All[v * strideWords + out.maskIndex] & out.maskBit) === 0) return -1;
794
+ const base = int32All[v * strideWords + out.baseIndex];
795
+ if (base === -2)
796
+ throw new Error('WebGL: a store site of output ' + out.varyingName + ' wrote two different elements in one thread (vertex ' + v +
797
+ '). Transform feedback captures one element per store site per thread; a kernel that scatters several elements from one store needs WebGPU/Wasm/desktop (AcceleratorRequirements.RequiresScatterStores).');
798
+ const e = base + out.siteConst;
799
+ if (e < 0 || e >= elemCount)
800
+ throw new Error('WebGL: output ' + out.varyingName + ' stored element ' + e + ' outside its view of ' + elemCount + ' elements (vertex ' + v + ')');
801
+ return e;
802
+ }
803
+
804
+ try {
805
+ for (let oi = 0; oi < outputs.length; oi++) {
806
+ const out = outputs[oi];
807
+
808
+ // Atomic vote: each thread emitted its increment amount; sum all and add to buffer[element].
809
+ // This emulates Atomic.Add without true GPU atomics (WebGL2 vertex shader limitation).
810
+ if (out.isAtomicVote) {
811
+ const entry = bufferRegistry[out.bufferId];
812
+ if (!entry) continue;
813
+ const destView = entry.data;
814
+ const writeOffset = out.writeByteOffset;
815
+ // Sum all per-vertex vote values (stored as int in the TF buffer)
816
+ const int32TF = new Int32Array(readbackFloat.buffer);
817
+ let sum = 0;
818
+ for (let v = 0; v < totalVertices; v++) {
819
+ sum += int32TF[(v * strideBytes + out.outputIndex * 4) >> 2];
820
+ }
821
+ // Accumulate (not replace) the target buffer element using Int32 arithmetic
822
+ const destInt32 = new Int32Array(destView.buffer);
823
+ const destIdx = writeOffset >> 2;
824
+ destInt32[destIdx] = destInt32[destIdx] + sum;
825
+ modifiedBufferIds.add(out.bufferId);
826
+ continue;
827
+ }
828
+
829
+ // Skip 'hi' emulated varyings (read with their 'lo' counterpart)
830
+ if (out.isEmulated && out.emulatedSuffix === 'hi') continue;
831
+
832
+ // Find the registry entry for this output
833
+ const entry = bufferRegistry[out.bufferId];
834
+ if (!entry) continue;
835
+ const destView = entry.data;
836
+ const writeOffset = out.writeByteOffset;
837
+
838
+ if (out.fieldIndex >= 0) {
839
+ // Struct field output - either a plain scalar field, or the 'lo' half of a
840
+ // 64-bit emulated field ('hi' halves were already skipped above). Checked
841
+ // BEFORE the plain isEmulated/'lo' branch below because a struct field's
842
+ // lo varying also has isEmulated=true, but must NOT go through the flat
843
+ // (non-struct) 8-bytes-per-vertex reconstruction - it's one field of a
844
+ // larger per-vertex struct record, at its own byte offset within it.
845
+ //
846
+ // Run the whole-struct reconstruction exactly once, triggered by the first
847
+ // (lowest outputIndex) struct-field varying for this param.
848
+ const structVaryings = outputs.filter(o => o.paramIndex === out.paramIndex && o.fieldIndex >= 0);
849
+ if (structVaryings[0].outputIndex !== out.outputIndex) continue;
850
+
851
+ // One representative varying per logical field (its 'lo' half for an
852
+ // emulated 64-bit field, the field itself otherwise), in field order. Each
853
+ // carries the field's REAL byte offset and size inside the element and the
854
+ // element size, from ILGPU's struct layout (GLSLKernelFunctionGenerator
855
+ // StructLeaf) - alignment padding included, so { int; long; } puts the long at
856
+ // byte 8. Only the field's own bytes are written: a sub-4-byte field copies the
857
+ // low bytes of its 32-bit varying and never touches its neighbours.
858
+ const maxFieldIndex = Math.max(...structVaryings.map(o => o.fieldIndex));
859
+ const fieldsInOrder = [];
860
+ for (let f = 0; f <= maxFieldIndex; f++) {
861
+ const forField = structVaryings.filter(o => o.fieldIndex === f);
862
+ fieldsInOrder.push(forField.find(o => o.emulatedSuffix === 'lo') || forField[0]);
863
+ }
864
+ const fieldByteWidths = fieldsInOrder.map(o => o.fieldByteSize);
865
+ const structElemSize = fieldsInOrder[0].structByteSize;
866
+ const fieldByteOffsets = fieldsInOrder.map(o => o.fieldByteOffset);
867
+
868
+ const viewElems = Math.floor(out.writeLengthBytes / structElemSize);
869
+ for (let v = 0; v < totalVertices; v++) {
870
+ const e = storeElement(fieldsInOrder[0], v, viewElems);
871
+ if (e < 0) continue;
872
+ for (let fi = 0; fi < fieldsInOrder.length; fi++) {
873
+ const fieldOut = fieldsInOrder[fi];
874
+ const dstOff = writeOffset + e * structElemSize + fieldByteOffsets[fi];
875
+ const srcOff = v * strideBytes + fieldOut.outputIndex * 4;
876
+ if (srcOff + 4 > readbackBytes.length) continue;
877
+ const loBytes = Math.min(fieldByteWidths[fi], 4);
878
+ for (let b = 0; b < loBytes; b++) destView[dstOff + b] = readbackBytes[srcOff + b];
879
+ if (fieldByteWidths[fi] === 8) {
880
+ const hiSrc = v * strideBytes + (fieldOut.outputIndex + 1) * 4;
881
+ destView[dstOff + 4] = readbackBytes[hiSrc];
882
+ destView[dstOff + 5] = readbackBytes[hiSrc + 1];
883
+ destView[dstOff + 6] = readbackBytes[hiSrc + 2];
884
+ destView[dstOff + 7] = readbackBytes[hiSrc + 3];
885
+ }
886
+ }
887
+ }
888
+ } else if (out.isEmulated && out.emulatedSuffix === 'lo') {
889
+ // A thread that stores MULTIPLE emulated-64-bit elements into this buffer
890
+ // (positional multi-store, e.g. digest[base+0..3] = o0..o3, each 8 bytes) gets
891
+ // one lo/hi varying PAIR per slot (EmitOutputVaryings' emuStoreCount branch) -
892
+ // place each slot at its own offset within the per-vertex record instead of
893
+ // always writeOffset + v*8 (which only ever wrote slot 0's storage location,
894
+ // repeatedly, for every slot - the actual root cause of the "Compress ref
895
+ // write-back" symptom: every store after the first silently overwrote the same
896
+ // 8 bytes, so only the LAST store's value ever reached the host, discovered and
897
+ // fixed 2026-09-22 with a minimal repro that reproduced it standalone, no ref
898
+ // params or fn-def calls needed at all).
899
+ const hiOutIdx = out.outputIndex + 1;
900
+ const viewElems = Math.floor(out.writeLengthBytes / 8);
901
+ for (let v = 0; v < totalVertices; v++) {
902
+ const e = storeElement(out, v, viewElems);
903
+ if (e < 0) continue;
904
+ const loSrc = v * strideBytes + out.outputIndex * 4;
905
+ const hiSrc = v * strideBytes + hiOutIdx * 4;
906
+ const dst = writeOffset + e * 8;
907
+ destView[dst] = readbackBytes[loSrc];
908
+ destView[dst + 1] = readbackBytes[loSrc + 1];
909
+ destView[dst + 2] = readbackBytes[loSrc + 2];
910
+ destView[dst + 3] = readbackBytes[loSrc + 3];
911
+ destView[dst + 4] = readbackBytes[hiSrc];
912
+ destView[dst + 5] = readbackBytes[hiSrc + 1];
913
+ destView[dst + 6] = readbackBytes[hiSrc + 2];
914
+ destView[dst + 7] = readbackBytes[hiSrc + 3];
915
+ }
916
+ } else if (out.fieldIndex < 0) {
917
+
918
+ // Sub-word packing: TF outputs one i32 per element, but the destination
919
+ // buffer stores packed sub-word values (e.g. 2 shorts per i32).
920
+ // Pack by reading each TF i32 and writing only the sub-word portion.
921
+ if (out.subWordElementSize && out.subWordElementSize < 4) {
922
+ const swSize = out.subWordElementSize;
923
+ const viewElems = Math.floor(out.writeLengthBytes / swSize);
924
+ for (let v = 0; v < totalVertices; v++) {
925
+ const e = storeElement(out, v, viewElems);
926
+ if (e < 0) continue;
927
+ const srcIdx = (v * strideBytes + out.outputIndex * 4) >> 2;
928
+ const val = int32All[srcIdx];
929
+ const dstOff = writeOffset + e * swSize;
930
+ if (swSize === 2) {
931
+ // Pack as 16-bit (little-endian)
932
+ destView[dstOff] = val & 0xFF;
933
+ destView[dstOff + 1] = (val >> 8) & 0xFF;
934
+ } else if (swSize === 1) {
935
+ destView[dstOff] = val & 0xFF;
936
+ }
937
+ }
938
+ } else if (out.baseIndex < 0 && (out.storeCount || 1) === 1 && ((destView.byteOffset + writeOffset) & 3) === 0) {
939
+ // Vertex v's value is element v (an own-element output, GLSLKernelFunctionGenerator
940
+ // _ownElementOutputs): one typed copy instead of a per-element call and four byte copies,
941
+ // which cost as much as the readback itself (WebGL 1.4M radix sort: 5.7 s of 800 dispatches).
942
+ const n = Math.min(totalVertices, Math.floor(out.writeLengthBytes / 4));
943
+ const dst32 = new Int32Array(destView.buffer, destView.byteOffset + writeOffset, n);
944
+ if (strideWords === 1) dst32.set(int32All.subarray(0, n));
945
+ else {
946
+ const o = out.outputIndex;
947
+ for (let v = 0; v < n; v++) dst32[v] = int32All[v * strideWords + o];
948
+ }
949
+ } else {
950
+ const viewElems = Math.floor(out.writeLengthBytes / 4);
951
+ for (let v = 0; v < totalVertices; v++) {
952
+ const e = storeElement(out, v, viewElems);
953
+ if (e < 0) continue;
954
+ const srcOff = v * strideBytes + out.outputIndex * 4;
955
+ const dstOff = writeOffset + e * 4;
956
+ if (srcOff + 4 <= readbackBytes.length) {
957
+ destView[dstOff] = readbackBytes[srcOff];
958
+ destView[dstOff + 1] = readbackBytes[srcOff + 1];
959
+ destView[dstOff + 2] = readbackBytes[srcOff + 2];
960
+ destView[dstOff + 3] = readbackBytes[srcOff + 3];
961
+ }
962
+ }
963
+ }
964
+ }
965
+
966
+ modifiedBufferIds.add(out.bufferId);
967
+ }
968
+
969
+ } catch (err) {
970
+ readbackError = err;
971
+ }
972
+ gl.bindBuffer(gl.TRANSFORM_FEEDBACK_BUFFER, null);
973
+
974
+ // Re-upload modified buffers to their GPU textures (GPU-resident update; also after a refused readback, so
975
+ // the CPU mirror and the texture agree)
976
+ for (const bid of modifiedBufferIds) {
977
+ const entry = bufferRegistry[bid];
978
+ if (entry) {
979
+ uploadTextureData(entry.texture, entry);
980
+ }
981
+ }
982
+
983
+ }
984
+
985
+ gl.useProgram(null);
986
+ // A context lost DURING the dispatch (driver reset, GPU hang) reads back an all-zero transform feedback buffer: no
987
+ // store-site bit set, so every element kept its old value and the dispatch looked successful (SpawnDev.Codecs
988
+ // VorbisResidueAccumulateGpu_Type2: target came back untouched, nothing refused). The webglcontextlost event comes
989
+ // later, asynchronously; isContextLost() is the synchronous answer.
990
+ if (!readbackError && gl.isContextLost())
991
+ readbackError = new Error('WebGL: the context was lost during this dispatch (GPU reset or driver crash); its results were not written.');
992
+ if (readbackError) throw readbackError;
993
+
994
+ // No ArrayBuffer transfers — data stays GPU-resident in the worker
995
+ return {
996
+ message: { done: true, dispatchId },
997
+ transferList: []
998
+ };
999
+ }
1000
+
1001
+ // ---- ImageBitmap blit ----
1002
+ // Creates an ImageBitmap from an RGBA pixel buffer and transfers it to the main thread.
1003
+ // The browser compositor manages the bitmap as a GPU texture — no pixel copy on transfer.
1004
+ function handleBlitBuffer(msg) {
1005
+ const { bufferId, width, height, requestId } = msg;
1006
+ const entry = bufferRegistry[bufferId];
1007
+ if (!entry) {
1008
+ self.postMessage({ type: 'blitResult', requestId, error: 'unknown bufferId' });
1009
+ return;
1010
+ }
1011
+ // entry.data is always current after dispatch (TF readback keeps it in sync).
1012
+ // Wrap as Uint8ClampedArray for ImageData — no copy, just a typed view.
1013
+ const rgba = new Uint8ClampedArray(entry.data.buffer, 0, width * height * 4);
1014
+ const imageData = new ImageData(rgba, width, height);
1015
+ createImageBitmap(imageData).then(function(bitmap) {
1016
+ self.postMessage({ type: 'blitResult', requestId, bitmap }, [bitmap]);
1017
+ }).catch(function(err) {
1018
+ self.postMessage({ type: 'blitResult', requestId, error: err.message });
1019
+ });
1020
+ }
_content/SpawnDev.ILGPU/webgpuDispatchPlan.js ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ // SpawnDev.ILGPU WebGPU dispatch-plan replay helper (loaded on demand via dynamic import of
3
+ // _content/SpawnDev.ILGPU/webgpuDispatchPlan.js - the glWorker.js static-asset pattern).
4
+ //
5
+ // A dispatch plan is a flat JS array of 7-element tagged records:
6
+ // [0, pipeline, bindGroup, x, y, z, submitAfter] - compute dispatch (submitAfter 1 = end the
7
+ // command buffer right after it: the NVIDIA
8
+ // large-function-array WORKAROUND,
9
+ // https://github.com/LostBeard/SpawnDev.ILGPU/issues/10)
10
+ // [1, srcBuffer, srcOffset, dstBuffer, dstOffset, size, 0] - copyBufferToBuffer
11
+ // [2, buffer, offset, size, 0, 0, 0] - clearBuffer (zero-fill)
12
+ // It is recorded ONCE by WebGPUDispatchPlan during a capture forward (the plan array holding the
13
+ // GPU objects is what keeps them alive - .NET-side wrapper disposal is irrelevant), then replayed
14
+ // here with a SINGLE .NET->JS interop crossing per forward: this loop re-encodes every operation
15
+ // into one command encoder in pure JS (microseconds per entry) and submits one command buffer.
16
+ // This is the browser twin of CUDA graph replay - WebGPU has no graph API, but the command encoder
17
+ // IS the graph recorder, and WebGPU guarantees ordering with implicit synchronization between
18
+ // passes/copies on the same queue.
19
+ (() => {
20
+ // Bind-group cache generation size (per device). Two generations: a lookup that misses the current one but hits the
21
+ // previous one promotes the group; when the current generation passes this size it becomes the previous one and the
22
+ // old previous one is dropped. So a group used at least once per generation is never dropped, while groups of a
23
+ // shape no longer in use age out. MEASURED 2026-10-02 (Anaglyphohol DAv3 video): one input shape is ~2.8k distinct
24
+ // groups, but the adaptive depth level cycles through many shapes (55k groups in all) - a single map cleared at a
25
+ // cap kept dropping the hot shape (20% hits); with generations the hot shapes stay.
26
+ const BG_GEN_MAX = 8192;
27
+ const api = {
28
+ // JS-side timing of the most recent replay() call on this page: encodeMs = the re-encode
29
+ // loop (createCommandEncoder .. last op), submitMs = enc.finish() + queue.submit(). GPU
30
+ // EXECUTION is not included - it completes asynchronously after submit (await
31
+ // onSubmittedWorkDone / SynchronizeAsync for that). Reading performance.now() is ~free,
32
+ // so this records unconditionally; .NET fetches it on demand only.
33
+ last: { ops: 0, encodeMs: 0, submitMs: 0 },
34
+ // Per-device staging buffer for submitBatch's ordered host uploads (tag 4). Grows, never shrinks.
35
+ _staging: new WeakMap(),
36
+ // Per-device bind-group cache for submitBatch (api.bindGroupReuse): key = layout id + every entry's
37
+ // (binding, buffer id, offset, size) -> GPUBindGroup, in two generations of up to BG_GEN_MAX (see there), so a
38
+ // workload whose buffers churn costs a bounded amount of memory. bgHits/bgMisses are cumulative counters.
39
+ _bindGroups: new WeakMap(),
40
+ bgHits: 0,
41
+ bgMisses: 0,
42
+ bgDrops: 0, // generations started (first use per device, then one per rotation)
43
+ bgLastKey: '', // the most recent miss's key (diagnostic)
44
+ // ── Interop cost probes ─────────────────────────────────────────────────────────────────
45
+ // These do NOTHING on purpose. device.createBindGroup measured 1.14 ms per call in a Kokoro
46
+ // pass (2,117 ms of 2,128 ms of the whole bind-group phase), and "1.14 ms" has three possible
47
+ // owners with three different fixes: the .NET->JS crossing itself, MARSHALLING the descriptor
48
+ // (its members are walked and rebuilt as a JS object per call - a layout reference, an entries
49
+ // array, and a nested resource object per entry - so the cost scales with members), or Dawn's
50
+ // own validation. A no-op crossing brackets the first; a no-op crossing that still marshals the
51
+ // descriptor brackets the first two; whatever the real call costs beyond that is Dawn's.
52
+ // noopDescriptor touches .entries.length so the marshalled object cannot be optimised away.
53
+ noop(x) { return x | 0; },
54
+ // WebGPUBackend.BatchSinglePass -> submitBatch (see there). Set from C# when the switch changes.
55
+ setSinglePass(v) { api.singlePass = !!v; return 0; },
56
+ // WebGPUBackend.BatchBindGroupReuse -> submitBatch's bind-group cache. Turning it off drops every cached group.
57
+ setBindGroupReuse(v) { api.bindGroupReuse = !!v; if (!api.bindGroupReuse) api._bindGroups = new WeakMap(); return 0; },
58
+ // DIAGNOSTIC ABLATION (WebGPUBackend.DiagSubmitAblation; results are garbage while set): 2 = skip createBindGroup
59
+ // + the dispatch encode, 3 = return without doing anything. (A "skip only the scalar writes" mode ran every
60
+ // kernel on stale loop bounds and HUNG the GPU - DXGI_ERROR_DEVICE_HUNG; 2 vs 3 measures the writes safely.)
61
+ setAblation(v) { api.ablation = v | 0; return 0; },
62
+ noopDescriptor(desc) { return desc && desc.entries ? desc.entries.length : 0; },
63
+
64
+ // The SpawnJS instance whose wasm heap submitHeader reads (C# passes SpawnJSRuntime.DotnetInstance.Id once).
65
+ // getHeap() returns the CURRENT heap buffer - it re-fetches it after memory growth detached the old one.
66
+ setHeapSource(dotnetId) { api._heapInst = globalThis.SpawnJSInterop.getInstace(dotnetId); return 0; },
67
+ // The batch submit's entry from WebGPUStream.SubmitBatch: ONE number crosses - the heap address of a pinned
68
+ // Float64 header - and everything else is read from the wasm heap here:
69
+ // [0] device id [1] records addr [2] record count [3] data addr [4] data byte length
70
+ // [5] maxPassesPerSubmit [6] upload bytes [7..10] arenaR id, bytes, arenaW id, bytes
71
+ // [11] single pass (0/1) [12] ablation [13] bind-group reuse (0/1)
72
+ // The records and data arrays are pinned C# arrays (never moved), so views over the heap at their
73
+ // addresses ARE the arrays - nothing is copied and no HeapView object is created per submit.
74
+ submitHeader(hdrAddr) {
75
+ const heap = api._heapInst.getHeap();
76
+ const h = new Float64Array(heap, hdrAddr, 14);
77
+ api.singlePass = h[11] !== 0;
78
+ api.ablation = h[12] | 0;
79
+ const reuse = h[13] !== 0;
80
+ if (reuse !== (api.bindGroupReuse !== false)) api.setBindGroupReuse(reuse);
81
+ const device = globalThis.SpawnJSInterop.spawnJSObjects[h[0]];
82
+ if (!device) throw new Error(`ilgpuWebGPUPlan.submitHeader: device (SpawnJS id ${h[0]}) is not held`);
83
+ const n = h[2];
84
+ const rec = new Float64Array(heap, h[1], n);
85
+ const data = new Uint8Array(heap, h[3], h[4]);
86
+ return api.submitBatch(device, rec, n, data, h[5], h[6], h[7], h[8], h[9], h[10]);
87
+ },
88
+
89
+ // Rewrite the dstOffset (slot [i*7+4]) of copy entries in place - the patch surface for
90
+ // parameterized replay (e.g. a KV-cache append whose destination row advances per decode
91
+ // token). Entries must be tag-1 copies; throws otherwise (a wrong index would silently
92
+ // corrupt a dispatch record).
93
+ patchCopyDst(plan, entryIndices, newDstOffsets) {
94
+ for (let k = 0; k < entryIndices.length; k++) {
95
+ const i = entryIndices[k] * 7;
96
+ if (plan[i] !== 1) throw new Error(`patchCopyDst: entry ${entryIndices[k]} is tag ${plan[i]}, not a copy`);
97
+ plan[i + 4] = newDstOffsets[k];
98
+ }
99
+ },
100
+ // Submits the accelerator's PLAIN (uncaptured) dispatch batch: WebGPUStream appends numeric
101
+ // records while kernels are dispatched and hands the whole batch over in ONE crossing here, where
102
+ // the bind groups are created and every op is encoded. Every GPU object is named by its SpawnJS
103
+ // hold id and resolved from SpawnJSInterop.spawnJSObjects, so no descriptor is ever marshalled -
104
+ // SpawnJS builds a nested .NET object one property Set per member, ~40 crossings for a bind-group
105
+ // descriptor, which is what made createBindGroup the largest host cost of a graph forward.
106
+ // Records (Float64Array `rec`, first `n` values):
107
+ // [0, pipelineId, layoutId, nEntries, x, y, z, (binding, bufferId, offset, size) * nEntries]
108
+ // [1, srcId, srcOffset, dstId, dstOffset, size] copyBufferToBuffer
109
+ // [2, bufferId, offset, size] clearBuffer
110
+ // [3, bufferId, bufferOffset, dataOffset, size] queue.writeBuffer from `data` (Uint8Array)
111
+ // [4, bufferId, bufferOffset, dataOffset, size] ORDERED host upload: copyBufferToBuffer from the
112
+ // staging copy of `data`, encoded in record order
113
+ // A tag-3 write is issued when it is reached, so it precedes the submit of the command buffer holding
114
+ // the dispatch that reads it - the same order as the per-dispatch path (write now, submit later). It
115
+ // is only for buffers the batch alone uses (per-dispatch scalar/stride/lock buffers).
116
+ // A tag-4 upload targets an ordinary buffer that earlier records in the batch may still read, so it
117
+ // must land exactly where it sits in the batch: `data` is written ONCE into a persistent staging
118
+ // buffer and each upload is a copyBufferToBuffer in record order. Reusing the staging buffer across
119
+ // batches is safe because queue.writeBuffer executes after all previously submitted work.
120
+ // Command buffers are split every maxPassesPerSubmit dispatches (see replay() for why).
121
+ // SCALAR ARENAS (WebGPUBackend.BatchScalarArena): the batch's per-dispatch scalars are 256-byte slots of two
122
+ // arena buffers (arenaRId: read-only bindings, arenaWId: read_write struct scalars; 0 = unused). Their used
123
+ // prefixes are the LAST arenaRBytes + arenaWBytes bytes of `data` and are written FIRST, before any command
124
+ // buffer of this batch is submitted - every slot is used once per batch, so one write per arena is exact.
125
+ // BIND-GROUP REUSE (api.bindGroupReuse): a bind group is immutable and SpawnJS hold ids are never reused, so
126
+ // two dispatch records with equal layout + entries can share one; with the arenas the keys repeat every frame.
127
+ // ONE COMPUTE PASS FOR A RUN OF DISPATCHES (api.singlePass, set from WebGPUBackend.BatchSinglePass - default
128
+ // true): consecutive dispatch records share an open pass; it is ended before an encoder-level command (copy,
129
+ // clear, upload) and at every submit, and setPipeline is skipped when the pipeline repeats. Ordering is the
130
+ // spec's, not ours: every dispatch in a compute pass is its OWN usage scope, so a storage write by one dispatch
131
+ // is visible to the next exactly as across passes - the implementation inserts the barrier. What a pass per
132
+ // dispatch added was a beginComputePass/end pair (and a fresh pass state) for each of ~800 dispatches a frame.
133
+ // Returns the number of records processed.
134
+ submitBatch(device, rec, n, data, maxPassesPerSubmit, uploadBytes, arenaRId, arenaRBytes, arenaWId, arenaWBytes) {
135
+ const ablation = api.ablation | 0;
136
+ if (ablation === 3) return 0;
137
+ const objs = globalThis.SpawnJSInterop.spawnJSObjects;
138
+ const obj = (id, what, at) => {
139
+ const o = objs[id];
140
+ if (o === undefined || o === null)
141
+ throw new Error(`ilgpuWebGPUPlan.submitBatch: ${what} (SpawnJS id ${id}) at record ${at} is not held - it was disposed while a dispatch still referenced it`);
142
+ return o;
143
+ };
144
+ const cap = (maxPassesPerSubmit > 0) ? (maxPassesPerSubmit | 0) : 0x7fffffff;
145
+ const queue = device.queue;
146
+ let staging = null;
147
+ if (uploadBytes > 0) {
148
+ staging = api._staging.get(device);
149
+ if (!staging || staging.size < uploadBytes) {
150
+ if (staging) staging.destroy(); // its last readers were submitted; destroy waits for them
151
+ let size = 65536;
152
+ while (size < uploadBytes) size *= 2;
153
+ staging = device.createBuffer({ label: 'ilgpu-batch-upload-staging', size, usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST });
154
+ api._staging.set(device, staging);
155
+ }
156
+ queue.writeBuffer(staging, 0, data, 0, uploadBytes);
157
+ }
158
+ const arenaOff = data.length - (arenaRBytes | 0) - (arenaWBytes | 0);
159
+ if (arenaRBytes > 0) queue.writeBuffer(obj(arenaRId, 'scalar arena', -1), 0, data, arenaOff, arenaRBytes);
160
+ if (arenaWBytes > 0) queue.writeBuffer(obj(arenaWId, 'scalar arena (read_write)', -1), 0, data, arenaOff + arenaRBytes, arenaWBytes);
161
+ let bgCache = null;
162
+ if (api.bindGroupReuse !== false) {
163
+ bgCache = api._bindGroups.get(device);
164
+ if (!bgCache) { bgCache = { cur: new Map(), prev: new Map() }; api._bindGroups.set(device, bgCache); api.bgDrops++; }
165
+ else if (bgCache.cur.size > BG_GEN_MAX) { bgCache.prev = bgCache.cur; bgCache.cur = new Map(); api.bgDrops++; }
166
+ }
167
+ const single = api.singlePass !== false;
168
+ let enc = null, passes = 0, ops = 0;
169
+ let pass = null, passPipeline = null;
170
+ const endPass = () => { if (pass !== null) { pass.end(); pass = null; passPipeline = null; } };
171
+ for (let i = 0; i < n; ops++) {
172
+ const tag = rec[i];
173
+ if (tag === 0 && ablation === 2) {
174
+ i += 7 + 4 * rec[i + 3];
175
+ } else if (tag === 0) {
176
+ const ne = rec[i + 3];
177
+ const j0 = i + 7, jEnd = j0 + 4 * ne;
178
+ let bindGroup, key;
179
+ if (bgCache !== null) {
180
+ key = '' + rec[i + 2];
181
+ for (let j = j0; j < jEnd; j++) key += ',' + rec[j];
182
+ bindGroup = bgCache.cur.get(key);
183
+ if (bindGroup === undefined) {
184
+ bindGroup = bgCache.prev.get(key);
185
+ if (bindGroup !== undefined) bgCache.cur.set(key, bindGroup);
186
+ }
187
+ }
188
+ if (bindGroup === undefined) {
189
+ const entries = new Array(ne);
190
+ for (let e = 0, j = j0; e < ne; e++, j += 4)
191
+ entries[e] = { binding: rec[j], resource: { buffer: obj(rec[j + 1], 'buffer', i), offset: rec[j + 2], size: rec[j + 3] } };
192
+ bindGroup = device.createBindGroup({ layout: obj(rec[i + 2], 'bind group layout', i), entries });
193
+ if (bgCache !== null) { bgCache.cur.set(key, bindGroup); api.bgMisses++; api.bgLastKey = key; }
194
+ } else api.bgHits++;
195
+ const j = jEnd;
196
+ if (enc === null) enc = device.createCommandEncoder();
197
+ const pipeline = obj(rec[i + 1], 'pipeline', i);
198
+ if (single) {
199
+ if (pass === null) pass = enc.beginComputePass();
200
+ if (pipeline !== passPipeline) { pass.setPipeline(pipeline); passPipeline = pipeline; }
201
+ pass.setBindGroup(0, bindGroup);
202
+ pass.dispatchWorkgroups(rec[i + 4], rec[i + 5], rec[i + 6]);
203
+ } else {
204
+ const p1 = enc.beginComputePass();
205
+ p1.setPipeline(pipeline);
206
+ p1.setBindGroup(0, bindGroup);
207
+ p1.dispatchWorkgroups(rec[i + 4], rec[i + 5], rec[i + 6]);
208
+ p1.end();
209
+ }
210
+ i = j;
211
+ if (++passes >= cap) { endPass(); queue.submit([enc.finish()]); enc = null; passes = 0; }
212
+ } else if (tag === 1) {
213
+ endPass();
214
+ if (enc === null) enc = device.createCommandEncoder();
215
+ enc.copyBufferToBuffer(obj(rec[i + 1], 'copy source', i), rec[i + 2], obj(rec[i + 3], 'copy destination', i), rec[i + 4], rec[i + 5]);
216
+ i += 6;
217
+ } else if (tag === 2) {
218
+ endPass();
219
+ if (enc === null) enc = device.createCommandEncoder();
220
+ enc.clearBuffer(obj(rec[i + 1], 'clear target', i), rec[i + 2], rec[i + 3]);
221
+ i += 4;
222
+ } else if (tag === 3) {
223
+ queue.writeBuffer(obj(rec[i + 1], 'write target', i), rec[i + 2], data, rec[i + 3], rec[i + 4]);
224
+ i += 5;
225
+ } else if (tag === 4) {
226
+ endPass();
227
+ if (enc === null) enc = device.createCommandEncoder();
228
+ enc.copyBufferToBuffer(staging, rec[i + 3], obj(rec[i + 1], 'upload target', i), rec[i + 2], rec[i + 4]);
229
+ i += 5;
230
+ } else {
231
+ throw new Error(`ilgpuWebGPUPlan.submitBatch: bad record tag ${tag} at ${i}`);
232
+ }
233
+ }
234
+ endPass();
235
+ if (enc !== null) queue.submit([enc.finish()]);
236
+ return ops;
237
+ },
238
+
239
+ // Replays a recorded plan on the given device: one pass per dispatch (pass-per-dispatch keeps
240
+ // storage-buffer write->read ordering guarantees airtight), copies/clears encoded inline in
241
+ // captured order, submitted in BATCHES of maxPassesPerSubmit compute passes.
242
+ // Returns the number of operations encoded.
243
+ //
244
+ // 🔴 WHY THIS BATCHES INSTEAD OF SUBMITTING ONCE. It used to encode the whole plan into a
245
+ // single command encoder and issue one queue.submit(). That is fine for a small plan and it
246
+ // LOSES THE DEVICE for a large one: MEASURED 2026-09-15, Kokoro at input_ids[1,360] replayed
247
+ // and Chrome came back "WebGPU device has been lost and cannot accept commands" - the GPU
248
+ // watchdog killing a single command buffer that ran too long. A 35-token Kokoro plan is
249
+ // already 3,155 dispatches; the 360-token one is several times that, in ONE buffer, with no
250
+ // point at which the driver can preempt.
251
+ //
252
+ // The uncaptured path never had this problem because WebGPUStream flushes as it goes - the
253
+ // library's own documented rule is "if dispatching many kernels (>50), call Flush() every
254
+ // 16-32 dispatches". Capture replay was the one path that ignored it. Splitting into several
255
+ // command buffers changes nothing about ordering: buffers submitted to the same queue execute
256
+ // in submission order, and the implicit inter-pass synchronization is per-queue, not
257
+ // per-buffer.
258
+ replay(device, plan, maxPassesPerSubmit) {
259
+ const t0 = performance.now();
260
+ const cap = (maxPassesPerSubmit > 0) ? (maxPassesPerSubmit | 0) : 0x7fffffff;
261
+ const n = plan.length;
262
+ let enc = device.createCommandEncoder();
263
+ let passesInBatch = 0;
264
+ let submitMs = 0;
265
+ const flush = () => {
266
+ const s0 = performance.now();
267
+ device.queue.submit([enc.finish()]);
268
+ submitMs += performance.now() - s0;
269
+ passesInBatch = 0;
270
+ };
271
+ for (let i = 0; i < n; i += 7) {
272
+ const tag = plan[i];
273
+ if (tag === 0) {
274
+ const pass = enc.beginComputePass();
275
+ pass.setPipeline(plan[i + 1]);
276
+ pass.setBindGroup(0, plan[i + 2]);
277
+ pass.dispatchWorkgroups(plan[i + 3], plan[i + 4], plan[i + 5]);
278
+ pass.end();
279
+ // Close the batch only BETWEEN operations, never inside a pass. A dispatch marked submitAfter
280
+ // (WORKAROUND, issue #10) must not share its command buffer with anything after it.
281
+ ++passesInBatch;
282
+ if (plan[i + 6] === 1 || passesInBatch >= cap) {
283
+ flush();
284
+ enc = device.createCommandEncoder();
285
+ }
286
+ } else if (tag === 1) {
287
+ enc.copyBufferToBuffer(plan[i + 1], plan[i + 2], plan[i + 3], plan[i + 4], plan[i + 5]);
288
+ } else if (tag === 2) {
289
+ enc.clearBuffer(plan[i + 1], plan[i + 2], plan[i + 3]);
290
+ }
291
+ }
292
+ const t1 = performance.now();
293
+ flush(); // the tail (a no-op encoder submits an empty buffer, which is legal)
294
+ api.last.ops = n / 7;
295
+ api.last.encodeMs = (t1 - t0) - submitMs;
296
+ api.last.submitMs = submitMs;
297
+ return n / 7;
298
+ },
299
+ // Replays the plan with per-pass GPU timestamps and returns a JSON string aggregating GPU
300
+ // time by pipeline label (the kernel name). Requires the device to have 'timestamp-query'
301
+ // (requested by ILGPU device init when the adapter supports it) - returns
302
+ // {"supported":false} otherwise. One timestamp at the START of each compute pass plus the
303
+ // END of the last pass: passes execute back-to-back on the queue, so t[k+1]-t[k] is pass
304
+ // k's duration (encoder-level copies/clears between passes are attributed to the preceding
305
+ // pass - negligible). Chunked across query sets (4096 timestamps max each). NOTE: Chrome
306
+ // quantizes timestamps to 100us unless --enable-webgpu-developer-features - the total
307
+ // (last-first) telescopes exactly either way, but fine per-kernel attribution wants the
308
+ // flag. Waits for GPU completion internally (the resolve readback maps after the work).
309
+ async replayTimed(device, plan) {
310
+ if (!device.features.has('timestamp-query'))
311
+ return JSON.stringify({ supported: false, reason: "device lacks timestamp-query" });
312
+ const n = plan.length;
313
+ const passIdx = []; // plan record offset of each compute pass
314
+ for (let i = 0; i < n; i += 7) if (plan[i] === 0) passIdx.push(i);
315
+ const passes = passIdx.length;
316
+ if (passes === 0)
317
+ return JSON.stringify({ supported: false, reason: "plan has no compute passes" });
318
+ const QS_CAP = 4096;
319
+ const stamps = passes + 1;
320
+ const querySets = [];
321
+ for (let remaining = stamps; remaining > 0; remaining -= QS_CAP)
322
+ querySets.push(device.createQuerySet({ type: 'timestamp', count: Math.min(remaining, QS_CAP) }));
323
+ const qsOf = k => querySets[Math.floor(k / QS_CAP)];
324
+ const qiOf = k => k % QS_CAP;
325
+
326
+ let enc = device.createCommandEncoder();
327
+ // The last pass also writes the closing timestamp (its end). timestampWrites targets ONE
328
+ // query set, so if that end index would land in the next chunk (passes ≡ 0 mod 4096),
329
+ // skip it - the last pass then simply has no duration row (correct, just one row short).
330
+ const hasClosingStamp = Math.floor(passes / QS_CAP) === Math.floor((passes - 1) / QS_CAP);
331
+ const measuredPasses = hasClosingStamp ? passes : passes - 1;
332
+ let k = 0;
333
+ for (let i = 0; i < n; i += 7) {
334
+ const tag = plan[i];
335
+ if (tag === 0) {
336
+ const tw = { querySet: qsOf(k), beginningOfPassWriteIndex: qiOf(k) };
337
+ if (k === passes - 1 && hasClosingStamp)
338
+ tw.endOfPassWriteIndex = qiOf(k + 1);
339
+ const pass = enc.beginComputePass({ timestampWrites: tw });
340
+ pass.setPipeline(plan[i + 1]);
341
+ pass.setBindGroup(0, plan[i + 2]);
342
+ pass.dispatchWorkgroups(plan[i + 3], plan[i + 4], plan[i + 5]);
343
+ pass.end();
344
+ k++;
345
+ // WORKAROUND (issue #10): keep the live path's submit boundary. Query sets are device objects, so
346
+ // the resolve in the final command buffer still reads every timestamp written before it.
347
+ if (plan[i + 6] === 1) {
348
+ device.queue.submit([enc.finish()]);
349
+ enc = device.createCommandEncoder();
350
+ }
351
+ } else if (tag === 1) {
352
+ enc.copyBufferToBuffer(plan[i + 1], plan[i + 2], plan[i + 3], plan[i + 4], plan[i + 5]);
353
+ } else if (tag === 2) {
354
+ enc.clearBuffer(plan[i + 1], plan[i + 2], plan[i + 3]);
355
+ }
356
+ }
357
+ // Resolve every query set into one buffer, then copy to a mappable readback buffer.
358
+ const resolveBuf = device.createBuffer({ size: stamps * 8, usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC });
359
+ const readBuf = device.createBuffer({ size: stamps * 8, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
360
+ for (let s = 0, ofs = 0; s < querySets.length; s++) {
361
+ enc.resolveQuerySet(querySets[s], 0, querySets[s].count, resolveBuf, ofs);
362
+ ofs += querySets[s].count * 8;
363
+ }
364
+ enc.copyBufferToBuffer(resolveBuf, 0, readBuf, 0, stamps * 8);
365
+ device.queue.submit([enc.finish()]);
366
+ await readBuf.mapAsync(GPUMapMode.READ);
367
+ const t = new BigUint64Array(readBuf.getMappedRange().slice(0));
368
+ readBuf.unmap();
369
+ readBuf.destroy(); resolveBuf.destroy();
370
+ for (const qs of querySets) qs.destroy();
371
+
372
+ // Aggregate pass durations by pipeline label, and keep each pass as a row in plan order with its workgroup
373
+ // counts (which SHAPE of a kernel is slow: e.g. a GEMM's late small layers launching too few workgroups).
374
+ const byLabel = new Map();
375
+ const dispatches = [];
376
+ let totalNs = 0;
377
+ for (let p = 0; p < measuredPasses; p++) {
378
+ const durNs = Number(t[p + 1] - t[p]);
379
+ const at = passIdx[p];
380
+ const label = plan[at + 1].label || '(unlabeled)';
381
+ const valid = durNs >= 0; // guard against wrap/invalid
382
+ dispatches.push({ label, ms: valid ? +(durNs / 1e6).toFixed(4) : null, wg: [plan[at + 3], plan[at + 4], plan[at + 5]] });
383
+ if (!valid) continue;
384
+ totalNs += durNs;
385
+ const e = byLabel.get(label) || { ms: 0, count: 0, maxMs: 0 };
386
+ e.ms += durNs / 1e6; e.count++; e.maxMs = Math.max(e.maxMs, durNs / 1e6);
387
+ byLabel.set(label, e);
388
+ }
389
+ const kernels = [...byLabel.entries()]
390
+ .map(([label, e]) => ({ label, ms: +e.ms.toFixed(3), count: e.count, maxMs: +e.maxMs.toFixed(3) }))
391
+ .sort((a, b) => b.ms - a.ms);
392
+ return JSON.stringify({
393
+ supported: true, passes, ops: n / 7,
394
+ totalMs: +(totalNs / 1e6).toFixed(3),
395
+ spanMs: +(Number(t[measuredPasses] - t[0]) / 1e6).toFixed(3),
396
+ kernels,
397
+ dispatches
398
+ });
399
+ }
400
+ };
401
+ // Register - but never downgrade. A second copy of this module (another URL, an old cached file) must not
402
+ // replace a newer one already in use: the library looks up ilgpuWebGPUPlan.submitBatch on every flush.
403
+ // Bump HELPER_VERSION whenever the api's surface changes.
404
+ const HELPER_VERSION = 6; // 2: submitBatch (plain-dispatch record batches, ordered uploads); 3: single-pass runs, setSinglePass; 4: scalar arenas, bind-group reuse; 5: submitHeader (pinned heap header); 6: replayTimed per-pass rows (dispatches)
405
+ api.version = HELPER_VERSION;
406
+ const existing = globalThis.ilgpuWebGPUPlan;
407
+ if (!existing || !(existing.version >= HELPER_VERSION)) globalThis.ilgpuWebGPUPlan = api;
408
+ })();
_framework/ILGPU.Algorithms.ffei46c8ng.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f25498d4f612e010b11f231ab2be335b172a851d22d8b452de18ffaba2d483ff
3
+ size 22402
_framework/ILGPU.k78gepz5ei.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22bae2b0771a8aa8e9a3e106e4ece40772919fbc5e6a8534c1591970e8a8e659
3
+ size 506681
_framework/Microsoft.AspNetCore.Components.Web.cmuc7bdjac.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86b3dd578ae8e46a7b89c68f103e9c14a85fb76e223920cff6ac86bedd55a441
3
+ size 28231
_framework/Microsoft.AspNetCore.Components.WebAssembly.iea6k79bon.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73f479308561f11f6c7727f7e383f46055b8e6cfa2a6452c1b646e12bca490fd
3
+ size 49972
_framework/Microsoft.AspNetCore.Components.irsccstbtv.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5283e6f68a60d357d6c35eb29e6f313a961c45ccbe2d178483ef5046def0475b
3
+ size 110557
_framework/Microsoft.Extensions.Configuration.Abstractions.wslsrredsq.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d162efb609ea061afb94d43d914c9afd6bfd06506e32c3e6124f8a9f8a2ef99
3
+ size 2698
_framework/Microsoft.Extensions.Configuration.Json.dmmcgk01r0.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d77f10dc1fb571eac1225471953dd41e4a1ed23c22192ecadf1cbb615dbd1181
3
+ size 4762
_framework/Microsoft.Extensions.Configuration.rgjmp347zf.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2fb72ff395eb03c95f070729077a2c0e6f8ad96508a28d2a8232e87cbbf8326
3
+ size 4167
_framework/Microsoft.Extensions.DependencyInjection.Abstractions.d95iifg76m.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55d3d29f507b7624fa2fab78056ed21a306e0065804b8ecaf9a5e0771689d8f1
3
+ size 13206
_framework/Microsoft.Extensions.DependencyInjection.mvfec3p7kh.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbdf1b10cd968650d7c5f54b9794025581adb7ea79cb1adde6650b90005fe526
3
+ size 22442
_framework/Microsoft.Extensions.Logging.5w9ia7xlgq.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aae8809175f256fefd479894e0ff6006b3b3eae0e27aa1692207ee07e31972fe
3
+ size 8627
_framework/Microsoft.Extensions.Logging.Abstractions.xx3hs6cn2q.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48d05d5ce63088dd0b23798456cf3d8942c49cac0ac69f23c588c055bcb2c0de
3
+ size 12564
_framework/Microsoft.Extensions.Options.espvvlqak1.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b086d423f7b99db8bbf606b353d3b5b9358e2bf51c349e055285f8838e117fb
3
+ size 8150
_framework/Microsoft.Extensions.Primitives.crxdkm6t9l.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aca61a0f270479230d4b1270e796a7cd81d4080de862fda359033fc259dfd49a
3
+ size 5158
_framework/Microsoft.JSInterop.0523xs2ej1.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:213c66b5c20b7faa0a2ddca7ad0ec0658a8fb6cc30cef90ea5bcd1ed926f1233
3
+ size 21422
_framework/Microsoft.JSInterop.WebAssembly.5ql0ra5mpq.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:252ab1c7b0b3a7c67d65f641f5ec942f3fcfcc39ca39fb901304e26593445a7a
3
+ size 5636
_framework/SpawnDev.BackgroundServices.1yeryblw74.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:947d1c299d5a6ddce9201ca017fbc8df7278245fbfdec97ac0c89b4a898cb7df
3
+ size 32526
_framework/SpawnDev.Blazor.BootRecovery.wqj5nz7x99.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:284efa3bfea1ca5a0d9882c29cfc49260bcb725c9cb07087bbae12d6dde66c42
3
+ size 9673
_framework/SpawnDev.Codecs.xofv24znhd.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee0a1ef3aab5032d05465cf821290911f1356db1755545b66073e851fad87de7
3
+ size 3650706
_framework/SpawnDev.EBML.xdne5e0w64.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2aea025ec965d9c5e22a6a07e5dfa14c07859fc0c70ebe97b979a04c560df9fd
3
+ size 154241
_framework/SpawnDev.ILGPU.6mjayrscgw.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8ed3e63e657611119e28f064b23d319ffc132ebced44273417522fcdff38d30
3
+ size 1821971
_framework/SpawnDev.ILGPU.ML.2gzqxw91d8.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:11ded34378ce8da7a27fc1cf3c2544c3752bae5c68894279e9e5c2c23b9ed510
3
+ size 4102976
_framework/SpawnDev.ILGPU.ML.Kernels.xas971tlmk.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:67dd9619eda3db6796907190f17e5d78cf0f9e3e2f185ca7488f84848af8f9ca
3
+ size 718097
_framework/SpawnDev.MultiMedia.omfwfbvzp1.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b25b3c09bb6a2bd050dd9864a3936953e02b14e3fc104fa3935a8712e7692a2d
3
+ size 164220
_framework/SpawnDev.PatchStreams.fa7qoyfxjz.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28904938ed8d93ca4eae855d612c3da7a2128b769a475a50366d54d28a182a32
3
+ size 39873
_framework/SpawnDev.Phonemizer.14wgzuo4bh.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c58fe5d9d3545cb8e124cd91aea1aee3b667338d681b4a664f05e450bd22a2f
3
+ size 1474813
_framework/SpawnDev.SpawnJS.Blazor.pmbh2dtfc3.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ee9e0f73ba1140f493fd760c105b3202b66bfdf1da59150f1106fe2398936a5
3
+ size 15810
_framework/SpawnDev.SpawnJS.obwsmd2ii3.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a2387101296195939cfbed2614688f52911d01b5850e93320a946488340e24a
3
+ size 1471276
_framework/SpawnGen.Editor.ysklqo5dvy.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5d7cb62f34bbd5b8c16bc7200eaa6b40a35bc6c0268f558042e7d65961cecd0f
3
+ size 123171
_framework/SpawnGen.Engine.963inzh8su.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc417b6cd752e7dbbab591a53e0ee86b2570a81eec7d0bc1e5ee1caf84f277ae
3
+ size 76961
_framework/SpawnGen.Glsl.gumig0hdrg.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da717294b231d08ead5f7bbe98f38afdf75825c31456eec374bcd9199385f16f
3
+ size 54422
_framework/SpawnGen.Nodes.Core.nefbdvknei.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa5b1a25ecfe89e31a1b78afa5a9572d22df7133b75a5d1d5dfbcac13c34daf9
3
+ size 353765
_framework/SpawnGen.Nodes.ML.m5uycdlwtd.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7cd36ae79c15c1cc8c8d77234f793ea1b5a0567247976b6545c643046e623f2c
3
+ size 348653
_framework/SpawnGen.Runtime.75kyqfga9w.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d759af4fc1c1017f51c432be489c98b65f7c8990a55ac4ea5688abe8ebf1a5f2
3
+ size 17072
_framework/SpawnGen.Studio.r201i5b3vg.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d54143271d95ce92a031fc9efb7bae8e9c1ca14d40a9e254a8f25e70ed91d1cf
3
+ size 177164
_framework/System.Collections.Concurrent.ff7cq2nm1d.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da739802d5b28f0690047b305fea70225a82eda20744a052e2afb432d1d0520c
3
+ size 14291
_framework/System.Collections.Immutable.wgf13aswj8.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:304119e9a4ec0690edcc8708a7df28d41af163914d8d726abcab2adf6c107e10
3
+ size 33831
_framework/System.Collections.NonGeneric.hsozm72ati.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c8e321c03e6b4eab32c0755e4ba5d22f18eef6ff6a0681fb66295a9ed3b042c
3
+ size 3244
_framework/System.Collections.Specialized.f7h3kag6r1.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:adefb2dc8feff1a714574c19792f504aec1563674795d26195e62846d15dcc0c
3
+ size 4374
_framework/System.Collections.aw6c0lqys1.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d55d23bd6c88f3ab0e1a65f4b7c30ad6a1b491cb131a9b80860bfd4013a0410
3
+ size 25742
_framework/System.ComponentModel.Annotations.nftdtj3wv1.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd7063454e5e673efe55d39f9b4e4f32fabf3aca4e08569ce93ad3d14323403e
3
+ size 2357
_framework/System.ComponentModel.Primitives.5z48w2rdnk.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a17e4a38d7297a7e51881aa8224cfdd9af5b433907489f43718f6cad6ec70c86
3
+ size 3027
_framework/System.ComponentModel.TypeConverter.wyfjsyv15c.wasm.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:138d6f234533f5bd7b704b81f803bcab27a1d23f177ec6b8cb30c5c534a1f504
3
+ size 19669