@biodream-llc/zyth-runtime 0.0.0-stage → 0.1.0-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/LICENSE-MIT ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BioDream LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/index.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ // Generated by `zyth build --target npm-runtime`. Do not edit.
2
+
3
+ /** Element types a tensor crosses into JavaScript as. */
4
+ export type DType = "f32" | "f64" | "i32" | "i64" | "u8" | "bool";
5
+
6
+ /** The typed array behind each element type. */
7
+ export interface TensorData {
8
+ f32: Float32Array;
9
+ f64: Float64Array;
10
+ i32: Int32Array;
11
+ i64: BigInt64Array;
12
+ u8: Uint8Array;
13
+ bool: Uint8Array;
14
+ }
15
+
16
+ export class Tensor<D extends DType = DType> {
17
+ constructor(data: TensorData[D], shape?: number[], dtype?: D);
18
+ readonly data: TensorData[D];
19
+ readonly shape: number[];
20
+ readonly dtype: D;
21
+ readonly size: number;
22
+ /** Nested JavaScript arrays. */
23
+ toArray(): unknown;
24
+ }
25
+
26
+ /** What tensor parameters accept: a Tensor, a typed array (1-D), `{ data, shape }`, or nested number arrays. */
27
+ export type TensorInput = Tensor | Float32Array | Float64Array | Int32Array | { data: ArrayBufferView; shape: number[] } | number[] | number[][] | number[][][];
28
+
29
+ /** `tensor([[1, 2], [3, 4]])` or `tensor(float32Array, [2, 2])`. */
30
+ export function tensor<D extends DType = "f32">(data: unknown, shape?: number[], dtype?: D): Tensor<D>;
31
+
32
+ export class ZythError extends Error {
33
+ readonly code: string;
34
+ /** The full Zyth diagnostic. */
35
+ readonly details: string;
36
+ }
37
+
38
+ /** An argument's shape, dtype, or device does not match the Zyth signature. */
39
+ export class ZythShapeError extends ZythError {}
40
+
41
+ /** Load the runtime and every registered Zyth program ahead of the first call (optional). */
42
+ export function load(): Promise<void>;
43
+ /** Used by the code of Zyth packages: registers a package's program. */
44
+ export function library(source: string, opts?: { name?: string; full?: boolean; code?: string }): unknown;
45
+ /** Options, before the first call: `{ gpu: false }` computes `gpu` tensors on the CPU. */
46
+ export function configure(opts?: { gpu?: boolean }): void;
47
+ /** Where `gpu` tensors are computed: the WebGPU adapter's name (browsers and Deno with WebGPU), or "cpu". */
48
+ export function device(): Promise<string>;
49
+
package/index.js ADDED
@@ -0,0 +1,848 @@
1
+ // @ts-self-types="./index.d.ts"
2
+ // Generated by `zyth build --target npm-runtime`. Do not edit.
3
+ const __zythGpuRoot = {};
4
+ // WebGPU runtime for Zyth's WebAssembly build: provides the `env.zyth_gpu_*`
5
+ // imports that crates/zyth-tensor/src/webgpu.rs calls.
6
+ //
7
+ // const gpu = await ZythGPU.create(); // null without WebGPU + JSPI
8
+ // const env = { ...yourImports, ...ZythGPU.imports(gpu, () => memory) };
9
+ // const { instance } = await WebAssembly.instantiate(bytes, { env });
10
+ // const ex = ZythGPU.wrap(instance.exports, gpu); // entry points become async
11
+ //
12
+ // Reading GPU memory is asynchronous in WebGPU; `zyth_gpu_read` suspends the
13
+ // WebAssembly stack with JSPI (WebAssembly.Suspending) until the copy is done,
14
+ // so entry points that may compute on the GPU must be called through `wrap`.
15
+ // Without WebGPU or JSPI, `zyth_gpu_available` returns 0 and `gpu` tensors are
16
+ // computed on the CPU.
17
+ (function (root) {
18
+ "use strict";
19
+ const ENTRY_POINTS = ["zyth_run", "zyth_app_start", "zyth_app_event", "zyth_lib_call", "zyth_lib_call_in", "zyth_lib_load", "zyth_lib_load_code"];
20
+
21
+ async function create() {
22
+ if (typeof navigator === "undefined" || !navigator.gpu) return null;
23
+ if (typeof WebAssembly.Suspending !== "function" || typeof WebAssembly.promising !== "function") return null;
24
+ const adapter = await navigator.gpu.requestAdapter();
25
+ if (!adapter) return null;
26
+ const lim = adapter.limits;
27
+ const device = await adapter.requestDevice({
28
+ requiredLimits: {
29
+ maxStorageBufferBindingSize: lim.maxStorageBufferBindingSize,
30
+ maxBufferSize: lim.maxBufferSize,
31
+ maxStorageBuffersPerShaderStage: Math.min(lim.maxStorageBuffersPerShaderStage, 10),
32
+ },
33
+ });
34
+ const info = adapter.info || {};
35
+ const name = [info.vendor, info.architecture, info.description].filter(Boolean).join(" ");
36
+ device.lost.then((e) => console.warn("Zyth: WebGPU device lost:", e.message));
37
+ device.onuncapturederror = (e) => console.error("Zyth WebGPU error:", e.error.message);
38
+ // dispatches are batched: their parameters share one buffer, and they share one compute pass
39
+ const align = Math.max(4, (device.limits.minStorageBufferOffsetAlignment || 256) / 4);
40
+ return { device, name, bufs: [null], pipes: [null], layouts: [null], encoder: null, pending: 0, batch: [], words: new Uint32Array(1 << 14), wlen: 0, align };
41
+ }
42
+
43
+ function imports(g, memory) {
44
+ const mem = () => memory().buffer;
45
+ const stub = {
46
+ zyth_gpu_available: () => 0,
47
+ zyth_gpu_alloc: () => 0,
48
+ zyth_gpu_free: () => {},
49
+ zyth_gpu_write: () => {},
50
+ zyth_gpu_read: () => {},
51
+ zyth_gpu_copy: () => {},
52
+ zyth_gpu_clear: () => {},
53
+ zyth_gpu_kernel: () => 0,
54
+ zyth_gpu_dispatch: () => 1,
55
+ zyth_gpu_name: () => 0,
56
+ };
57
+ // zyth.gfx without WebGPU: nothing draws (gfx.available() is false)
58
+ for (const k of ["zyth_gfx_surface", "zyth_gfx_shader", "zyth_gfx_pipeline", "zyth_gfx_buffer", "zyth_gfx_texture", "zyth_gfx_sampler", "zyth_gfx_events", "zyth_gfx_error"]) stub[k] = () => 0;
59
+ for (const k of ["zyth_gfx_samples", "zyth_gfx_texture_write"]) stub[k] = () => 1;
60
+ for (const k of ["zyth_gfx_available"]) stub[k] = () => 0;
61
+ for (const k of ["zyth_gfx_size", "zyth_gfx_free", "zyth_gfx_present", "zyth_gfx_close"]) stub[k] = () => {};
62
+ for (const k of ["zyth_gfx_buffer_write", "zyth_gfx_frame", "zyth_gfx_read"]) stub[k] = () => 1;
63
+ if (!g) return stub;
64
+ const dev = g.device;
65
+ const dec = new TextDecoder();
66
+ const U = GPUBufferUsage;
67
+ // encode the batched dispatches, in order, before anything encoded after them
68
+ const encodeBatch = () => {
69
+ if (!g.batch.length) return;
70
+ const total = Math.max(4, g.wlen);
71
+ const params = dev.createBuffer({ size: total * 4, usage: U.STORAGE, mappedAtCreation: true });
72
+ new Uint32Array(params.getMappedRange()).set(g.words.subarray(0, total));
73
+ params.unmap();
74
+ const e = (g.encoder ||= dev.createCommandEncoder());
75
+ const pass = e.beginComputePass();
76
+ for (const c of g.batch) {
77
+ const entries = [{ binding: 0, resource: { buffer: params, offset: c.off * 4, size: c.len * 4 } }];
78
+ for (let i = 0; i < c.bufs.length; i++) entries.push({ binding: i + 1, resource: { buffer: c.bufs[i] } });
79
+ pass.setPipeline(c.p);
80
+ pass.setBindGroup(0, dev.createBindGroup({ layout: c.layout, entries }));
81
+ pass.dispatchWorkgroups(c.gx, c.gy, c.gz);
82
+ }
83
+ pass.end();
84
+ g.batch = [];
85
+ g.wlen = 0;
86
+ };
87
+ const enc = () => {
88
+ encodeBatch();
89
+ return (g.encoder ||= dev.createCommandEncoder());
90
+ };
91
+ const flush = () => {
92
+ encodeBatch();
93
+ if (g.encoder) {
94
+ dev.queue.submit([g.encoder.finish()]);
95
+ g.encoder = null;
96
+ g.pending = 0;
97
+ }
98
+ };
99
+ return {
100
+ zyth_gpu_available: () => 1,
101
+ zyth_gpu_alloc: (bytes) => {
102
+ // (VERTEX and INDEX too: zyth.gfx draws from tensors' buffers)
103
+ const b = dev.createBuffer({ size: Math.max(16, (bytes + 3) & ~3), usage: U.STORAGE | U.COPY_SRC | U.COPY_DST | U.VERTEX | U.INDEX });
104
+ g.bufs.push(b);
105
+ return g.bufs.length - 1;
106
+ },
107
+ zyth_gpu_free: (id) => {
108
+ const b = g.bufs[id];
109
+ if (b) b.destroy();
110
+ g.bufs[id] = null;
111
+ },
112
+ zyth_gpu_write: (id, off, ptr, len) => {
113
+ // earlier dispatches may still use this (pooled) buffer: keep queue order
114
+ flush();
115
+ const src = new Uint8Array(mem(), ptr, len);
116
+ const n = len & ~3;
117
+ if (n > 0) dev.queue.writeBuffer(g.bufs[id], off, src, 0, n);
118
+ if (len > n) {
119
+ const tail = new Uint8Array(4);
120
+ tail.set(src.subarray(n));
121
+ dev.queue.writeBuffer(g.bufs[id], off + n, tail);
122
+ }
123
+ },
124
+ zyth_gpu_read: new WebAssembly.Suspending(async (id, off, ptr, len) => {
125
+ const size = (len + 3) & ~3;
126
+ const staging = dev.createBuffer({ size, usage: U.MAP_READ | U.COPY_DST });
127
+ enc().copyBufferToBuffer(g.bufs[id], off, staging, 0, size);
128
+ flush();
129
+ try {
130
+ await staging.mapAsync(GPUMapMode.READ);
131
+ new Uint8Array(mem(), ptr, len).set(new Uint8Array(staging.getMappedRange(), 0, len));
132
+ staging.unmap();
133
+ } catch (e) {
134
+ console.error("Zyth: WebGPU readback failed:", e.message);
135
+ new Uint8Array(mem(), ptr, len).fill(0);
136
+ }
137
+ staging.destroy();
138
+ }),
139
+ zyth_gpu_copy: (dst, src, len) => enc().copyBufferToBuffer(g.bufs[src], 0, g.bufs[dst], 0, (len + 3) & ~3),
140
+ zyth_gpu_clear: (id, len) => enc().clearBuffer(g.bufs[id], 0, (len + 3) & ~3),
141
+ zyth_gpu_kernel: (np, nl, sp, sl) => {
142
+ const name = dec.decode(new Uint8Array(mem(), np, nl));
143
+ const code = dec.decode(new Uint8Array(mem(), sp, sl));
144
+ const module = dev.createShaderModule({ code, label: name });
145
+ module.getCompilationInfo().then((info) => {
146
+ for (const m of info.messages) if (m.type === "error") console.error(`Zyth WGSL ${name}:${m.lineNum}: ${m.message}`);
147
+ });
148
+ const p = dev.createComputePipeline({ layout: "auto", compute: { module, entryPoint: "main" }, label: name });
149
+ g.pipes.push(p);
150
+ g.layouts.push(p.getBindGroupLayout(0));
151
+ return g.pipes.length - 1;
152
+ },
153
+ zyth_gpu_dispatch: (pipe, wp, nw, bp, nb, gx, gy, gz) => {
154
+ const p = g.pipes[pipe];
155
+ if (!p) return 1;
156
+ // this dispatch's parameters at an aligned offset of the batch's parameter buffer
157
+ const off = Math.ceil(g.wlen / g.align) * g.align;
158
+ const len = Math.max(4, nw);
159
+ if (off + len > g.words.length) {
160
+ const w = new Uint32Array(Math.max(g.words.length * 2, off + len));
161
+ w.set(g.words.subarray(0, g.wlen));
162
+ g.words = w;
163
+ }
164
+ g.words.fill(0, g.wlen, off + len);
165
+ g.words.set(new Uint32Array(mem(), wp, nw), off);
166
+ g.wlen = off + len;
167
+ const ids = new Uint32Array(mem(), bp, nb);
168
+ const bufs = [];
169
+ for (let i = 0; i < nb; i++) bufs.push(g.bufs[ids[i]]);
170
+ g.batch.push({ p, layout: g.layouts[pipe], bufs, off, len, gx, gy, gz });
171
+ if (++g.pending >= 512) flush();
172
+ return 0;
173
+ },
174
+ zyth_gpu_name: (ptr, cap) => {
175
+ const b = new TextEncoder().encode(g.name);
176
+ const n = Math.min(b.length, cap);
177
+ new Uint8Array(mem(), ptr, n).set(b.subarray(0, n));
178
+ return n;
179
+ },
180
+ ...gfxImports(g, mem, flush),
181
+ };
182
+ }
183
+
184
+ // zyth.gfx (crates/zyth-tensor/src/gfx_web.rs): drawing with the same device as `gpu` tensors.
185
+ // Every surface draws into an sRGB texture (so colors match native builds and frames can be
186
+ // read back); a canvas gets a copy of it at the end of each frame.
187
+ function gfxImports(g, mem, flush) {
188
+ const dev = g.device;
189
+ const dec = new TextDecoder();
190
+ const U = GPUBufferUsage, T = GPUTextureUsage;
191
+ const str = (p, l) => dec.decode(new Uint8Array(mem(), p, l));
192
+ const gx = (g.gfx = { surfaces: [null], shaders: [null], pipes: [null], bufs: [null], texs: [null], texobjs: [], samplers: [null], error: "" });
193
+ const fail = (m) => { gx.error = String(m); return 0; };
194
+ const FMT = "rgba8unorm-srgb";
195
+ const target = (w, h) => dev.createTexture({ size: [w, h], format: FMT, usage: T.RENDER_ATTACHMENT | T.COPY_SRC | T.TEXTURE_BINDING });
196
+ const depth = (w, h, n = 1) => dev.createTexture({ size: [w, h], format: "depth32float", usage: T.RENDER_ATTACHMENT, sampleCount: n });
197
+ const msaa = (w, h, n) => (n > 1 ? dev.createTexture({ size: [w, h], format: FMT, usage: T.RENDER_ATTACHMENT, sampleCount: n }) : null);
198
+ const vfmt = { f32: ["float32", 4], f32x2: ["float32x2", 8], f32x3: ["float32x3", 12], f32x4: ["float32x4", 16], u32: ["uint32", 4], u32x2: ["uint32x2", 8], u32x3: ["uint32x3", 12], u32x4: ["uint32x4", 16], i32: ["sint32", 4], i32x2: ["sint32x2", 8], unorm8x4: ["unorm8x4", 4] };
199
+ // a canvas with a host element goes into the element now carrying that id (it may have
200
+ // appeared since, or been replaced by a new one)
201
+ const place = (s) => {
202
+ if (!s.host || typeof document === "undefined") return;
203
+ const h = document.getElementById(s.host);
204
+ if (h && s.canvas.parentNode !== h) h.appendChild(s.canvas);
205
+ };
206
+ const keyOf = (e) => (e.key.length === 1 ? e.key : e.key === "Escape" ? "Escape" : e.key);
207
+ const scoped = async (f) => {
208
+ dev.pushErrorScope("validation");
209
+ let r;
210
+ try { r = f(); } catch (e) { await dev.popErrorScope(); return fail(e.message); }
211
+ const e = await dev.popErrorScope();
212
+ return e ? fail(e.message) : r;
213
+ };
214
+ return {
215
+ zyth_gfx_available: () => 1,
216
+ zyth_gfx_error: (p, cap) => {
217
+ const b = new TextEncoder().encode(gx.error);
218
+ const n = Math.min(b.length, cap);
219
+ new Uint8Array(mem(), p, n).set(b.subarray(0, n));
220
+ gx.error = "";
221
+ return n;
222
+ },
223
+ zyth_gfx_surface: (w, h, canvas, tp, tl) => {
224
+ const s = { w, h, color: target(w, h), depth: depth(w, h), samples: 1, msaa: null, events: [], canvas: null, ctx: null };
225
+ if (canvas && typeof document !== "undefined") {
226
+ const c = document.createElement("canvas");
227
+ c.width = w; c.height = h; c.tabIndex = 0;
228
+ c.className = "zyth-gfx";
229
+ // "title\0host": the canvas goes into the element with id `host` (gfx.window(host:))
230
+ // (with a host, the canvas waits until the element exists, and follows it when the
231
+ // page replaces it, e.g. a React component mounted again: see `place`)
232
+ const [title, host] = str(tp, tl).split("\0");
233
+ c.title = title;
234
+ s.host = host || null;
235
+ if (host) { const h = document.getElementById(host); if (h) h.appendChild(c); }
236
+ else (document.getElementById("zyth-gfx") || document.body).appendChild(c);
237
+ const ctx = c.getContext("webgpu");
238
+ ctx.configure({ device: dev, format: "rgba8unorm", viewFormats: [FMT], usage: T.RENDER_ATTACHMENT, alphaMode: "opaque" });
239
+ const pos = (e) => { const r = c.getBoundingClientRect(); return [(e.clientX - r.left) * (w / r.width), (e.clientY - r.top) * (h / r.height)]; };
240
+ const btn = (b) => ["left", "middle", "right"][b] || "other";
241
+ c.addEventListener("pointermove", (e) => { const [x, y] = pos(e); s.events.push(`mouse_move\t${x}\t${y}`); });
242
+ c.addEventListener("pointerdown", (e) => { c.focus(); const [x, y] = pos(e); s.events.push(`mouse_down\t${btn(e.button)}\t${x}\t${y}`); });
243
+ c.addEventListener("pointerup", (e) => { const [x, y] = pos(e); s.events.push(`mouse_up\t${btn(e.button)}\t${x}\t${y}`); });
244
+ c.addEventListener("wheel", (e) => { e.preventDefault(); s.events.push(`wheel\t${-e.deltaX / 100}\t${-e.deltaY / 100}`); }, { passive: false });
245
+ c.addEventListener("keydown", (e) => s.events.push(`key_down\t${keyOf(e)}`));
246
+ c.addEventListener("keyup", (e) => s.events.push(`key_up\t${keyOf(e)}`));
247
+ s.canvas = c; s.ctx = ctx;
248
+ }
249
+ gx.surfaces.push(s);
250
+ return gx.surfaces.length - 1;
251
+ },
252
+ zyth_gfx_samples: (id, n) => {
253
+ const s = gx.surfaces[id];
254
+ if (!s) { fail("unknown surface"); return 1; }
255
+ if (s.samples !== n) { s.samples = n; s.depth = depth(s.w, s.h, n); s.msaa = msaa(s.w, s.h, n); }
256
+ return 0;
257
+ },
258
+ zyth_gfx_size: (id, out) => {
259
+ const s = gx.surfaces[id];
260
+ new Uint32Array(mem(), out, 2).set(s ? [s.w, s.h] : [0, 0]);
261
+ },
262
+ zyth_gfx_shader: new WebAssembly.Suspending(async (p, l) => {
263
+ const code = str(p, l);
264
+ const m = dev.createShaderModule({ code, label: "zyth shader" });
265
+ const info = await m.getCompilationInfo();
266
+ const errs = info.messages.filter((x) => x.type === "error");
267
+ if (errs.length) return fail(errs.map((x) => `${x.lineNum}:${x.linePos}: ${x.message}`).join("; "));
268
+ gx.shaders.push(m);
269
+ return gx.shaders.length - 1;
270
+ }),
271
+ zyth_gfx_pipeline: new WebAssembly.Suspending(async (p, l) => {
272
+ const d = JSON.parse(str(p, l));
273
+ const m = gx.shaders[d.shader];
274
+ if (!m) return fail("unknown shader");
275
+ let loc = 0;
276
+ const buffers = [];
277
+ for (const b of d.buffers) {
278
+ let off = 0;
279
+ const attributes = [];
280
+ for (const a of b.attrs) {
281
+ const f = vfmt[a];
282
+ if (!f) return fail(`unknown vertex format \`${a}\``);
283
+ attributes.push({ format: f[0], offset: off, shaderLocation: loc++ });
284
+ off += f[1];
285
+ }
286
+ buffers.push({ arrayStride: off, stepMode: b.instance ? "instance" : "vertex", attributes });
287
+ }
288
+ const topo = { triangles: "triangle-list", triangle_list: "triangle-list", triangle_strip: "triangle-strip", lines: "line-list", line_list: "line-list", line_strip: "line-strip", points: "point-list", point_list: "point-list" }[d.topology];
289
+ if (!topo) return fail(`unknown topology \`${d.topology}\``);
290
+ const blend = { none: undefined, "": undefined, alpha: { color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha" }, alpha: { srcFactor: "one", dstFactor: "one-minus-src-alpha" } }, add: { color: { srcFactor: "one", dstFactor: "one" }, alpha: { srcFactor: "one", dstFactor: "one-minus-src-alpha" } } };
291
+ if (!(d.blend in blend)) return fail(`unknown blend \`${d.blend}\``);
292
+ const cull = { none: "none", "": "none", back: "back", front: "front" }[d.cull];
293
+ if (!cull) return fail(`unknown cull mode \`${d.cull}\``);
294
+ const pipe = await scoped(() => dev.createRenderPipeline({
295
+ label: "zyth pipeline",
296
+ layout: "auto",
297
+ vertex: { module: m, entryPoint: d.vertex, buffers },
298
+ primitive: { topology: topo, cullMode: cull },
299
+ multisample: { count: (gx.surfaces[d.surface] || {}).samples || 1 },
300
+ depthStencil: { format: "depth32float", depthWriteEnabled: d.depth, depthCompare: d.depth ? "less" : "always" },
301
+ fragment: { module: m, entryPoint: d.fragment, targets: [{ format: FMT, blend: blend[d.blend] }] },
302
+ }));
303
+ if (!pipe) return 0;
304
+ gx.pipes.push(pipe);
305
+ return gx.pipes.length - 1;
306
+ }),
307
+ zyth_gfx_buffer: (p, l) => {
308
+ const size = Math.max(16, (l + 15) & ~15);
309
+ const b = dev.createBuffer({ size, usage: U.VERTEX | U.INDEX | U.UNIFORM | U.STORAGE | U.COPY_DST, label: "zyth gfx buffer" });
310
+ const src = new Uint8Array(mem(), p, l);
311
+ const n = l & ~3;
312
+ if (n) dev.queue.writeBuffer(b, 0, src, 0, n);
313
+ if (l > n) { const t = new Uint8Array(4); t.set(src.subarray(n)); dev.queue.writeBuffer(b, n, t); }
314
+ gx.bufs.push(b);
315
+ return gx.bufs.length - 1;
316
+ },
317
+ zyth_gfx_buffer_write: (id, off, p, l) => {
318
+ const b = gx.bufs[id];
319
+ if (!b) { fail("unknown buffer"); return 1; }
320
+ if (off + l > b.size) { fail(`writing ${l} bytes at ${off} goes past the end of a buffer of ${b.size} bytes`); return 1; }
321
+ const src = new Uint8Array(mem(), p, l);
322
+ const n = l & ~3;
323
+ if (n) dev.queue.writeBuffer(b, off, src, 0, n);
324
+ if (l > n) { const t = new Uint8Array(4); t.set(src.subarray(n)); dev.queue.writeBuffer(b, off + n, t); }
325
+ return 0;
326
+ },
327
+ zyth_gfx_free: (id) => { const b = gx.bufs[id]; if (b) b.destroy(); gx.bufs[id] = null; },
328
+ zyth_gfx_texture: (w, h, p, l) => {
329
+ const t = dev.createTexture({ size: [w, h], format: FMT, usage: T.TEXTURE_BINDING | T.COPY_DST });
330
+ dev.queue.writeTexture({ texture: t }, new Uint8Array(mem(), p, l), { bytesPerRow: 4 * w, rowsPerImage: h }, [w, h]);
331
+ gx.texs.push(t.createView());
332
+ gx.texobjs[gx.texs.length - 1] = t;
333
+ return gx.texs.length - 1;
334
+ },
335
+ zyth_gfx_texture_write: (id, x, y, w, h, p, l) => {
336
+ const t = gx.texobjs[id];
337
+ if (!t) { fail("unknown texture"); return 1; }
338
+ dev.queue.writeTexture({ texture: t, origin: [x, y] }, new Uint8Array(mem(), p, l), { bytesPerRow: 4 * w, rowsPerImage: h }, [w, h]);
339
+ return 0;
340
+ },
341
+ zyth_gfx_sampler: (p, l) => {
342
+ const d = JSON.parse(str(p, l));
343
+ const a = { clamp: "clamp-to-edge", repeat: "repeat", mirror: "mirror-repeat" }[d.wrap];
344
+ gx.samplers.push(dev.createSampler({ magFilter: d.filter, minFilter: d.filter, addressModeU: a, addressModeV: a, addressModeW: a }));
345
+ return gx.samplers.length - 1;
346
+ },
347
+ zyth_gfx_frame: (sid, p, l) => {
348
+ const s = gx.surfaces[sid];
349
+ if (!s) { fail("unknown surface"); return 1; }
350
+ const f = JSON.parse(str(p, l));
351
+ // tensor work first (the frame may draw what it computed)
352
+ flush();
353
+ const res = (b) => (b[0] === 1 ? g.bufs[b[1]] : gx.bufs[b[1]]);
354
+ const e = dev.createCommandEncoder({ label: "zyth frame" });
355
+ const pass = e.beginRenderPass({
356
+ // multisampled: drawn into the samples, resolved into the surface's texture
357
+ colorAttachments: [s.msaa
358
+ ? { view: s.msaa.createView(), resolveTarget: s.color.createView(), clearValue: { r: f.clear[0], g: f.clear[1], b: f.clear[2], a: f.clear[3] }, loadOp: "clear", storeOp: "discard" }
359
+ : { view: s.color.createView(), clearValue: { r: f.clear[0], g: f.clear[1], b: f.clear[2], a: f.clear[3] }, loadOp: "clear", storeOp: "store" }],
360
+ depthStencilAttachment: { view: s.depth.createView(), depthClearValue: 1, depthLoadOp: "clear", depthStoreOp: "discard" },
361
+ });
362
+ for (const d of f.draws) {
363
+ const pipe = gx.pipes[d.p];
364
+ if (!pipe) { fail("unknown pipeline"); return 1; }
365
+ pass.setPipeline(pipe);
366
+ if (d.b.length) {
367
+ const entries = d.b.map((b, i) => {
368
+ if (b[0] === 2) return { binding: i, resource: gx.texs[b[1]] };
369
+ if (b[0] === 4) return { binding: i, resource: gx.surfaces[b[1]].color.createView() };
370
+ if (b[0] === 3) return { binding: i, resource: gx.samplers[b[1]] };
371
+ if (b[0] === 1) return { binding: i, resource: { buffer: g.bufs[b[1]], offset: b[2], size: b[3] } };
372
+ return { binding: i, resource: { buffer: gx.bufs[b[1]] } };
373
+ });
374
+ pass.setBindGroup(0, dev.createBindGroup({ layout: pipe.getBindGroupLayout(0), entries }));
375
+ }
376
+ d.v.forEach((v, i) => (v[0] === 1 ? pass.setVertexBuffer(i, res(v), v[2], v[3]) : pass.setVertexBuffer(i, res(v))));
377
+ if (d.i) {
378
+ const ib = d.i.b;
379
+ if (ib[0] === 1) pass.setIndexBuffer(res(ib), d.i.wide ? "uint32" : "uint16", ib[2], ib[3]);
380
+ else pass.setIndexBuffer(res(ib), d.i.wide ? "uint32" : "uint16");
381
+ pass.drawIndexed(d.n, d.inst);
382
+ } else pass.draw(d.n, d.inst);
383
+ }
384
+ pass.end();
385
+ if (s.ctx) {
386
+ place(s);
387
+ // the frame onto the canvas (a full-screen triangle sampling it; copying between the
388
+ // two textures loses the device on some implementations)
389
+ if (!gx.blit) {
390
+ const m = dev.createShaderModule({ code: "@group(0) @binding(0) var t: texture_2d<f32>;\n@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f { let p = vec2f(f32((i << 1u) & 2u), f32(i & 2u)); return vec4f(p * 2.0 - 1.0, 0.0, 1.0); }\n@fragment fn fs(@builtin(position) q: vec4f) -> @location(0) vec4f { return textureLoad(t, vec2i(q.xy), 0); }" });
391
+ gx.blit = dev.createRenderPipeline({ layout: "auto", vertex: { module: m, entryPoint: "vs" }, fragment: { module: m, entryPoint: "fs", targets: [{ format: FMT }] } });
392
+ }
393
+ const view = s.ctx.getCurrentTexture().createView({ format: FMT });
394
+ const bp = e.beginRenderPass({ colorAttachments: [{ view, loadOp: "clear", clearValue: { r: 0, g: 0, b: 0, a: 1 }, storeOp: "store" }] });
395
+ bp.setPipeline(gx.blit);
396
+ bp.setBindGroup(0, dev.createBindGroup({ layout: gx.blit.getBindGroupLayout(0), entries: [{ binding: 0, resource: s.color.createView() }] }));
397
+ bp.draw(3);
398
+ bp.end();
399
+ }
400
+ dev.queue.submit([e.finish()]);
401
+ return 0;
402
+ },
403
+ // a canvas's frame is shown when the browser draws the page: wait for that
404
+ zyth_gfx_present: new WebAssembly.Suspending(() => new Promise((r) => (typeof requestAnimationFrame === "function" ? requestAnimationFrame(() => r()) : setTimeout(r, 16)))),
405
+ zyth_gfx_read: new WebAssembly.Suspending(async (sid, p, l) => {
406
+ const s = gx.surfaces[sid];
407
+ if (!s) { fail("unknown surface"); return 1; }
408
+ const row = Math.ceil((s.w * 4) / 256) * 256;
409
+ const st = dev.createBuffer({ size: row * s.h, usage: U.MAP_READ | U.COPY_DST });
410
+ const e = dev.createCommandEncoder();
411
+ e.copyTextureToBuffer({ texture: s.color }, { buffer: st, bytesPerRow: row, rowsPerImage: s.h }, [s.w, s.h]);
412
+ dev.queue.submit([e.finish()]);
413
+ await st.mapAsync(GPUMapMode.READ);
414
+ const src = new Uint8Array(st.getMappedRange());
415
+ const out = new Uint8Array(mem(), p, l);
416
+ for (let y = 0; y < s.h; y++) out.set(src.subarray(y * row, y * row + s.w * 4), y * s.w * 4);
417
+ st.unmap(); st.destroy();
418
+ return 0;
419
+ }),
420
+ zyth_gfx_events: (sid, p, cap) => {
421
+ const s = gx.surfaces[sid];
422
+ if (!s) return 0;
423
+ const b = new TextEncoder().encode(s.events.join("\n"));
424
+ s.events = [];
425
+ const n = Math.min(b.length, cap);
426
+ new Uint8Array(mem(), p, n).set(b.subarray(0, n));
427
+ return n;
428
+ },
429
+ zyth_gfx_close: (sid) => {
430
+ const s = gx.surfaces[sid];
431
+ if (s && s.canvas) s.canvas.remove();
432
+ gx.surfaces[sid] = null;
433
+ },
434
+ };
435
+ }
436
+
437
+ // Entry points that can reach a GPU readback must be "promising" (they return Promises).
438
+ function wrap(exports, g) {
439
+ if (!g) return exports;
440
+ const out = Object.assign({}, exports);
441
+ for (const k of ENTRY_POINTS) if (typeof exports[k] === "function") out[k] = WebAssembly.promising(exports[k]);
442
+ return out;
443
+ }
444
+
445
+ root.ZythGPU = { create, imports, wrap, ENTRY_POINTS };
446
+ })(__zythGpuRoot);
447
+
448
+ const ZythGPU = __zythGpuRoot.ZythGPU;
449
+
450
+ // Zyth runtime for npm packages, shared by every Zyth package of an app (the package
451
+ // `@biodream-llc/zyth-runtime`, built by `zyth build --target npm-runtime`). Each package registers its
452
+ // Zyth source with `library(source, { full })`; one zyth.wasm instance runs them all, so an
453
+ // app with several Zyth packages downloads the runtime once. The light zyth.wasm is used
454
+ // unless a package registered before the first call draws or loads images (`full`).
455
+ // Works in Node.js, Deno, Bun, and browsers (ES modules).
456
+
457
+ const dec = new TextDecoder();
458
+ const enc = new TextEncoder();
459
+ // WebGPU (browsers, Deno): `gpu` tensors run on it when the runtime has WebGPU and JSPI;
460
+ // otherwise, and with `configure({ gpu: false })`, on the CPU
461
+ let useGpu = true;
462
+ let started = false;
463
+
464
+ /** Options, before the first call: `{ gpu: false }` computes `gpu` tensors on the CPU. */
465
+ export function configure(opts = {}) {
466
+ if (started) throw new Error("configure() must come before the first call");
467
+ if (opts.gpu === false) useGpu = false;
468
+ }
469
+
470
+ /** Where `gpu` tensors are computed: the WebGPU adapter's name, or "cpu". */
471
+ export async function device() {
472
+ const rt = await runtime(libs.some((l) => l.full));
473
+ return rt.gpu ? rt.gpu.name || "webgpu" : "cpu";
474
+ }
475
+
476
+ export class ZythError extends Error {
477
+ constructor(e) {
478
+ super(e.message);
479
+ this.name = "ZythError";
480
+ this.code = e.code;
481
+ this.details = e.text;
482
+ }
483
+ }
484
+
485
+ /** Raised when an argument's shape, dtype, or device does not match the Zyth signature. */
486
+ export class ZythShapeError extends ZythError {
487
+ constructor(e) {
488
+ super(e);
489
+ this.name = "ZythShapeError";
490
+ }
491
+ }
492
+
493
+ /** An n-dimensional array: flat row-major `data` plus `shape`. */
494
+ export class Tensor {
495
+ constructor(data, shape, dtype) {
496
+ this.data = data;
497
+ this.shape = shape ?? [data.length];
498
+ this.dtype = dtype ?? dtypeOf(data);
499
+ const n = this.shape.reduce((a, b) => a * b, 1);
500
+ if (n !== data.length) throw new ZythShapeError({ code: "E0406", message: `data has ${data.length} elements but shape [${this.shape}] needs ${n}`, text: "" });
501
+ }
502
+ get size() {
503
+ return this.data.length;
504
+ }
505
+ toArray() {
506
+ const build = (off, dim) => {
507
+ if (dim === this.shape.length) return Number(this.data[off]);
508
+ const stride = this.shape.slice(dim + 1).reduce((a, b) => a * b, 1);
509
+ return Array.from({ length: this.shape[dim] }, (_, i) => build(off + i * stride, dim + 1));
510
+ };
511
+ return build(0, 0);
512
+ }
513
+ }
514
+
515
+ function dtypeOf(d) {
516
+ if (d instanceof Float32Array) return "f32";
517
+ if (d instanceof Float64Array) return "f64";
518
+ if (d instanceof Int32Array) return "i32";
519
+ if (typeof BigInt64Array !== "undefined" && d instanceof BigInt64Array) return "i64";
520
+ if (d instanceof Uint8Array) return "u8";
521
+ return "f32";
522
+ }
523
+
524
+ const TYPED = { f32: Float32Array, f64: Float64Array, i32: Int32Array, i64: BigInt64Array, u8: Uint8Array, bool: Uint8Array };
525
+
526
+ /** `tensor([[1, 2], [3, 4]])` or `tensor(float32Array, [2, 2])`. */
527
+ export function tensor(data, shape, dtype) {
528
+ if (ArrayBuffer.isView(data)) return new Tensor(data, shape, dtype);
529
+ const dims = [];
530
+ for (let x = data; Array.isArray(x); x = x[0]) dims.push(x.length);
531
+ const T = TYPED[dtype ?? "f32"];
532
+ return new Tensor(T.from(data.flat(Infinity), dtype === "i64" ? BigInt : undefined), shape ?? dims, dtype ?? "f32");
533
+ }
534
+
535
+ function asTensor(x) {
536
+ if (x instanceof Tensor) return x;
537
+ if (ArrayBuffer.isView(x)) return new Tensor(x);
538
+ if (x && typeof x === "object" && ArrayBuffer.isView(x.data)) return new Tensor(x.data, x.shape, x.dtype);
539
+ if (Array.isArray(x)) return tensor(x);
540
+ return null;
541
+ }
542
+
543
+ const finalizer = typeof FinalizationRegistry !== "undefined" ? new FinalizationRegistry(([lib, h]) => lib.call({ op: "free", handle: h }).catch(() => {})) : null;
544
+
545
+ // ---- encoding (wire format of zyth_interp::embed: u32 JSON length | JSON | blob)
546
+
547
+ function encodeArgs(lib, values, tensorParams) {
548
+ const parts = [];
549
+ let len = 0;
550
+ const enc1 = (v, isTensor) => {
551
+ const t = isTensor || ArrayBuffer.isView(v) || v instanceof Tensor ? asTensor(v) : null;
552
+ if (t) {
553
+ const bytes = new Uint8Array(t.data.buffer, t.data.byteOffset, t.data.byteLength);
554
+ const out = { $tensor: { dtype: t.dtype, shape: t.shape, offset: len, length: bytes.length } };
555
+ parts.push(bytes);
556
+ len += bytes.length;
557
+ return out;
558
+ }
559
+ if (v && v.__zythHandle !== undefined) {
560
+ // a model lives in the package that made it
561
+ if (v.__zythLib && v.__zythLib !== lib) throw new ZythError({ code: "E0101", message: `a ${v.model ?? "model"} from the package ${v.__zythLib.name} cannot be passed to the package ${lib.name}`, text: "" });
562
+ return { $handle: v.__zythHandle };
563
+ }
564
+ if (Array.isArray(v)) return v.map((x) => enc1(x, false));
565
+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, enc1(x, false)]));
566
+ if (v === undefined) return null;
567
+ if (typeof v === "bigint") return Number(v);
568
+ return v;
569
+ };
570
+ const json = values.map((v, i) => enc1(v, tensorParams[i]));
571
+ const blob = new Uint8Array(len);
572
+ let o = 0;
573
+ for (const p of parts) {
574
+ blob.set(p, o);
575
+ o += p.length;
576
+ }
577
+ return [json, blob];
578
+ }
579
+
580
+ function decodeValue(lib, v, blob) {
581
+ if (Array.isArray(v)) return v.map((x) => decodeValue(lib, x, blob));
582
+ if (v && typeof v === "object") {
583
+ if (v.$tensor) {
584
+ const t = v.$tensor;
585
+ const T = TYPED[t.dtype] ?? Float32Array;
586
+ const bytes = blob.slice(t.offset, t.offset + t.length);
587
+ return new Tensor(new T(bytes.buffer, 0, t.length / T.BYTES_PER_ELEMENT), t.shape, t.dtype);
588
+ }
589
+ if (v.$handle !== undefined) {
590
+ const C = lib.models.get(v.model);
591
+ if (C) return C._wrap(v.$handle);
592
+ // a model whose class is not exported (React packages hold it as a value): freed in
593
+ // WebAssembly when JavaScript lets go of it
594
+ const m = { __zythHandle: v.$handle, __zythLib: lib, model: v.model };
595
+ finalizer?.register(m, [lib, v.$handle]);
596
+ return m;
597
+ }
598
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, decodeValue(lib, x, blob)]));
599
+ }
600
+ return v;
601
+ }
602
+
603
+ // ---- runtime instances (normally one; a second, full one only when a package that draws
604
+ // registers after the light one started)
605
+
606
+ let pending = "";
607
+ function write(text) {
608
+ pending += text;
609
+ const lines = pending.split("\n");
610
+ pending = lines.pop();
611
+ for (const l of lines) console.log(l);
612
+ }
613
+
614
+ const env = {
615
+ zyth_now_ms: () => (typeof performance !== "undefined" ? performance.timeOrigin + performance.now() : Date.now()),
616
+ zyth_dom_get: () => 0,
617
+ // models.load: no on-demand files and no GPU size here (files come with the program)
618
+ zyth_gpu_mb: () => -1,
619
+ zyth_fetch_start: () => -1,
620
+ zyth_fetch_step: () => -1,
621
+ zyth_fetch_total: () => 0,
622
+ zyth_fetch_done: () => 0,
623
+ zyth_fetch_peek: () => 0,
624
+ zyth_dom_set: () => 1,
625
+ zyth_dom_listen: () => 1,
626
+ // replaced by ZythGPU's imports when WebGPU is used
627
+ zyth_gpu_available: () => 0,
628
+ zyth_gpu_alloc: () => 0,
629
+ zyth_gpu_write: () => {},
630
+ zyth_gpu_read: () => {},
631
+ zyth_gpu_copy: () => {},
632
+ zyth_gpu_clear: () => {},
633
+ zyth_gpu_kernel: () => 0,
634
+ zyth_gpu_dispatch: () => 1,
635
+ zyth_gpu_name: () => 0,
636
+ };
637
+
638
+ // Both are named here so bundlers ship both; a page downloads only the one it uses.
639
+ const WASM = { full: () => new URL("./zyth.wasm", import.meta.url), lite: () => new URL("./zyth-lite.wasm", import.meta.url) };
640
+
641
+ async function wasmBytes(url) {
642
+ const isNode = typeof process !== "undefined" && process.versions && process.versions.node && url.protocol === "file:";
643
+ if (isNode) {
644
+ // a name in a variable, so bundlers (Vite, webpack, esbuild) leave this Node-only import alone
645
+ const fsName = "node:fs/promises";
646
+ const { readFile } = await import(/* @vite-ignore */ /* webpackIgnore: true */ fsName);
647
+ return readFile(url);
648
+ }
649
+ const r = await fetch(url);
650
+ if (!r.ok) throw new Error(`cannot load ${url}: ${r.status}`);
651
+ return r.arrayBuffer();
652
+ }
653
+
654
+ class Runtime {
655
+ constructor(full) {
656
+ this.full = full;
657
+ this.ex = null;
658
+ this.gpu = null;
659
+ this.ready = this.start();
660
+ }
661
+ async start() {
662
+ started = true;
663
+ if (useGpu) this.gpu = await ZythGPU.create().catch(() => null);
664
+ let memory = null;
665
+ // ZythGPU.imports also gives the stand-ins (GPU and zyth.gfx) when there is no WebGPU
666
+ const imports = { ...env, zyth_write: (p, n) => write(dec.decode(this.bytes(p, n).slice())), ...ZythGPU.imports(this.gpu, () => memory) };
667
+ let bytes;
668
+ try {
669
+ bytes = await wasmBytes((this.full ? WASM.full : WASM.lite)());
670
+ } catch (e) {
671
+ // a runtime package built without the light zyth.wasm
672
+ if (this.full) throw e;
673
+ this.full = true;
674
+ bytes = await wasmBytes(WASM.full());
675
+ }
676
+ const { instance } = await WebAssembly.instantiate(bytes, { env: imports });
677
+ memory = instance.exports.memory;
678
+ this.ex = ZythGPU.wrap(instance.exports, this.gpu);
679
+ }
680
+ bytes(p, n) {
681
+ return new Uint8Array(this.ex.memory.buffer, p, n);
682
+ }
683
+ put(b) {
684
+ const p = this.ex.zyth_alloc(b.length);
685
+ this.bytes(p, b.length).set(b);
686
+ return p;
687
+ }
688
+ take(p) {
689
+ const n = new DataView(this.ex.memory.buffer).getUint32(p, true);
690
+ const out = this.bytes(p + 4, n).slice();
691
+ this.ex.zyth_free(p, n + 4);
692
+ return out;
693
+ }
694
+ async load(source, code) {
695
+ await this.ready;
696
+ const src = enc.encode(source);
697
+ const p = this.put(src);
698
+ let rp;
699
+ if (code && this.ex.zyth_lib_load_code) {
700
+ // checked bytecode: run without parsing (the light runtime has no parser)
701
+ const c = fromBase64(code);
702
+ const cp = this.put(c);
703
+ rp = await this.ex.zyth_lib_load_code(p, src.length, cp, c.length);
704
+ this.ex.zyth_free(cp, c.length);
705
+ } else {
706
+ rp = await this.ex.zyth_lib_load(p, src.length);
707
+ }
708
+ this.ex.zyth_free(p, src.length);
709
+ const r = JSON.parse(dec.decode(this.take(rp)));
710
+ if (!r.ok) throw new ZythError({ code: "E0001", message: "the Zyth library failed to load", text: r.text });
711
+ return r.id;
712
+ }
713
+ async call(id, msg) {
714
+ const p = this.put(msg);
715
+ // (a Promise when the GPU is used: reading GPU memory suspends the WebAssembly stack)
716
+ const resp = this.take(await this.ex.zyth_lib_call_in(id, p, msg.length));
717
+ this.ex.zyth_free(p, msg.length);
718
+ return resp;
719
+ }
720
+ }
721
+
722
+ const libs = [];
723
+ const runtimes = {};
724
+ function runtime(full) {
725
+ // the light runtime only while no package needs the full one
726
+ if (!full && runtimes.full) return runtimes.full.ready.then(() => runtimes.full);
727
+ const key = full ? "full" : "lite";
728
+ runtimes[key] ??= new Runtime(full);
729
+ return runtimes[key].ready.then(() => runtimes[key]);
730
+ }
731
+
732
+ // Calls run one after another: a call that waits (a frame waiting for the screen, GPU memory
733
+ // being read) must not be entered by another call (the library is not re-entrant).
734
+ let queue = Promise.resolve();
735
+ function serial(f) {
736
+ const r = queue.then(f);
737
+ queue = r.catch(() => {});
738
+ return r;
739
+ }
740
+
741
+ function fromBase64(s) {
742
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
743
+ const b = atob(s);
744
+ const out = new Uint8Array(b.length);
745
+ for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i);
746
+ return out;
747
+ }
748
+
749
+ class Library {
750
+ constructor(name, source, full, code) {
751
+ this.name = name;
752
+ this.source = source;
753
+ this.code = code;
754
+ this.full = full;
755
+ this.models = new Map();
756
+ this.ready = null;
757
+ }
758
+ /** Load the runtime and this package's program (done by the first call). */
759
+ load() {
760
+ // the first package to start decides for those registered by then: full if any needs it
761
+ this.ready ??= (async () => {
762
+ this.rt = await runtime(this.full || (!started && libs.some((l) => l.full)));
763
+ this.id = await serial(() => this.rt.load(this.source, this.code));
764
+ })();
765
+ return this.ready;
766
+ }
767
+ call(req, args = [], tensorParams = [], named = {}) {
768
+ return this.load().then(() => serial(() => this.callNow(req, args, tensorParams, named)));
769
+ }
770
+ async callNow(req, args, tensorParams, named) {
771
+ const [json, blob] = encodeArgs(this, args, tensorParams);
772
+ const [njson, nblob] = encodeArgs(this, Object.values(named), []);
773
+ // named tensors go after positional ones in the blob
774
+ const shift = blob.length;
775
+ const fix = (v) => {
776
+ if (Array.isArray(v)) return v.map(fix);
777
+ if (v && typeof v === "object") {
778
+ if (v.$tensor) return { $tensor: { ...v.$tensor, offset: v.$tensor.offset + shift } };
779
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, fix(x)]));
780
+ }
781
+ return v;
782
+ };
783
+ const namedObj = Object.fromEntries(Object.keys(named).map((k, i) => [k, fix(njson[i])]));
784
+ const body = enc.encode(JSON.stringify({ ...req, args: json, named: namedObj }));
785
+ const msg = new Uint8Array(4 + body.length + blob.length + nblob.length);
786
+ new DataView(msg.buffer).setUint32(0, body.length, true);
787
+ msg.set(body, 4);
788
+ msg.set(blob, 4 + body.length);
789
+ msg.set(nblob, 4 + body.length + blob.length);
790
+ const resp = await this.rt.call(this.id, msg);
791
+ const jn = new DataView(resp.buffer).getUint32(0, true);
792
+ const r = JSON.parse(dec.decode(resp.subarray(4, 4 + jn)));
793
+ if (!r.ok) throw r.error.kind === "shape" ? new ZythShapeError(r.error) : new ZythError(r.error);
794
+ return decodeValue(this, r.value, resp.subarray(4 + jn));
795
+ }
796
+ callFn(name, args, tensorParams, named) {
797
+ return this.call({ op: "call", name }, args, tensorParams, named);
798
+ }
799
+ modelClass(name, methods) {
800
+ const lib = this;
801
+ class Model {
802
+ static async create(args = {}) {
803
+ return lib.call({ op: "new", model: name }, [], [], args);
804
+ }
805
+ static _wrap(h) {
806
+ const m = Object.create(Model.prototype);
807
+ m.__zythHandle = h;
808
+ m.__zythLib = lib;
809
+ finalizer?.register(m, [lib, h], m);
810
+ return m;
811
+ }
812
+ /** Run the model (its `forward`). */
813
+ forward(...args) {
814
+ return lib.call({ op: "method", handle: this.__zythHandle, name: "forward" }, args, args.map(() => true));
815
+ }
816
+ /** Call any method of the model by its Zyth name, e.g. `m.method("param_count")`. */
817
+ method(mname, ...args) {
818
+ return lib.call({ op: "method", handle: this.__zythHandle, name: mname }, args, []);
819
+ }
820
+ /** Release the model now instead of waiting for garbage collection. */
821
+ free() {
822
+ finalizer?.unregister(this);
823
+ return lib.call({ op: "free", handle: this.__zythHandle });
824
+ }
825
+ }
826
+ for (const [js, zy, tp] of methods) {
827
+ Model.prototype[js] = function (...args) {
828
+ return lib.call({ op: "method", handle: this.__zythHandle, name: zy }, args, tp);
829
+ };
830
+ }
831
+ Object.defineProperty(Model, "name", { value: name });
832
+ this.models.set(name, Model);
833
+ return Model;
834
+ }
835
+ }
836
+
837
+ /** Register a Zyth package's program (generated code calls this when the package is imported).
838
+ * `full`: the program draws or loads images (needs the full zyth.wasm). */
839
+ export function library(source, { name = "zyth", full = false, code = null } = {}) {
840
+ const l = new Library(name, source, full, code);
841
+ libs.push(l);
842
+ return l;
843
+ }
844
+
845
+ /** Load the runtime and every registered program ahead of the first call (optional). */
846
+ export function load() {
847
+ return Promise.all(libs.map((l) => l.load())).then(() => {});
848
+ }
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@biodream-llc/zyth-runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-dev",
4
+ "description": "The Zyth runtime (zyth.wasm) shared by the npm packages Zyth builds",
5
+ "license": "Apache-2.0 OR MIT",
6
+ "author": "BioDream LLC",
7
+ "type": "module",
8
+ "main": "./index.js",
9
+ "types": "./index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./index.d.ts",
13
+ "default": "./index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "index.js",
18
+ "index.d.ts",
19
+ "zyth.wasm",
20
+ "LICENSE-APACHE",
21
+ "LICENSE-MIT",
22
+ "zyth-lite.wasm"
23
+ ],
24
+ "sideEffects": false
25
+ }
package/zyth-lite.wasm ADDED
Binary file
package/zyth.wasm ADDED
Binary file
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.