@tensor-cad/engine 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/node.js ADDED
@@ -0,0 +1,1487 @@
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ "use strict";
6
+
7
+ (() => {
8
+ const enosys = () => {
9
+ const err = new Error("not implemented");
10
+ err.code = "ENOSYS";
11
+ return err;
12
+ };
13
+
14
+ if (!globalThis.fs) {
15
+ let outputBuf = "";
16
+ globalThis.fs = {
17
+ constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
18
+ writeSync(fd, buf) {
19
+ outputBuf += decoder.decode(buf);
20
+ const nl = outputBuf.lastIndexOf("\n");
21
+ if (nl != -1) {
22
+ console.log(outputBuf.substring(0, nl));
23
+ outputBuf = outputBuf.substring(nl + 1);
24
+ }
25
+ return buf.length;
26
+ },
27
+ write(fd, buf, offset, length, position, callback) {
28
+ if (offset !== 0 || length !== buf.length || position !== null) {
29
+ callback(enosys());
30
+ return;
31
+ }
32
+ const n = this.writeSync(fd, buf);
33
+ callback(null, n);
34
+ },
35
+ chmod(path, mode, callback) { callback(enosys()); },
36
+ chown(path, uid, gid, callback) { callback(enosys()); },
37
+ close(fd, callback) { callback(enosys()); },
38
+ fchmod(fd, mode, callback) { callback(enosys()); },
39
+ fchown(fd, uid, gid, callback) { callback(enosys()); },
40
+ fstat(fd, callback) { callback(enosys()); },
41
+ fsync(fd, callback) { callback(null); },
42
+ ftruncate(fd, length, callback) { callback(enosys()); },
43
+ lchown(path, uid, gid, callback) { callback(enosys()); },
44
+ link(path, link, callback) { callback(enosys()); },
45
+ lstat(path, callback) { callback(enosys()); },
46
+ mkdir(path, perm, callback) { callback(enosys()); },
47
+ open(path, flags, mode, callback) { callback(enosys()); },
48
+ read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
49
+ readdir(path, callback) { callback(enosys()); },
50
+ readlink(path, callback) { callback(enosys()); },
51
+ rename(from, to, callback) { callback(enosys()); },
52
+ rmdir(path, callback) { callback(enosys()); },
53
+ stat(path, callback) { callback(enosys()); },
54
+ symlink(path, link, callback) { callback(enosys()); },
55
+ truncate(path, length, callback) { callback(enosys()); },
56
+ unlink(path, callback) { callback(enosys()); },
57
+ utimes(path, atime, mtime, callback) { callback(enosys()); },
58
+ };
59
+ }
60
+
61
+ if (!globalThis.process) {
62
+ globalThis.process = {
63
+ getuid() { return -1; },
64
+ getgid() { return -1; },
65
+ geteuid() { return -1; },
66
+ getegid() { return -1; },
67
+ getgroups() { throw enosys(); },
68
+ pid: -1,
69
+ ppid: -1,
70
+ umask() { throw enosys(); },
71
+ cwd() { throw enosys(); },
72
+ chdir() { throw enosys(); },
73
+ }
74
+ }
75
+
76
+ if (!globalThis.path) {
77
+ globalThis.path = {
78
+ resolve(...pathSegments) {
79
+ return pathSegments.join("/");
80
+ }
81
+ }
82
+ }
83
+
84
+ if (!globalThis.crypto) {
85
+ throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
86
+ }
87
+
88
+ if (!globalThis.performance) {
89
+ throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
90
+ }
91
+
92
+ if (!globalThis.TextEncoder) {
93
+ throw new Error("globalThis.TextEncoder is not available, polyfill required");
94
+ }
95
+
96
+ if (!globalThis.TextDecoder) {
97
+ throw new Error("globalThis.TextDecoder is not available, polyfill required");
98
+ }
99
+
100
+ const encoder = new TextEncoder("utf-8");
101
+ const decoder = new TextDecoder("utf-8");
102
+
103
+ globalThis.Go = class {
104
+ constructor() {
105
+ this.argv = ["js"];
106
+ this.env = {};
107
+ this.exit = (code) => {
108
+ if (code !== 0) {
109
+ console.warn("exit code:", code);
110
+ }
111
+ };
112
+ this._exitPromise = new Promise((resolve) => {
113
+ this._resolveExitPromise = resolve;
114
+ });
115
+ this._pendingEvent = null;
116
+ this._scheduledTimeouts = new Map();
117
+ this._nextCallbackTimeoutID = 1;
118
+
119
+ const setInt64 = (addr, v) => {
120
+ this.mem.setUint32(addr + 0, v, true);
121
+ this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
122
+ }
123
+
124
+ const setInt32 = (addr, v) => {
125
+ this.mem.setUint32(addr + 0, v, true);
126
+ }
127
+
128
+ const getInt64 = (addr) => {
129
+ const low = this.mem.getUint32(addr + 0, true);
130
+ const high = this.mem.getInt32(addr + 4, true);
131
+ return low + high * 4294967296;
132
+ }
133
+
134
+ const loadValue = (addr) => {
135
+ const f = this.mem.getFloat64(addr, true);
136
+ if (f === 0) {
137
+ return undefined;
138
+ }
139
+ if (!isNaN(f)) {
140
+ return f;
141
+ }
142
+
143
+ const id = this.mem.getUint32(addr, true);
144
+ return this._values[id];
145
+ }
146
+
147
+ const storeValue = (addr, v) => {
148
+ const nanHead = 0x7FF80000;
149
+
150
+ if (typeof v === "number" && v !== 0) {
151
+ if (isNaN(v)) {
152
+ this.mem.setUint32(addr + 4, nanHead, true);
153
+ this.mem.setUint32(addr, 0, true);
154
+ return;
155
+ }
156
+ this.mem.setFloat64(addr, v, true);
157
+ return;
158
+ }
159
+
160
+ if (v === undefined) {
161
+ this.mem.setFloat64(addr, 0, true);
162
+ return;
163
+ }
164
+
165
+ let id = this._ids.get(v);
166
+ if (id === undefined) {
167
+ id = this._idPool.pop();
168
+ if (id === undefined) {
169
+ id = this._values.length;
170
+ }
171
+ this._values[id] = v;
172
+ this._goRefCounts[id] = 0;
173
+ this._ids.set(v, id);
174
+ }
175
+ this._goRefCounts[id]++;
176
+ let typeFlag = 0;
177
+ switch (typeof v) {
178
+ case "object":
179
+ if (v !== null) {
180
+ typeFlag = 1;
181
+ }
182
+ break;
183
+ case "string":
184
+ typeFlag = 2;
185
+ break;
186
+ case "symbol":
187
+ typeFlag = 3;
188
+ break;
189
+ case "function":
190
+ typeFlag = 4;
191
+ break;
192
+ }
193
+ this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
194
+ this.mem.setUint32(addr, id, true);
195
+ }
196
+
197
+ const loadSlice = (addr) => {
198
+ const array = getInt64(addr + 0);
199
+ const len = getInt64(addr + 8);
200
+ return new Uint8Array(this._inst.exports.mem.buffer, array, len);
201
+ }
202
+
203
+ const loadSliceOfValues = (addr) => {
204
+ const array = getInt64(addr + 0);
205
+ const len = getInt64(addr + 8);
206
+ const a = new Array(len);
207
+ for (let i = 0; i < len; i++) {
208
+ a[i] = loadValue(array + i * 8);
209
+ }
210
+ return a;
211
+ }
212
+
213
+ const loadString = (addr) => {
214
+ const saddr = getInt64(addr + 0);
215
+ const len = getInt64(addr + 8);
216
+ return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
217
+ }
218
+
219
+ const testCallExport = (a, b) => {
220
+ this._inst.exports.testExport0();
221
+ return this._inst.exports.testExport(a, b);
222
+ }
223
+
224
+ const timeOrigin = Date.now() - performance.now();
225
+ this.importObject = {
226
+ _gotest: {
227
+ add: (a, b) => a + b,
228
+ callExport: testCallExport,
229
+ },
230
+ gojs: {
231
+ // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
232
+ // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
233
+ // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
234
+ // This changes the SP, thus we have to update the SP used by the imported function.
235
+
236
+ // func wasmExit(code int32)
237
+ "runtime.wasmExit": (sp) => {
238
+ sp >>>= 0;
239
+ const code = this.mem.getInt32(sp + 8, true);
240
+ this.exited = true;
241
+ delete this._inst;
242
+ delete this._values;
243
+ delete this._goRefCounts;
244
+ delete this._ids;
245
+ delete this._idPool;
246
+ this.exit(code);
247
+ },
248
+
249
+ // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
250
+ "runtime.wasmWrite": (sp) => {
251
+ sp >>>= 0;
252
+ const fd = getInt64(sp + 8);
253
+ const p = getInt64(sp + 16);
254
+ const n = this.mem.getInt32(sp + 24, true);
255
+ fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
256
+ },
257
+
258
+ // func resetMemoryDataView()
259
+ "runtime.resetMemoryDataView": (sp) => {
260
+ sp >>>= 0;
261
+ this.mem = new DataView(this._inst.exports.mem.buffer);
262
+ },
263
+
264
+ // func nanotime1() int64
265
+ "runtime.nanotime1": (sp) => {
266
+ sp >>>= 0;
267
+ setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
268
+ },
269
+
270
+ // func walltime() (sec int64, nsec int32)
271
+ "runtime.walltime": (sp) => {
272
+ sp >>>= 0;
273
+ const msec = (new Date).getTime();
274
+ setInt64(sp + 8, msec / 1000);
275
+ this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
276
+ },
277
+
278
+ // func scheduleTimeoutEvent(delay int64) int32
279
+ "runtime.scheduleTimeoutEvent": (sp) => {
280
+ sp >>>= 0;
281
+ const id = this._nextCallbackTimeoutID;
282
+ this._nextCallbackTimeoutID++;
283
+ this._scheduledTimeouts.set(id, setTimeout(
284
+ () => {
285
+ this._resume();
286
+ while (this._scheduledTimeouts.has(id)) {
287
+ // for some reason Go failed to register the timeout event, log and try again
288
+ // (temporary workaround for https://github.com/golang/go/issues/28975)
289
+ console.warn("scheduleTimeoutEvent: missed timeout event");
290
+ this._resume();
291
+ }
292
+ },
293
+ getInt64(sp + 8),
294
+ ));
295
+ this.mem.setInt32(sp + 16, id, true);
296
+ },
297
+
298
+ // func clearTimeoutEvent(id int32)
299
+ "runtime.clearTimeoutEvent": (sp) => {
300
+ sp >>>= 0;
301
+ const id = this.mem.getInt32(sp + 8, true);
302
+ clearTimeout(this._scheduledTimeouts.get(id));
303
+ this._scheduledTimeouts.delete(id);
304
+ },
305
+
306
+ // func getRandomData(r []byte)
307
+ "runtime.getRandomData": (sp) => {
308
+ sp >>>= 0;
309
+ crypto.getRandomValues(loadSlice(sp + 8));
310
+ },
311
+
312
+ // func finalizeRef(v ref)
313
+ "syscall/js.finalizeRef": (sp) => {
314
+ sp >>>= 0;
315
+ const id = this.mem.getUint32(sp + 8, true);
316
+ this._goRefCounts[id]--;
317
+ if (this._goRefCounts[id] === 0) {
318
+ const v = this._values[id];
319
+ this._values[id] = null;
320
+ this._ids.delete(v);
321
+ this._idPool.push(id);
322
+ }
323
+ },
324
+
325
+ // func stringVal(value string) ref
326
+ "syscall/js.stringVal": (sp) => {
327
+ sp >>>= 0;
328
+ storeValue(sp + 24, loadString(sp + 8));
329
+ },
330
+
331
+ // func valueGet(v ref, p string) ref
332
+ "syscall/js.valueGet": (sp) => {
333
+ sp >>>= 0;
334
+ const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
335
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
336
+ storeValue(sp + 32, result);
337
+ },
338
+
339
+ // func valueSet(v ref, p string, x ref)
340
+ "syscall/js.valueSet": (sp) => {
341
+ sp >>>= 0;
342
+ Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
343
+ },
344
+
345
+ // func valueDelete(v ref, p string)
346
+ "syscall/js.valueDelete": (sp) => {
347
+ sp >>>= 0;
348
+ Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
349
+ },
350
+
351
+ // func valueIndex(v ref, i int) ref
352
+ "syscall/js.valueIndex": (sp) => {
353
+ sp >>>= 0;
354
+ storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
355
+ },
356
+
357
+ // valueSetIndex(v ref, i int, x ref)
358
+ "syscall/js.valueSetIndex": (sp) => {
359
+ sp >>>= 0;
360
+ Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
361
+ },
362
+
363
+ // func valueCall(v ref, m string, args []ref) (ref, bool)
364
+ "syscall/js.valueCall": (sp) => {
365
+ sp >>>= 0;
366
+ try {
367
+ const v = loadValue(sp + 8);
368
+ const m = Reflect.get(v, loadString(sp + 16));
369
+ const args = loadSliceOfValues(sp + 32);
370
+ const result = Reflect.apply(m, v, args);
371
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
372
+ storeValue(sp + 56, result);
373
+ this.mem.setUint8(sp + 64, 1);
374
+ } catch (err) {
375
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
376
+ storeValue(sp + 56, err);
377
+ this.mem.setUint8(sp + 64, 0);
378
+ }
379
+ },
380
+
381
+ // func valueInvoke(v ref, args []ref) (ref, bool)
382
+ "syscall/js.valueInvoke": (sp) => {
383
+ sp >>>= 0;
384
+ try {
385
+ const v = loadValue(sp + 8);
386
+ const args = loadSliceOfValues(sp + 16);
387
+ const result = Reflect.apply(v, undefined, args);
388
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
389
+ storeValue(sp + 40, result);
390
+ this.mem.setUint8(sp + 48, 1);
391
+ } catch (err) {
392
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
393
+ storeValue(sp + 40, err);
394
+ this.mem.setUint8(sp + 48, 0);
395
+ }
396
+ },
397
+
398
+ // func valueNew(v ref, args []ref) (ref, bool)
399
+ "syscall/js.valueNew": (sp) => {
400
+ sp >>>= 0;
401
+ try {
402
+ const v = loadValue(sp + 8);
403
+ const args = loadSliceOfValues(sp + 16);
404
+ const result = Reflect.construct(v, args);
405
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
406
+ storeValue(sp + 40, result);
407
+ this.mem.setUint8(sp + 48, 1);
408
+ } catch (err) {
409
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
410
+ storeValue(sp + 40, err);
411
+ this.mem.setUint8(sp + 48, 0);
412
+ }
413
+ },
414
+
415
+ // func valueLength(v ref) int
416
+ "syscall/js.valueLength": (sp) => {
417
+ sp >>>= 0;
418
+ setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
419
+ },
420
+
421
+ // valuePrepareString(v ref) (ref, int)
422
+ "syscall/js.valuePrepareString": (sp) => {
423
+ sp >>>= 0;
424
+ const str = encoder.encode(String(loadValue(sp + 8)));
425
+ storeValue(sp + 16, str);
426
+ setInt64(sp + 24, str.length);
427
+ },
428
+
429
+ // valueLoadString(v ref, b []byte)
430
+ "syscall/js.valueLoadString": (sp) => {
431
+ sp >>>= 0;
432
+ const str = loadValue(sp + 8);
433
+ loadSlice(sp + 16).set(str);
434
+ },
435
+
436
+ // func valueInstanceOf(v ref, t ref) bool
437
+ "syscall/js.valueInstanceOf": (sp) => {
438
+ sp >>>= 0;
439
+ this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
440
+ },
441
+
442
+ // func copyBytesToGo(dst []byte, src ref) (int, bool)
443
+ "syscall/js.copyBytesToGo": (sp) => {
444
+ sp >>>= 0;
445
+ const dst = loadSlice(sp + 8);
446
+ const src = loadValue(sp + 32);
447
+ if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
448
+ this.mem.setUint8(sp + 48, 0);
449
+ return;
450
+ }
451
+ const toCopy = src.subarray(0, dst.length);
452
+ dst.set(toCopy);
453
+ setInt64(sp + 40, toCopy.length);
454
+ this.mem.setUint8(sp + 48, 1);
455
+ },
456
+
457
+ // func copyBytesToJS(dst ref, src []byte) (int, bool)
458
+ "syscall/js.copyBytesToJS": (sp) => {
459
+ sp >>>= 0;
460
+ const dst = loadValue(sp + 8);
461
+ const src = loadSlice(sp + 16);
462
+ if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
463
+ this.mem.setUint8(sp + 48, 0);
464
+ return;
465
+ }
466
+ const toCopy = src.subarray(0, dst.length);
467
+ dst.set(toCopy);
468
+ setInt64(sp + 40, toCopy.length);
469
+ this.mem.setUint8(sp + 48, 1);
470
+ },
471
+
472
+ "debug": (value) => {
473
+ console.log(value);
474
+ },
475
+ }
476
+ };
477
+ }
478
+
479
+ async run(instance) {
480
+ if (!(instance instanceof WebAssembly.Instance)) {
481
+ throw new Error("Go.run: WebAssembly.Instance expected");
482
+ }
483
+ this._inst = instance;
484
+ this.mem = new DataView(this._inst.exports.mem.buffer);
485
+ this._values = [ // JS values that Go currently has references to, indexed by reference id
486
+ NaN,
487
+ 0,
488
+ null,
489
+ true,
490
+ false,
491
+ globalThis,
492
+ this,
493
+ ];
494
+ this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
495
+ this._ids = new Map([ // mapping from JS values to reference ids
496
+ [0, 1],
497
+ [null, 2],
498
+ [true, 3],
499
+ [false, 4],
500
+ [globalThis, 5],
501
+ [this, 6],
502
+ ]);
503
+ this._idPool = []; // unused ids that have been garbage collected
504
+ this.exited = false; // whether the Go program has exited
505
+
506
+ // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
507
+ let offset = 4096;
508
+
509
+ const strPtr = (str) => {
510
+ const ptr = offset;
511
+ const bytes = encoder.encode(str + "\0");
512
+ new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
513
+ offset += bytes.length;
514
+ if (offset % 8 !== 0) {
515
+ offset += 8 - (offset % 8);
516
+ }
517
+ return ptr;
518
+ };
519
+
520
+ const argc = this.argv.length;
521
+
522
+ const argvPtrs = [];
523
+ this.argv.forEach((arg) => {
524
+ argvPtrs.push(strPtr(arg));
525
+ });
526
+ argvPtrs.push(0);
527
+
528
+ const keys = Object.keys(this.env).sort();
529
+ keys.forEach((key) => {
530
+ argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
531
+ });
532
+ argvPtrs.push(0);
533
+
534
+ const argv = offset;
535
+ argvPtrs.forEach((ptr) => {
536
+ this.mem.setUint32(offset, ptr, true);
537
+ this.mem.setUint32(offset + 4, 0, true);
538
+ offset += 8;
539
+ });
540
+
541
+ // The linker guarantees global data starts from at least wasmMinDataAddr.
542
+ // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
543
+ const wasmMinDataAddr = 4096 + 8192;
544
+ if (offset >= wasmMinDataAddr) {
545
+ throw new Error("total length of command line and environment variables exceeds limit");
546
+ }
547
+
548
+ this._inst.exports.run(argc, argv);
549
+ if (this.exited) {
550
+ this._resolveExitPromise();
551
+ }
552
+ await this._exitPromise;
553
+ }
554
+
555
+ _resume() {
556
+ if (this.exited) {
557
+ throw new Error("Go program has already exited");
558
+ }
559
+ this._inst.exports.resume();
560
+ if (this.exited) {
561
+ this._resolveExitPromise();
562
+ }
563
+ }
564
+
565
+ _makeFuncWrapper(id) {
566
+ const go = this;
567
+ return function () {
568
+ const event = { id: id, this: this, args: arguments };
569
+ go._pendingEvent = event;
570
+ go._resume();
571
+ return event.result;
572
+ };
573
+ }
574
+ }
575
+ })();
576
+
577
+ // packages/engine/src/node.ts
578
+ import { readFileSync } from "node:fs";
579
+ import { dirname, join } from "node:path";
580
+ import { fileURLToPath } from "node:url";
581
+
582
+ // packages/engine/src/catalog.ts
583
+ function fromUserBlock(type, def) {
584
+ const params = { ...def.params ?? {} };
585
+ const shapes = (side) => {
586
+ const out = {};
587
+ for (const [name, port] of Object.entries(side ?? {})) {
588
+ out[name] = typeof port === "string" ? port : port.shape;
589
+ }
590
+ return out;
591
+ };
592
+ return {
593
+ type,
594
+ kind: "composite",
595
+ category: def.category ?? "custom",
596
+ docs: {
597
+ summary: def.docs?.summary ?? "A block this design defines for itself.",
598
+ formula: def.docs?.formula,
599
+ refs: def.docs?.refs
600
+ },
601
+ params,
602
+ paramOrder: Object.keys(params),
603
+ ports: { in: shapes(def.ports?.in), out: shapes(def.ports?.out) }
604
+ };
605
+ }
606
+
607
+ class Catalog {
608
+ builtIn;
609
+ constructor(entries) {
610
+ this.builtIn = new Map(entries.map((entry) => [entry.type, entry]));
611
+ }
612
+ get builtInEntries() {
613
+ return [...this.builtIn.values()];
614
+ }
615
+ isBuiltIn(type) {
616
+ return this.builtIn.has(type);
617
+ }
618
+ get(type, doc) {
619
+ if (this.builtIn.has(type))
620
+ return this.builtIn.get(type);
621
+ const own = doc?.defs?.[type];
622
+ return own ? fromUserBlock(type, own) : undefined;
623
+ }
624
+ entries(doc) {
625
+ const out = this.builtInEntries;
626
+ for (const [type, def] of Object.entries(doc?.defs ?? {})) {
627
+ if (!this.builtIn.has(type))
628
+ out.push(fromUserBlock(type, def));
629
+ }
630
+ return out;
631
+ }
632
+ byCategory(doc) {
633
+ const out = {};
634
+ for (const entry of this.entries(doc)) {
635
+ (out[entry.category] ??= []).push(entry);
636
+ }
637
+ return out;
638
+ }
639
+ isUserBlock(doc, type) {
640
+ return Boolean(doc?.defs && type in doc.defs && !this.builtIn.has(type));
641
+ }
642
+ param(type, name, doc) {
643
+ return this.get(type, doc)?.params[name];
644
+ }
645
+ }
646
+ function isPrimitive(def) {
647
+ return def?.kind === "primitive";
648
+ }
649
+ function isComposite(def) {
650
+ return def?.kind === "composite";
651
+ }
652
+ function isContainer(def) {
653
+ return def?.kind === "container";
654
+ }
655
+
656
+ // packages/engine/src/types.ts
657
+ var DOC_VERSION = 1;
658
+ var RUNTIME_SYMBOLS = ["B", "T"];
659
+ var BOUNDARY_IN = "_in";
660
+ var BOUNDARY_OUT = "_out";
661
+ var DEFAULT_PARALLEL = {
662
+ dp: 1,
663
+ tp: 1,
664
+ pp: 1,
665
+ ep: 1,
666
+ zero: 0,
667
+ sequenceParallel: false
668
+ };
669
+ var DEFAULT_HARDWARE = "h100-sxm";
670
+ var DTYPE_BYTES = { fp32: 4, bf16: 2, fp16: 2, fp8: 1 };
671
+ // packages/engine/src/format.ts
672
+ function formatCount(n) {
673
+ const abs = Math.abs(n);
674
+ if (abs >= 1000000000000)
675
+ return `${(n / 1000000000000).toFixed(2)}T`;
676
+ if (abs >= 1e9)
677
+ return `${(n / 1e9).toFixed(2)}B`;
678
+ if (abs >= 1e6)
679
+ return `${(n / 1e6).toFixed(1)}M`;
680
+ if (abs >= 1000)
681
+ return `${(n / 1000).toFixed(1)}K`;
682
+ return String(n);
683
+ }
684
+ function formatFlops(n) {
685
+ const units = [
686
+ [1000000000000000000, "EFLOP"],
687
+ [1000000000000000, "PFLOP"],
688
+ [1000000000000, "TFLOP"],
689
+ [1e9, "GFLOP"],
690
+ [1e6, "MFLOP"],
691
+ [1000, "kFLOP"]
692
+ ];
693
+ for (const [scale, unit] of units) {
694
+ if (Math.abs(n) >= scale)
695
+ return `${(n / scale).toFixed(2)} ${unit}`;
696
+ }
697
+ return `${n.toFixed(0)} FLOP`;
698
+ }
699
+ function formatBytes(n) {
700
+ const units = [
701
+ [1024 ** 5, "PiB"],
702
+ [1024 ** 4, "TiB"],
703
+ [1024 ** 3, "GiB"],
704
+ [1024 ** 2, "MiB"],
705
+ [1024, "KiB"]
706
+ ];
707
+ for (const [scale, unit] of units) {
708
+ if (Math.abs(n) >= scale)
709
+ return `${(n / scale).toFixed(2)} ${unit}`;
710
+ }
711
+ return `${Math.round(n)} B`;
712
+ }
713
+ function formatHours(h) {
714
+ if (h < 1)
715
+ return `${(h * 60).toFixed(1)} min`;
716
+ if (h < 48)
717
+ return `${h.toFixed(1)} h`;
718
+ return `${(h / 24).toFixed(1)} days`;
719
+ }
720
+ function formatDollars(d) {
721
+ if (d >= 1e6)
722
+ return `$${(d / 1e6).toFixed(2)}M`;
723
+ if (d >= 1000)
724
+ return `$${(d / 1000).toFixed(1)}k`;
725
+ return `$${d.toFixed(2)}`;
726
+ }
727
+ // packages/engine/src/ir.ts
728
+ function splitEndpoint(endpoint) {
729
+ const i = endpoint.lastIndexOf(":");
730
+ if (i < 0)
731
+ throw new Error(`Malformed endpoint "${endpoint}", expected "node:port"`);
732
+ return { node: endpoint.slice(0, i), port: endpoint.slice(i + 1) };
733
+ }
734
+ function joinPath(prefix, id) {
735
+ return prefix ? `${prefix}/${id}` : id;
736
+ }
737
+
738
+ // packages/engine/src/index.ts
739
+ class EngineError extends Error {
740
+ constructor(message) {
741
+ super(message);
742
+ this.name = "EngineError";
743
+ }
744
+ }
745
+ function unwrap(text) {
746
+ let parsed;
747
+ try {
748
+ parsed = JSON.parse(text);
749
+ } catch {
750
+ throw new EngineError(`The engine returned something that is not JSON: ${text.slice(0, 200)}`);
751
+ }
752
+ if (parsed && typeof parsed === "object" && "error" in parsed && typeof parsed.error === "string") {
753
+ throw new EngineError(parsed.error);
754
+ }
755
+ return parsed;
756
+ }
757
+ function point(options) {
758
+ return options ? JSON.stringify(options) : "";
759
+ }
760
+ async function bytesOf(wasm) {
761
+ if (wasm && typeof wasm !== "string" && !(wasm instanceof URL))
762
+ return wasm;
763
+ const url = wasm ?? new URL("../wasm/tensorcad.wasm", import.meta.url);
764
+ const response = await fetch(url);
765
+ if (!response.ok) {
766
+ throw new EngineError(`Could not load the engine from ${String(url)}: ${response.status}`);
767
+ }
768
+ return await response.arrayBuffer();
769
+ }
770
+ async function createEngine(options = {}) {
771
+ if (typeof globalThis.Go !== "function") {
772
+ throw new EngineError('The Go WebAssembly runtime is missing. Import "@tensor-cad/engine/wasm_exec" before creating the engine.');
773
+ }
774
+ const go = new globalThis.Go;
775
+ const compiled = await WebAssembly.instantiate(await bytesOf(options.wasm), go.importObject);
776
+ const instance = "instance" in compiled ? compiled.instance : compiled;
777
+ go.run(instance);
778
+ const api = globalThis.__tensorcad;
779
+ if (!api) {
780
+ throw new EngineError("The engine started but published no API.");
781
+ }
782
+ return wrap(api);
783
+ }
784
+ function wrap(api) {
785
+ const entries = JSON.parse(api.catalog());
786
+ return {
787
+ blocks: new Catalog(entries),
788
+ version: () => unwrap(api.version()),
789
+ analyze: (doc, options) => unwrap(api.analyze(JSON.stringify(doc), point(options))),
790
+ validate: (doc, options) => unwrap(api.validate(JSON.stringify(doc), point(options))),
791
+ derive: (doc, options) => unwrap(api.derive(JSON.stringify(doc), point(options))),
792
+ infer: (doc, mode) => unwrap(api.infer(JSON.stringify(doc), mode ?? "flat")),
793
+ explain: (doc, path, options) => unwrap(api.explain(JSON.stringify(doc), path, point(options))),
794
+ explainAll: (doc, options) => unwrap(api.explainAll(JSON.stringify(doc), point(options))),
795
+ generateTorch: (doc, options) => unwrap(api.generateTorch(JSON.stringify(doc), options ? JSON.stringify(options) : "")),
796
+ scale: (doc, options) => unwrap(api.scale(JSON.stringify(doc), JSON.stringify(options))),
797
+ mup: (doc, options) => unwrap(api.mup(JSON.stringify(doc), options ? JSON.stringify(options) : "")),
798
+ plan: (doc, options, cluster) => unwrap(api.plan(JSON.stringify(doc), JSON.stringify(options ?? {}), JSON.stringify(cluster))),
799
+ diff: (a, b, options) => unwrap(api.diff(JSON.stringify(a), JSON.stringify(b), JSON.stringify(options ?? {}))),
800
+ presets: () => unwrap(api.presets()),
801
+ preset: (name) => unwrap(api.preset(name)),
802
+ importHuggingFace: (configText, name) => unwrap(api.importHf(configText, name ?? "")),
803
+ catalog: () => unwrap(api.catalog()),
804
+ rules: () => unwrap(api.rules()),
805
+ checkUserBlock: (def, name) => unwrap(api.checkUserBlock(JSON.stringify(def), name)),
806
+ hardware: () => unwrap(api.hardware())
807
+ };
808
+ }
809
+
810
+ // packages/engine/vendor/wasm_exec.js
811
+ (() => {
812
+ const enosys = () => {
813
+ const err = new Error("not implemented");
814
+ err.code = "ENOSYS";
815
+ return err;
816
+ };
817
+ if (!globalThis.fs) {
818
+ let outputBuf = "";
819
+ globalThis.fs = {
820
+ constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 },
821
+ writeSync(fd, buf) {
822
+ outputBuf += decoder.decode(buf);
823
+ const nl = outputBuf.lastIndexOf(`
824
+ `);
825
+ if (nl != -1) {
826
+ console.log(outputBuf.substring(0, nl));
827
+ outputBuf = outputBuf.substring(nl + 1);
828
+ }
829
+ return buf.length;
830
+ },
831
+ write(fd, buf, offset, length, position, callback) {
832
+ if (offset !== 0 || length !== buf.length || position !== null) {
833
+ callback(enosys());
834
+ return;
835
+ }
836
+ const n = this.writeSync(fd, buf);
837
+ callback(null, n);
838
+ },
839
+ chmod(path, mode, callback) {
840
+ callback(enosys());
841
+ },
842
+ chown(path, uid, gid, callback) {
843
+ callback(enosys());
844
+ },
845
+ close(fd, callback) {
846
+ callback(enosys());
847
+ },
848
+ fchmod(fd, mode, callback) {
849
+ callback(enosys());
850
+ },
851
+ fchown(fd, uid, gid, callback) {
852
+ callback(enosys());
853
+ },
854
+ fstat(fd, callback) {
855
+ callback(enosys());
856
+ },
857
+ fsync(fd, callback) {
858
+ callback(null);
859
+ },
860
+ ftruncate(fd, length, callback) {
861
+ callback(enosys());
862
+ },
863
+ lchown(path, uid, gid, callback) {
864
+ callback(enosys());
865
+ },
866
+ link(path, link, callback) {
867
+ callback(enosys());
868
+ },
869
+ lstat(path, callback) {
870
+ callback(enosys());
871
+ },
872
+ mkdir(path, perm, callback) {
873
+ callback(enosys());
874
+ },
875
+ open(path, flags, mode, callback) {
876
+ callback(enosys());
877
+ },
878
+ read(fd, buffer, offset, length, position, callback) {
879
+ callback(enosys());
880
+ },
881
+ readdir(path, callback) {
882
+ callback(enosys());
883
+ },
884
+ readlink(path, callback) {
885
+ callback(enosys());
886
+ },
887
+ rename(from, to, callback) {
888
+ callback(enosys());
889
+ },
890
+ rmdir(path, callback) {
891
+ callback(enosys());
892
+ },
893
+ stat(path, callback) {
894
+ callback(enosys());
895
+ },
896
+ symlink(path, link, callback) {
897
+ callback(enosys());
898
+ },
899
+ truncate(path, length, callback) {
900
+ callback(enosys());
901
+ },
902
+ unlink(path, callback) {
903
+ callback(enosys());
904
+ },
905
+ utimes(path, atime, mtime, callback) {
906
+ callback(enosys());
907
+ }
908
+ };
909
+ }
910
+ if (!globalThis.process) {
911
+ globalThis.process = {
912
+ getuid() {
913
+ return -1;
914
+ },
915
+ getgid() {
916
+ return -1;
917
+ },
918
+ geteuid() {
919
+ return -1;
920
+ },
921
+ getegid() {
922
+ return -1;
923
+ },
924
+ getgroups() {
925
+ throw enosys();
926
+ },
927
+ pid: -1,
928
+ ppid: -1,
929
+ umask() {
930
+ throw enosys();
931
+ },
932
+ cwd() {
933
+ throw enosys();
934
+ },
935
+ chdir() {
936
+ throw enosys();
937
+ }
938
+ };
939
+ }
940
+ if (!globalThis.path) {
941
+ globalThis.path = {
942
+ resolve(...pathSegments) {
943
+ return pathSegments.join("/");
944
+ }
945
+ };
946
+ }
947
+ if (!globalThis.crypto) {
948
+ throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
949
+ }
950
+ if (!globalThis.performance) {
951
+ throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
952
+ }
953
+ if (!globalThis.TextEncoder) {
954
+ throw new Error("globalThis.TextEncoder is not available, polyfill required");
955
+ }
956
+ if (!globalThis.TextDecoder) {
957
+ throw new Error("globalThis.TextDecoder is not available, polyfill required");
958
+ }
959
+ const encoder = new TextEncoder("utf-8");
960
+ const decoder = new TextDecoder("utf-8");
961
+ globalThis.Go = class {
962
+ constructor() {
963
+ this.argv = ["js"];
964
+ this.env = {};
965
+ this.exit = (code) => {
966
+ if (code !== 0) {
967
+ console.warn("exit code:", code);
968
+ }
969
+ };
970
+ this._exitPromise = new Promise((resolve) => {
971
+ this._resolveExitPromise = resolve;
972
+ });
973
+ this._pendingEvent = null;
974
+ this._scheduledTimeouts = new Map;
975
+ this._nextCallbackTimeoutID = 1;
976
+ const setInt64 = (addr, v) => {
977
+ this.mem.setUint32(addr + 0, v, true);
978
+ this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
979
+ };
980
+ const setInt32 = (addr, v) => {
981
+ this.mem.setUint32(addr + 0, v, true);
982
+ };
983
+ const getInt64 = (addr) => {
984
+ const low = this.mem.getUint32(addr + 0, true);
985
+ const high = this.mem.getInt32(addr + 4, true);
986
+ return low + high * 4294967296;
987
+ };
988
+ const loadValue = (addr) => {
989
+ const f = this.mem.getFloat64(addr, true);
990
+ if (f === 0) {
991
+ return;
992
+ }
993
+ if (!isNaN(f)) {
994
+ return f;
995
+ }
996
+ const id = this.mem.getUint32(addr, true);
997
+ return this._values[id];
998
+ };
999
+ const storeValue = (addr, v) => {
1000
+ const nanHead = 2146959360;
1001
+ if (typeof v === "number" && v !== 0) {
1002
+ if (isNaN(v)) {
1003
+ this.mem.setUint32(addr + 4, nanHead, true);
1004
+ this.mem.setUint32(addr, 0, true);
1005
+ return;
1006
+ }
1007
+ this.mem.setFloat64(addr, v, true);
1008
+ return;
1009
+ }
1010
+ if (v === undefined) {
1011
+ this.mem.setFloat64(addr, 0, true);
1012
+ return;
1013
+ }
1014
+ let id = this._ids.get(v);
1015
+ if (id === undefined) {
1016
+ id = this._idPool.pop();
1017
+ if (id === undefined) {
1018
+ id = this._values.length;
1019
+ }
1020
+ this._values[id] = v;
1021
+ this._goRefCounts[id] = 0;
1022
+ this._ids.set(v, id);
1023
+ }
1024
+ this._goRefCounts[id]++;
1025
+ let typeFlag = 0;
1026
+ switch (typeof v) {
1027
+ case "object":
1028
+ if (v !== null) {
1029
+ typeFlag = 1;
1030
+ }
1031
+ break;
1032
+ case "string":
1033
+ typeFlag = 2;
1034
+ break;
1035
+ case "symbol":
1036
+ typeFlag = 3;
1037
+ break;
1038
+ case "function":
1039
+ typeFlag = 4;
1040
+ break;
1041
+ }
1042
+ this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
1043
+ this.mem.setUint32(addr, id, true);
1044
+ };
1045
+ const loadSlice = (addr) => {
1046
+ const array = getInt64(addr + 0);
1047
+ const len = getInt64(addr + 8);
1048
+ return new Uint8Array(this._inst.exports.mem.buffer, array, len);
1049
+ };
1050
+ const loadSliceOfValues = (addr) => {
1051
+ const array = getInt64(addr + 0);
1052
+ const len = getInt64(addr + 8);
1053
+ const a = new Array(len);
1054
+ for (let i = 0;i < len; i++) {
1055
+ a[i] = loadValue(array + i * 8);
1056
+ }
1057
+ return a;
1058
+ };
1059
+ const loadString = (addr) => {
1060
+ const saddr = getInt64(addr + 0);
1061
+ const len = getInt64(addr + 8);
1062
+ return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
1063
+ };
1064
+ const testCallExport = (a, b) => {
1065
+ this._inst.exports.testExport0();
1066
+ return this._inst.exports.testExport(a, b);
1067
+ };
1068
+ const timeOrigin = Date.now() - performance.now();
1069
+ this.importObject = {
1070
+ _gotest: {
1071
+ add: (a, b) => a + b,
1072
+ callExport: testCallExport
1073
+ },
1074
+ gojs: {
1075
+ "runtime.wasmExit": (sp) => {
1076
+ sp >>>= 0;
1077
+ const code = this.mem.getInt32(sp + 8, true);
1078
+ this.exited = true;
1079
+ delete this._inst;
1080
+ delete this._values;
1081
+ delete this._goRefCounts;
1082
+ delete this._ids;
1083
+ delete this._idPool;
1084
+ this.exit(code);
1085
+ },
1086
+ "runtime.wasmWrite": (sp) => {
1087
+ sp >>>= 0;
1088
+ const fd = getInt64(sp + 8);
1089
+ const p = getInt64(sp + 16);
1090
+ const n = this.mem.getInt32(sp + 24, true);
1091
+ fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
1092
+ },
1093
+ "runtime.resetMemoryDataView": (sp) => {
1094
+ sp >>>= 0;
1095
+ this.mem = new DataView(this._inst.exports.mem.buffer);
1096
+ },
1097
+ "runtime.nanotime1": (sp) => {
1098
+ sp >>>= 0;
1099
+ setInt64(sp + 8, (timeOrigin + performance.now()) * 1e6);
1100
+ },
1101
+ "runtime.walltime": (sp) => {
1102
+ sp >>>= 0;
1103
+ const msec = new Date().getTime();
1104
+ setInt64(sp + 8, msec / 1000);
1105
+ this.mem.setInt32(sp + 16, msec % 1000 * 1e6, true);
1106
+ },
1107
+ "runtime.scheduleTimeoutEvent": (sp) => {
1108
+ sp >>>= 0;
1109
+ const id = this._nextCallbackTimeoutID;
1110
+ this._nextCallbackTimeoutID++;
1111
+ this._scheduledTimeouts.set(id, setTimeout(() => {
1112
+ this._resume();
1113
+ while (this._scheduledTimeouts.has(id)) {
1114
+ console.warn("scheduleTimeoutEvent: missed timeout event");
1115
+ this._resume();
1116
+ }
1117
+ }, getInt64(sp + 8)));
1118
+ this.mem.setInt32(sp + 16, id, true);
1119
+ },
1120
+ "runtime.clearTimeoutEvent": (sp) => {
1121
+ sp >>>= 0;
1122
+ const id = this.mem.getInt32(sp + 8, true);
1123
+ clearTimeout(this._scheduledTimeouts.get(id));
1124
+ this._scheduledTimeouts.delete(id);
1125
+ },
1126
+ "runtime.getRandomData": (sp) => {
1127
+ sp >>>= 0;
1128
+ crypto.getRandomValues(loadSlice(sp + 8));
1129
+ },
1130
+ "syscall/js.finalizeRef": (sp) => {
1131
+ sp >>>= 0;
1132
+ const id = this.mem.getUint32(sp + 8, true);
1133
+ this._goRefCounts[id]--;
1134
+ if (this._goRefCounts[id] === 0) {
1135
+ const v = this._values[id];
1136
+ this._values[id] = null;
1137
+ this._ids.delete(v);
1138
+ this._idPool.push(id);
1139
+ }
1140
+ },
1141
+ "syscall/js.stringVal": (sp) => {
1142
+ sp >>>= 0;
1143
+ storeValue(sp + 24, loadString(sp + 8));
1144
+ },
1145
+ "syscall/js.valueGet": (sp) => {
1146
+ sp >>>= 0;
1147
+ const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
1148
+ sp = this._inst.exports.getsp() >>> 0;
1149
+ storeValue(sp + 32, result);
1150
+ },
1151
+ "syscall/js.valueSet": (sp) => {
1152
+ sp >>>= 0;
1153
+ Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
1154
+ },
1155
+ "syscall/js.valueDelete": (sp) => {
1156
+ sp >>>= 0;
1157
+ Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
1158
+ },
1159
+ "syscall/js.valueIndex": (sp) => {
1160
+ sp >>>= 0;
1161
+ storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
1162
+ },
1163
+ "syscall/js.valueSetIndex": (sp) => {
1164
+ sp >>>= 0;
1165
+ Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
1166
+ },
1167
+ "syscall/js.valueCall": (sp) => {
1168
+ sp >>>= 0;
1169
+ try {
1170
+ const v = loadValue(sp + 8);
1171
+ const m = Reflect.get(v, loadString(sp + 16));
1172
+ const args = loadSliceOfValues(sp + 32);
1173
+ const result = Reflect.apply(m, v, args);
1174
+ sp = this._inst.exports.getsp() >>> 0;
1175
+ storeValue(sp + 56, result);
1176
+ this.mem.setUint8(sp + 64, 1);
1177
+ } catch (err) {
1178
+ sp = this._inst.exports.getsp() >>> 0;
1179
+ storeValue(sp + 56, err);
1180
+ this.mem.setUint8(sp + 64, 0);
1181
+ }
1182
+ },
1183
+ "syscall/js.valueInvoke": (sp) => {
1184
+ sp >>>= 0;
1185
+ try {
1186
+ const v = loadValue(sp + 8);
1187
+ const args = loadSliceOfValues(sp + 16);
1188
+ const result = Reflect.apply(v, undefined, args);
1189
+ sp = this._inst.exports.getsp() >>> 0;
1190
+ storeValue(sp + 40, result);
1191
+ this.mem.setUint8(sp + 48, 1);
1192
+ } catch (err) {
1193
+ sp = this._inst.exports.getsp() >>> 0;
1194
+ storeValue(sp + 40, err);
1195
+ this.mem.setUint8(sp + 48, 0);
1196
+ }
1197
+ },
1198
+ "syscall/js.valueNew": (sp) => {
1199
+ sp >>>= 0;
1200
+ try {
1201
+ const v = loadValue(sp + 8);
1202
+ const args = loadSliceOfValues(sp + 16);
1203
+ const result = Reflect.construct(v, args);
1204
+ sp = this._inst.exports.getsp() >>> 0;
1205
+ storeValue(sp + 40, result);
1206
+ this.mem.setUint8(sp + 48, 1);
1207
+ } catch (err) {
1208
+ sp = this._inst.exports.getsp() >>> 0;
1209
+ storeValue(sp + 40, err);
1210
+ this.mem.setUint8(sp + 48, 0);
1211
+ }
1212
+ },
1213
+ "syscall/js.valueLength": (sp) => {
1214
+ sp >>>= 0;
1215
+ setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
1216
+ },
1217
+ "syscall/js.valuePrepareString": (sp) => {
1218
+ sp >>>= 0;
1219
+ const str = encoder.encode(String(loadValue(sp + 8)));
1220
+ storeValue(sp + 16, str);
1221
+ setInt64(sp + 24, str.length);
1222
+ },
1223
+ "syscall/js.valueLoadString": (sp) => {
1224
+ sp >>>= 0;
1225
+ const str = loadValue(sp + 8);
1226
+ loadSlice(sp + 16).set(str);
1227
+ },
1228
+ "syscall/js.valueInstanceOf": (sp) => {
1229
+ sp >>>= 0;
1230
+ this.mem.setUint8(sp + 24, loadValue(sp + 8) instanceof loadValue(sp + 16) ? 1 : 0);
1231
+ },
1232
+ "syscall/js.copyBytesToGo": (sp) => {
1233
+ sp >>>= 0;
1234
+ const dst = loadSlice(sp + 8);
1235
+ const src = loadValue(sp + 32);
1236
+ if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
1237
+ this.mem.setUint8(sp + 48, 0);
1238
+ return;
1239
+ }
1240
+ const toCopy = src.subarray(0, dst.length);
1241
+ dst.set(toCopy);
1242
+ setInt64(sp + 40, toCopy.length);
1243
+ this.mem.setUint8(sp + 48, 1);
1244
+ },
1245
+ "syscall/js.copyBytesToJS": (sp) => {
1246
+ sp >>>= 0;
1247
+ const dst = loadValue(sp + 8);
1248
+ const src = loadSlice(sp + 16);
1249
+ if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
1250
+ this.mem.setUint8(sp + 48, 0);
1251
+ return;
1252
+ }
1253
+ const toCopy = src.subarray(0, dst.length);
1254
+ dst.set(toCopy);
1255
+ setInt64(sp + 40, toCopy.length);
1256
+ this.mem.setUint8(sp + 48, 1);
1257
+ },
1258
+ debug: (value) => {
1259
+ console.log(value);
1260
+ }
1261
+ }
1262
+ };
1263
+ }
1264
+ async run(instance) {
1265
+ if (!(instance instanceof WebAssembly.Instance)) {
1266
+ throw new Error("Go.run: WebAssembly.Instance expected");
1267
+ }
1268
+ this._inst = instance;
1269
+ this.mem = new DataView(this._inst.exports.mem.buffer);
1270
+ this._values = [
1271
+ NaN,
1272
+ 0,
1273
+ null,
1274
+ true,
1275
+ false,
1276
+ globalThis,
1277
+ this
1278
+ ];
1279
+ this._goRefCounts = new Array(this._values.length).fill(Infinity);
1280
+ this._ids = new Map([
1281
+ [0, 1],
1282
+ [null, 2],
1283
+ [true, 3],
1284
+ [false, 4],
1285
+ [globalThis, 5],
1286
+ [this, 6]
1287
+ ]);
1288
+ this._idPool = [];
1289
+ this.exited = false;
1290
+ let offset = 4096;
1291
+ const strPtr = (str) => {
1292
+ const ptr = offset;
1293
+ const bytes = encoder.encode(str + "\x00");
1294
+ new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
1295
+ offset += bytes.length;
1296
+ if (offset % 8 !== 0) {
1297
+ offset += 8 - offset % 8;
1298
+ }
1299
+ return ptr;
1300
+ };
1301
+ const argc = this.argv.length;
1302
+ const argvPtrs = [];
1303
+ this.argv.forEach((arg) => {
1304
+ argvPtrs.push(strPtr(arg));
1305
+ });
1306
+ argvPtrs.push(0);
1307
+ const keys = Object.keys(this.env).sort();
1308
+ keys.forEach((key) => {
1309
+ argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
1310
+ });
1311
+ argvPtrs.push(0);
1312
+ const argv = offset;
1313
+ argvPtrs.forEach((ptr) => {
1314
+ this.mem.setUint32(offset, ptr, true);
1315
+ this.mem.setUint32(offset + 4, 0, true);
1316
+ offset += 8;
1317
+ });
1318
+ const wasmMinDataAddr = 4096 + 8192;
1319
+ if (offset >= wasmMinDataAddr) {
1320
+ throw new Error("total length of command line and environment variables exceeds limit");
1321
+ }
1322
+ this._inst.exports.run(argc, argv);
1323
+ if (this.exited) {
1324
+ this._resolveExitPromise();
1325
+ }
1326
+ await this._exitPromise;
1327
+ }
1328
+ _resume() {
1329
+ if (this.exited) {
1330
+ throw new Error("Go program has already exited");
1331
+ }
1332
+ this._inst.exports.resume();
1333
+ if (this.exited) {
1334
+ this._resolveExitPromise();
1335
+ }
1336
+ }
1337
+ _makeFuncWrapper(id) {
1338
+ const go = this;
1339
+ return function() {
1340
+ const event = { id, this: this, args: arguments };
1341
+ go._pendingEvent = event;
1342
+ go._resume();
1343
+ return event.result;
1344
+ };
1345
+ }
1346
+ };
1347
+ })();
1348
+
1349
+ // packages/engine/src/node.ts
1350
+ var loaded = null;
1351
+ function modulePaths() {
1352
+ const here = dirname(fileURLToPath(import.meta.url));
1353
+ return [join(here, "tensorcad.wasm"), join(here, "..", "wasm", "tensorcad.wasm")];
1354
+ }
1355
+ async function loadEngine() {
1356
+ if (loaded)
1357
+ return loaded;
1358
+ const paths = modulePaths();
1359
+ let bytes = null;
1360
+ for (const path of paths) {
1361
+ try {
1362
+ const file = readFileSync(path);
1363
+ bytes = file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength);
1364
+ break;
1365
+ } catch {}
1366
+ }
1367
+ if (bytes === null) {
1368
+ throw new EngineError(`The analysis engine is not built (looked in ${paths.join(" and ")}). Run: bun run build:wasm`);
1369
+ }
1370
+ loaded = await createEngine({ wasm: bytes });
1371
+ PRESET_NAMES.push(...loaded.presets());
1372
+ HARDWARE.push(...loaded.hardware());
1373
+ for (const entry of loaded.blocks.builtInEntries)
1374
+ CATALOG[entry.type] = entry;
1375
+ return loaded;
1376
+ }
1377
+ function engine() {
1378
+ if (!loaded)
1379
+ throw new EngineError("The engine is not loaded yet; await loadEngine() first.");
1380
+ return loaded;
1381
+ }
1382
+ var PRESET_NAMES = [];
1383
+ var HARDWARE = [];
1384
+ var CATALOG = {};
1385
+ function analyze(doc, options) {
1386
+ return engine().analyze(doc, options);
1387
+ }
1388
+ function validate(doc, options) {
1389
+ return engine().validate(doc, options);
1390
+ }
1391
+ function derive(doc, options) {
1392
+ return engine().derive(doc, options);
1393
+ }
1394
+ function inferShapes(doc, mode = "flat") {
1395
+ return engine().infer(doc, mode);
1396
+ }
1397
+ function explain(doc, path, options) {
1398
+ return engine().explain(doc, path, options);
1399
+ }
1400
+ function explainAll(doc, options) {
1401
+ return engine().explainAll(doc, options);
1402
+ }
1403
+ function generateTorch(doc, options) {
1404
+ return engine().generateTorch(doc, options);
1405
+ }
1406
+ function scaleDesign(doc, options) {
1407
+ return engine().scale(doc, options);
1408
+ }
1409
+ function mupLadder(doc, options) {
1410
+ return engine().mup(doc, options);
1411
+ }
1412
+ function planCluster(doc, options, cluster) {
1413
+ return engine().plan(doc, options, cluster);
1414
+ }
1415
+ function diffDesigns(a, b, options) {
1416
+ return engine().diff(a, b, options);
1417
+ }
1418
+ function importHfConfig(configText, name) {
1419
+ return engine().importHuggingFace(configText, name);
1420
+ }
1421
+ function getPreset(name) {
1422
+ return engine().preset(name);
1423
+ }
1424
+ function countParams(doc) {
1425
+ return engine().analyze(doc).params;
1426
+ }
1427
+ function resolveSymbols(doc) {
1428
+ return engine().analyze(doc).symbols;
1429
+ }
1430
+ function getBlock(type, doc) {
1431
+ return engine().blocks.get(type, doc);
1432
+ }
1433
+ function catalogByCategory(doc) {
1434
+ return engine().blocks.byCategory(doc);
1435
+ }
1436
+ function hardwareById(id) {
1437
+ return HARDWARE.find((h) => h.id === id);
1438
+ }
1439
+ function peakFlops(hw, dtype) {
1440
+ return dtype === "fp8" && hw.peakFp8 > 0 ? hw.peakFp8 : hw.peakBf16;
1441
+ }
1442
+ export {
1443
+ BOUNDARY_IN,
1444
+ BOUNDARY_OUT,
1445
+ CATALOG,
1446
+ Catalog,
1447
+ DEFAULT_HARDWARE,
1448
+ DEFAULT_PARALLEL,
1449
+ DOC_VERSION,
1450
+ DTYPE_BYTES,
1451
+ EngineError,
1452
+ HARDWARE,
1453
+ PRESET_NAMES,
1454
+ RUNTIME_SYMBOLS,
1455
+ analyze,
1456
+ catalogByCategory,
1457
+ countParams,
1458
+ createEngine,
1459
+ derive,
1460
+ diffDesigns,
1461
+ engine,
1462
+ explain,
1463
+ explainAll,
1464
+ formatBytes,
1465
+ formatCount,
1466
+ formatDollars,
1467
+ formatFlops,
1468
+ formatHours,
1469
+ generateTorch,
1470
+ getBlock,
1471
+ getPreset,
1472
+ hardwareById,
1473
+ importHfConfig,
1474
+ inferShapes,
1475
+ isComposite,
1476
+ isContainer,
1477
+ isPrimitive,
1478
+ joinPath,
1479
+ loadEngine,
1480
+ mupLadder,
1481
+ peakFlops,
1482
+ planCluster,
1483
+ resolveSymbols,
1484
+ scaleDesign,
1485
+ splitEndpoint,
1486
+ validate
1487
+ };