@rkmodules/rules 0.0.50 → 0.0.51

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.
@@ -0,0 +1,2311 @@
1
+ import { create, all } from 'mathjs';
2
+ import React from 'react';
3
+ import { Handle, Position, useConnection, getSimpleBezierPath, ReactFlowProvider, useOnSelectionChange, applyNodeChanges, applyEdgeChanges, ReactFlow, Background, BackgroundVariant, Controls } from '@xyflow/react';
4
+ import { useDrop, useDrag } from 'react-dnd';
5
+ import katex from 'katex';
6
+ import classNames from 'classnames';
7
+ import rcin from 'rc-input-number';
8
+ import { create as create$1 } from 'zustand';
9
+ import { persist } from 'zustand/middleware';
10
+
11
+ /******************************************************************************
12
+ Copyright (c) Microsoft Corporation.
13
+
14
+ Permission to use, copy, modify, and/or distribute this software for any
15
+ purpose with or without fee is hereby granted.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23
+ PERFORMANCE OF THIS SOFTWARE.
24
+ ***************************************************************************** */
25
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
26
+
27
+
28
+ var __assign = function() {
29
+ __assign = Object.assign || function __assign(t) {
30
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
31
+ s = arguments[i];
32
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
33
+ }
34
+ return t;
35
+ };
36
+ return __assign.apply(this, arguments);
37
+ };
38
+
39
+ function __rest(s, e) {
40
+ var t = {};
41
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
42
+ t[p] = s[p];
43
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
44
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
45
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
46
+ t[p[i]] = s[p[i]];
47
+ }
48
+ return t;
49
+ }
50
+
51
+ function __awaiter(thisArg, _arguments, P, generator) {
52
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
53
+ return new (P || (P = Promise))(function (resolve, reject) {
54
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
55
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
56
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
57
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
58
+ });
59
+ }
60
+
61
+ function __generator(thisArg, body) {
62
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
63
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
64
+ function verb(n) { return function (v) { return step([n, v]); }; }
65
+ function step(op) {
66
+ if (f) throw new TypeError("Generator is already executing.");
67
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
68
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
69
+ if (y = 0, t) op = [op[0] & 2, t.value];
70
+ switch (op[0]) {
71
+ case 0: case 1: t = op; break;
72
+ case 4: _.label++; return { value: op[1], done: false };
73
+ case 5: _.label++; y = op[1]; op = [0]; continue;
74
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
75
+ default:
76
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
77
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
78
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
79
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
80
+ if (t[2]) _.ops.pop();
81
+ _.trys.pop(); continue;
82
+ }
83
+ op = body.call(thisArg, _);
84
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
85
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
86
+ }
87
+ }
88
+
89
+ function __values(o) {
90
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
91
+ if (m) return m.call(o);
92
+ if (o && typeof o.length === "number") return {
93
+ next: function () {
94
+ if (o && i >= o.length) o = void 0;
95
+ return { value: o && o[i++], done: !o };
96
+ }
97
+ };
98
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
99
+ }
100
+
101
+ function __read(o, n) {
102
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
103
+ if (!m) return o;
104
+ var i = m.call(o), r, ar = [], e;
105
+ try {
106
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
107
+ }
108
+ catch (error) { e = { error: error }; }
109
+ finally {
110
+ try {
111
+ if (r && !r.done && (m = i["return"])) m.call(i);
112
+ }
113
+ finally { if (e) throw e.error; }
114
+ }
115
+ return ar;
116
+ }
117
+
118
+ function __spreadArray(to, from, pack) {
119
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
120
+ if (ar || !(i in from)) {
121
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
122
+ ar[i] = from[i];
123
+ }
124
+ }
125
+ return to.concat(ar || Array.prototype.slice.call(from));
126
+ }
127
+
128
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
129
+ var e = new Error(message);
130
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
131
+ };
132
+
133
+ var DISCARD = Symbol("DISCARD");
134
+ /**
135
+ * removes the common prefix from the paths in the tree
136
+ * @param tree
137
+ * @returns
138
+ */
139
+ function simplifyTree(tree) {
140
+ var keys = Object.keys(tree);
141
+ if (keys.length <= 1)
142
+ return tree; // ✅ Don't simplify if only one path
143
+ // Parse all paths into number arrays
144
+ var parsedPaths = keys.map(function (path) { return path.split(";").map(Number); });
145
+ // Find common prefix
146
+ var prefixLength = parsedPaths[0].length;
147
+ for (var i = 1; i < parsedPaths.length; i++) {
148
+ var path = parsedPaths[i];
149
+ for (var j = 0; j < prefixLength; j++) {
150
+ if (path[j] !== parsedPaths[0][j]) {
151
+ prefixLength = j;
152
+ break;
153
+ }
154
+ }
155
+ }
156
+ var simplified = {};
157
+ for (var i = 0; i < parsedPaths.length; i++) {
158
+ var oldPath = keys[i];
159
+ var newPath = parsedPaths[i].slice(prefixLength).join(";");
160
+ simplified[newPath] = tree[oldPath];
161
+ }
162
+ return simplified;
163
+ }
164
+ /**
165
+ * Expands a tree by applying a function to each item in the tree.
166
+ * @param tree
167
+ * @param fn
168
+ * @returns
169
+ */
170
+ function expandTree(tree, fn) {
171
+ var result = {};
172
+ var _loop_1 = function (path) {
173
+ var items = tree[path];
174
+ items.forEach(function (item, i) {
175
+ var subpath = "".concat(path, ";").concat(i); // Create new sub-branch per item
176
+ var expandedItems = fn(item, path, i); // Apply function
177
+ // if (expandedItems.length > 0) {
178
+ result[subpath] = expandedItems;
179
+ // }
180
+ });
181
+ };
182
+ for (var path in tree) {
183
+ _loop_1(path);
184
+ }
185
+ return result;
186
+ }
187
+ /**
188
+ * Creates a new branch for each item in the existing tree branches
189
+ * @param tree
190
+ * @returns
191
+ */
192
+ function graftTree(tree) {
193
+ return Object.fromEntries(Object.entries(tree).reduce(function (entries, _a) {
194
+ var _b = __read(_a, 2), path = _b[0], values = _b[1];
195
+ entries.push.apply(entries, __spreadArray([], __read(values.map(function (value, index) {
196
+ return [path + ";" + index, [value]];
197
+ })), false));
198
+ return entries;
199
+ }, []));
200
+ }
201
+ /**
202
+ * Reduce the complexity of a tree by merging the outermost branches.
203
+ * @param tree
204
+ */
205
+ function trimTree(tree, depth) {
206
+ var _a;
207
+ if (depth === void 0) { depth = 1; }
208
+ if (depth <= 0)
209
+ return tree;
210
+ var result = {};
211
+ for (var path in tree) {
212
+ var parts = path.split(";");
213
+ // leave at least a path length of 1
214
+ var end = depth >= parts.length ? 1 : -depth;
215
+ var newPath = parts.slice(0, end).join(";");
216
+ if (!result[newPath]) {
217
+ result[newPath] = [];
218
+ }
219
+ // flatten onto new branch
220
+ (_a = result[newPath]).push.apply(_a, __spreadArray([], __read(tree[path]), false));
221
+ }
222
+ return result;
223
+ }
224
+ /**
225
+ * checks if the given structure is a data tree
226
+ */
227
+ function isTree(value) {
228
+ return (typeof value === "object" &&
229
+ value !== null &&
230
+ !Array.isArray(value) &&
231
+ Object.keys(value).length > 0 &&
232
+ Object.values(value).every(function (v) { return Array.isArray(v); }));
233
+ }
234
+ function isSingleTon(value) {
235
+ return (Object.keys(value).length === 1 && Object.values(value)[0].length === 1);
236
+ }
237
+ /**
238
+ * turns a value or array of values into a tree
239
+ */
240
+ function broadCast(value) {
241
+ if (Array.isArray(value)) {
242
+ return { "0": value };
243
+ }
244
+ if (isTree(value)) {
245
+ return value;
246
+ }
247
+ return { "0": [value] };
248
+ }
249
+ function getBranch(tree, path) {
250
+ return tree[path];
251
+ }
252
+ /**
253
+ * maps a tree, the tree branches are flatmapped, so if an array is returned for each item in the list, a flat list is returned
254
+ * @param tree
255
+ * @param fn
256
+ * @returns
257
+ */
258
+ function mapTree(tree, fn) {
259
+ return nAryOnTree([tree], function (_a, _b, index) {
260
+ var _c = __read(_a, 1), item = _c[0];
261
+ var _d = __read(_b, 1), path = _d[0];
262
+ return fn(item, path, index);
263
+ });
264
+ }
265
+ function mapTreeBranch(tree, fn) {
266
+ return nAryOnTreeBranch([tree], function (_a, _b) {
267
+ var _c = __read(_a, 1), branch = _c[0];
268
+ var _d = __read(_b, 1), path = _d[0];
269
+ return fn(branch, path);
270
+ });
271
+ }
272
+ /**
273
+ * n-ary operation on a tree, branch by branch
274
+ * - branches are matched by index,
275
+ * - last branches are repeated when the branch count differs
276
+ * - branch names from the longest or first tree are used
277
+ * - if a corresponding index does not exist in the branch, its item argument is undefined
278
+ * - the callback function is called with (items, paths)
279
+ * @param trees
280
+ * @param fn
281
+ * @returns
282
+ */
283
+ function nAryOnTreeBranch(trees, fn) {
284
+ var result = {};
285
+ var allKeys = trees.map(function (tree) { return Object.keys(tree); });
286
+ var maxBranches = Math.max.apply(Math, __spreadArray([], __read(allKeys.map(function (keys) { return keys.length; })), false));
287
+ var _loop_2 = function (i) {
288
+ var paths = allKeys.map(function (keys) { return keys[Math.min(i, keys.length - 1)]; });
289
+ var branches = trees.map(function (tree) { return tree[paths[trees.indexOf(tree)]] || []; });
290
+ // get all the paths of which the trees are the longest, use the first
291
+ var maxPaths = paths.filter(function (_, i) { return allKeys[i].length === maxBranches; });
292
+ var path = maxPaths[0];
293
+ var newBranch = fn(branches, paths);
294
+ if (newBranch === null || newBranch === void 0 ? void 0 : newBranch.length) {
295
+ result[path] = newBranch;
296
+ }
297
+ };
298
+ // if (!trees.every((t) => Object.keys(t).length > 0)) {
299
+ // return result;
300
+ // }
301
+ for (var i = 0; i < maxBranches; i++) {
302
+ _loop_2(i);
303
+ }
304
+ return result;
305
+ }
306
+ /**
307
+ * n-ary operation on a tree, branch by branch
308
+ * - branches are matched by index,
309
+ * - last branches are repeated when the branch count differs
310
+ * - branch names from the longest or first tree are used
311
+ * - if a corresponding index does not exist in the branch, its item argument is undefined
312
+ * - the callback function is called with (items, paths, index)
313
+ * - return DISCARD to not add the item to the branch
314
+ * @param trees
315
+ * @param fn
316
+ * @returns
317
+ */
318
+ function nAryOnTree(trees, fn, fill) {
319
+ return nAryOnTreeBranch(trees, function (branches, paths) {
320
+ var maxLength = Math.max.apply(Math, __spreadArray([], __read(branches.map(function (b) { return b.length; })), false));
321
+ if (maxLength === 0)
322
+ return; // Skip empty branches
323
+ var results = [];
324
+ var _loop_3 = function (i) {
325
+ var items = branches.map(function (b) {
326
+ if (fill) {
327
+ // repeat last item if index exceeds branch length
328
+ return b[Math.min(i, b.length - 1)];
329
+ }
330
+ return b[i];
331
+ });
332
+ var result = fn(items, paths, i);
333
+ if (result !== DISCARD) {
334
+ results = results.concat(result);
335
+ }
336
+ };
337
+ for (var i = 0; i < maxLength; i++) {
338
+ _loop_3(i);
339
+ }
340
+ return results;
341
+ });
342
+ }
343
+ /**
344
+ * binary operation on a tree, branch by branch
345
+ * - branches are matched by index,
346
+ * - last branches are repeated when the branch count differs
347
+ * - branch names from the longest or first tree are used
348
+ * - if a corresponding index does not exist in the branch, its item argument is undefined
349
+ * - the callback function is called with (itemA, itemB, pathA, pathB)
350
+ * @param treeA
351
+ * @param treeB
352
+ * @param fn
353
+ * @returns
354
+ */
355
+ function binaryOnTreeBranch(treeA, treeB, fn) {
356
+ return nAryOnTreeBranch([treeA, treeB], function (_a, _b) {
357
+ var _c = __read(_a, 2), branchA = _c[0], branchB = _c[1];
358
+ var _d = __read(_b, 2), pathA = _d[0], pathB = _d[1];
359
+ return fn(branchA, branchB, pathA, pathB);
360
+ });
361
+ }
362
+ /**
363
+ * binary operation on a tree, branch by branch
364
+ * - branches are matched by index,
365
+ * - last branches are repeated when the branch count differs
366
+ * - branch names from the longest or first tree are used
367
+ * - if a corresponding index does not exist in the branch, its item argument is undefined
368
+ * - the callback function is called with (itemA, itemB, pathA, pathB, index)
369
+ * @param treeA
370
+ * @param treeB
371
+ * @param fn
372
+ * @returns
373
+ */
374
+ function binaryOnTree(treeA, treeB, fn, fill) {
375
+ return nAryOnTree([treeA, treeB], function (_a, _b, index) {
376
+ var _c = __read(_a, 2), itemA = _c[0], itemB = _c[1];
377
+ var _d = __read(_b, 2), pathA = _d[0], pathB = _d[1];
378
+ return fn(itemA, itemB, pathA, pathB, index);
379
+ }, fill);
380
+ }
381
+ function treeSize(tree) {
382
+ return Object.keys(tree).length;
383
+ }
384
+ function sameShape(a, b) {
385
+ var sa = Object.keys(a).sort().join("|");
386
+ var sb = Object.keys(b).sort().join("|");
387
+ return sa === sb;
388
+ }
389
+ /**
390
+ * flattens the whole tree into an array
391
+ */
392
+ function toArray(a) {
393
+ return Object.values(a).flat();
394
+ }
395
+
396
+ // utilities
397
+ /**
398
+ * merges two trees by concatenating the branches with the same path
399
+ * @param a
400
+ * @param b
401
+ * @returns
402
+ */
403
+ function mergeTrees(a, b) {
404
+ var e_1, _a;
405
+ var _b;
406
+ var out = __assign({}, a);
407
+ try {
408
+ for (var _c = __values(Object.entries(b)), _d = _c.next(); !_d.done; _d = _c.next()) {
409
+ var _e = __read(_d.value, 2), k = _e[0], arr = _e[1];
410
+ out[k] = ((_b = out[k]) !== null && _b !== void 0 ? _b : []).concat(arr);
411
+ }
412
+ }
413
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
414
+ finally {
415
+ try {
416
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
417
+ }
418
+ finally { if (e_1) throw e_1.error; }
419
+ }
420
+ return out;
421
+ }
422
+
423
+ function isReference(value) {
424
+ return (typeof value === "string" &&
425
+ value.startsWith("<") &&
426
+ value.endsWith(">"));
427
+ }
428
+ function parseReference(ref) {
429
+ return ref.slice(1, -1);
430
+ }
431
+ function uid$1() {
432
+ return Math.random().toString(36).substring(2, 15);
433
+ }
434
+ function getValue$1(obj, path) {
435
+ if (!(obj && path)) {
436
+ return;
437
+ }
438
+ var parts = path.split(".");
439
+ var value = obj[parts.shift() || ""];
440
+ while (parts.length && value) {
441
+ value = value[parts.shift() || ""];
442
+ }
443
+ return value;
444
+ }
445
+ function interpolateValue(value, scope) {
446
+ if (Array.isArray(value)) {
447
+ if (!value.length)
448
+ return broadCast([]);
449
+ if (!value.every(isTree)) {
450
+ // interpolate to an array of trees
451
+ var mappedValue_1 = value.map(function (v) { return interpolateValue(v, scope); });
452
+ if (!mappedValue_1.every(isTree)) {
453
+ // this is a bit of a hack when the values were all plain values
454
+ // in that case, just return them, which will result in a single tree
455
+ return mappedValue_1;
456
+ }
457
+ // then, for each value, combine the branches with the same index
458
+ return nAryOnTreeBranch(mappedValue_1, function (branches) { return branches.flat(); });
459
+ }
460
+ else {
461
+ // combine the trees into one
462
+ var tree = value.reduce(function (acc, t) { return mergeTrees(acc, t); });
463
+ return mapTree(tree, function (v) { return interpolateValue(v, scope); });
464
+ }
465
+ }
466
+ if (isTree(value)) {
467
+ return mapTree(value, function (v) { return interpolateValue(v, scope); });
468
+ }
469
+ if (typeof value === "object" && value !== null) {
470
+ if (Object.keys(value).length === 0) {
471
+ return {};
472
+ }
473
+ // interpolate to a record of trees:
474
+ var interpolated = interpolate(value, scope);
475
+ // then, for each value, combine the branches with the same index
476
+ var keys_1 = Object.keys(interpolated);
477
+ return nAryOnTree(Object.values(interpolated), function (items) {
478
+ return Object.fromEntries(items.map(function (item, keyIndex) {
479
+ return [keys_1[keyIndex], item];
480
+ }));
481
+ });
482
+ }
483
+ if (!isReference(value)) {
484
+ return value;
485
+ }
486
+ var parts = parseReference(value).split(".");
487
+ var mappedValue = getValue$1(scope, parts.slice(0, 2).join("."));
488
+ if (parts.length > 2) {
489
+ // deep interpolate
490
+ mappedValue = mapTree(mappedValue, function (v) {
491
+ return getValue$1(v, parts.slice(2).join("."));
492
+ });
493
+ }
494
+ return mappedValue;
495
+ }
496
+ function interpolate(inputs, scope) {
497
+ return Object.fromEntries(Object.entries(inputs).map(function (_a) {
498
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
499
+ var mappedValue = interpolateValue(value, scope);
500
+ return [key, broadCast(mappedValue)];
501
+ }));
502
+ }
503
+
504
+ /**
505
+ * TODO: need rank polymorhism on the tree item sizes
506
+ */
507
+ var getValue = {
508
+ name: "getValue",
509
+ label: "Get Value",
510
+ description: "Get a value from an object at a specified path.",
511
+ inputs: {
512
+ tree: "any",
513
+ path: "string",
514
+ },
515
+ outputs: {
516
+ tree: "any",
517
+ },
518
+ // TODO: may want to do something with other values of path
519
+ impl: function (inputs, params) { return __awaiter(void 0, void 0, void 0, function () {
520
+ var paths, tree;
521
+ return __generator(this, function (_a) {
522
+ paths = toArray(inputs.path || {});
523
+ tree = mapTree(inputs.tree, function (value) {
524
+ // get the property from the object
525
+ return getValue$1(value, paths[0]);
526
+ });
527
+ return [2 /*return*/, { tree: tree }];
528
+ });
529
+ }); },
530
+ };
531
+
532
+ var log = {
533
+ name: "log",
534
+ label: "Log",
535
+ description: "Logs the input data to the console",
536
+ nodeType: "Log",
537
+ inputs: {
538
+ data: "any",
539
+ },
540
+ outputs: {
541
+ data: "any", // Return the data for potential further use
542
+ },
543
+ impl: function (input) { return __awaiter(void 0, void 0, void 0, function () {
544
+ return __generator(this, function (_a) {
545
+ console.table(input.data);
546
+ return [2 /*return*/, {
547
+ data: input.data, // Return the data for potential further use
548
+ }];
549
+ });
550
+ }); },
551
+ };
552
+
553
+ /**
554
+ * value primitive function
555
+ */
556
+ var value = {
557
+ name: "value",
558
+ label: "Value",
559
+ description: "Outputs a constant value of a specified type",
560
+ inputs: {},
561
+ params: {
562
+ value: "string",
563
+ type: {
564
+ type: "string",
565
+ default: "number",
566
+ options: ["number", "boolean", "string"],
567
+ },
568
+ },
569
+ outputs: {
570
+ value: "any",
571
+ },
572
+ impl: function (inputs, params) { return __awaiter(void 0, void 0, void 0, function () {
573
+ var value;
574
+ return __generator(this, function (_a) {
575
+ value = params.value;
576
+ switch (params.type) {
577
+ case "number":
578
+ return [2 /*return*/, { value: broadCast(Number(value)) }];
579
+ case "boolean":
580
+ return [2 /*return*/, { value: broadCast(Boolean(value)) }];
581
+ case "string":
582
+ return [2 /*return*/, { value: broadCast(String(value)) }];
583
+ default:
584
+ // return as is
585
+ return [2 /*return*/, { value: broadCast(value) }];
586
+ }
587
+ });
588
+ }); },
589
+ };
590
+
591
+ var _a$6;
592
+ var primitives$6 = (_a$6 = {},
593
+ _a$6[getValue.name] = getValue,
594
+ _a$6[log.name] = log,
595
+ _a$6[value.name] = value,
596
+ _a$6);
597
+
598
+ var add = {
599
+ name: "add",
600
+ label: "Add",
601
+ description: "Add two numbers",
602
+ inputs: {
603
+ a: { type: "number", default: 0 },
604
+ b: { type: "number", default: 0 },
605
+ },
606
+ outputs: {
607
+ sum: "number",
608
+ },
609
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
610
+ return __generator(this, function (_a) {
611
+ return [2 /*return*/, {
612
+ sum: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
613
+ return itemA + itemB;
614
+ }, true),
615
+ }];
616
+ });
617
+ }); },
618
+ };
619
+
620
+ var math$1 = create(all, {});
621
+ function evaluate(expression, scope) {
622
+ // console.log("evaluating", expression, "in", scope);
623
+ var result;
624
+ try {
625
+ result = math$1.evaluate(expression, scope);
626
+ if (typeof result.toNumber === "function") {
627
+ result = result.toNumber();
628
+ }
629
+ }
630
+ catch (e) {
631
+ console.log("Calc:", e);
632
+ console.log("Calc:", { expression: expression, scope: scope });
633
+ // todo: communicate errors
634
+ }
635
+ // console.log("result", result);
636
+ return result;
637
+ }
638
+ /**
639
+ * TODO: need rank polymorhism on the tree item sizes
640
+ */
641
+ var calc = {
642
+ name: "calc",
643
+ label: "Calc",
644
+ nodeType: "Calc",
645
+ inputs: {},
646
+ params: {
647
+ expression: "string",
648
+ },
649
+ outputs: {
650
+ result: "number",
651
+ },
652
+ impl: function (inputs, params) { return __awaiter(void 0, void 0, void 0, function () {
653
+ var expression, inputEntries, result;
654
+ return __generator(this, function (_a) {
655
+ expression = params.expression;
656
+ if (!expression)
657
+ return [2 /*return*/, {}];
658
+ inputEntries = Object.entries(inputs);
659
+ if (!inputEntries.every(function (_a, i, a) {
660
+ var _b = __read(_a, 2); _b[0]; var v = _b[1];
661
+ return sameShape(v, a[0][1]);
662
+ })) {
663
+ throw new Error("All inputs must have the same shape");
664
+ }
665
+ // if no inputs, just return the result of the expression
666
+ if (inputEntries.length === 0) {
667
+ return [2 /*return*/, { result: broadCast(evaluate(expression, {})) }];
668
+ }
669
+ result = mapTree(inputEntries[0][1], function (_, p, i) {
670
+ // create a scope for each input
671
+ var vars = {};
672
+ inputEntries.forEach(function (_a) {
673
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
674
+ vars[key] = value[p][i];
675
+ });
676
+ return evaluate(expression, vars);
677
+ });
678
+ // await new Promise((resolve) => setTimeout(resolve, 5000)); // yield to event loop
679
+ return [2 /*return*/, { result: result }];
680
+ });
681
+ }); },
682
+ };
683
+ var BUILT_INS = new Set([
684
+ // constants
685
+ "pi",
686
+ "e",
687
+ "tau",
688
+ "phi",
689
+ "Infinity",
690
+ "NaN",
691
+ "i",
692
+ "true",
693
+ "false",
694
+ "null",
695
+ // common built-in functions (skip as variables when used as callees)
696
+ "sin",
697
+ "cos",
698
+ "tan",
699
+ "asin",
700
+ "acos",
701
+ "atan",
702
+ "atan2",
703
+ "sinh",
704
+ "cosh",
705
+ "tanh",
706
+ "log",
707
+ "log10",
708
+ "ln",
709
+ "exp",
710
+ "sqrt",
711
+ "abs",
712
+ "min",
713
+ "max",
714
+ "round",
715
+ "floor",
716
+ "ceil",
717
+ "sum",
718
+ "mean",
719
+ "median",
720
+ "mode",
721
+ "std",
722
+ "var",
723
+ "pow",
724
+ "mod",
725
+ "gcd",
726
+ "lcm",
727
+ "derivative",
728
+ "integral",
729
+ "simplify",
730
+ "im",
731
+ "re",
732
+ ]);
733
+ /**
734
+ * Return a sorted list of unbound symbol names in a MathJS expression.
735
+ * @param expr The expression string, e.g. "x + y"
736
+ * @param scope Names already defined/known (e.g. from your evaluation scope)
737
+ * @param extraBound Extra names to treat as bound (e.g. UI reserved words)
738
+ */
739
+ function getUnboundSymbols(expr, scope, extraBound) {
740
+ if (scope === void 0) { scope = {}; }
741
+ if (extraBound === void 0) { extraBound = []; }
742
+ var ast;
743
+ try {
744
+ ast = math$1.parse(expr);
745
+ }
746
+ catch (_a) {
747
+ return [];
748
+ }
749
+ var bound = new Set(__spreadArray(__spreadArray([], __read(Object.keys(scope)), false), __read(extraBound), false));
750
+ var free = new Set();
751
+ var isFunctionCallee = function (node, parent) {
752
+ return (parent === null || parent === void 0 ? void 0 : parent.type) === "FunctionNode" && parent.fn === node;
753
+ };
754
+ ast.traverse(function (node, _path, parent) {
755
+ if (node.type !== "SymbolNode")
756
+ return;
757
+ var name = node.name;
758
+ // Skip if symbol is the function name in a call, e.g. sin in sin(x)
759
+ if (isFunctionCallee(node, parent))
760
+ return;
761
+ // Skip mathjs built-ins and anything caller said is already bound
762
+ if (BUILT_INS.has(name) || bound.has(name))
763
+ return;
764
+ free.add(name);
765
+ });
766
+ // If you want to also exclude left-hand sides of assignments within the expr:
767
+ // (Uncommon in "fill in variables" UIs, but easy to guard against.)
768
+ ast.traverse(function (node) {
769
+ if (node.type === "AssignmentNode") {
770
+ var target = node.object;
771
+ if ((target === null || target === void 0 ? void 0 : target.type) === "SymbolNode") {
772
+ free.delete(target.name);
773
+ }
774
+ }
775
+ });
776
+ return Array.from(free).sort();
777
+ }
778
+
779
+ var divide = {
780
+ name: "divide",
781
+ label: "Divide",
782
+ description: "Divide two numbers",
783
+ inputs: {
784
+ a: { type: "number", default: 1 },
785
+ b: { type: "number", default: 1 },
786
+ },
787
+ outputs: {
788
+ quotient: "number",
789
+ },
790
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
791
+ return __generator(this, function (_a) {
792
+ return [2 /*return*/, {
793
+ quotient: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
794
+ return itemA / itemB;
795
+ }, true),
796
+ }];
797
+ });
798
+ }); },
799
+ };
800
+
801
+ var greaterThan = {
802
+ name: "greaterThan",
803
+ label: "Greater Than",
804
+ description: "Compare on greater than or greater than or equal to",
805
+ inputs: {
806
+ a: "number",
807
+ b: "number",
808
+ },
809
+ outputs: {
810
+ gt: "boolean",
811
+ gte: "boolean",
812
+ },
813
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
814
+ return __generator(this, function (_a) {
815
+ return [2 /*return*/, {
816
+ gt: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
817
+ return itemA > itemB;
818
+ }, true),
819
+ gte: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
820
+ return itemA >= itemB;
821
+ }, true),
822
+ }];
823
+ });
824
+ }); },
825
+ };
826
+
827
+ var lessThan = {
828
+ name: "lessThan",
829
+ label: "Less Than",
830
+ description: "Compare on less than or less than or equal to",
831
+ inputs: {
832
+ a: "number",
833
+ b: "number",
834
+ },
835
+ outputs: {
836
+ lt: "boolean",
837
+ lte: "boolean",
838
+ },
839
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
840
+ return __generator(this, function (_a) {
841
+ return [2 /*return*/, {
842
+ lt: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
843
+ return itemA < itemB;
844
+ }, true),
845
+ lte: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
846
+ return itemA <= itemB;
847
+ }, true),
848
+ }];
849
+ });
850
+ }); },
851
+ };
852
+
853
+ var multiply = {
854
+ name: "multiply",
855
+ label: "Multiply",
856
+ description: "Multiply two numbers",
857
+ inputs: {
858
+ a: { type: "number", default: 1 },
859
+ b: { type: "number", default: 1 },
860
+ },
861
+ outputs: {
862
+ product: "number",
863
+ },
864
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
865
+ return __generator(this, function (_a) {
866
+ return [2 /*return*/, {
867
+ product: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
868
+ return itemA * itemB;
869
+ }, true),
870
+ }];
871
+ });
872
+ }); },
873
+ };
874
+
875
+ var subtract = {
876
+ name: "subtract",
877
+ label: "Subtract",
878
+ description: "Subtract two numbers",
879
+ inputs: {
880
+ a: { type: "number", default: 0 },
881
+ b: { type: "number", default: 0 },
882
+ },
883
+ outputs: {
884
+ difference: "number",
885
+ },
886
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
887
+ return __generator(this, function (_a) {
888
+ return [2 /*return*/, {
889
+ difference: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
890
+ return itemA - itemB;
891
+ }, true),
892
+ }];
893
+ });
894
+ }); },
895
+ };
896
+
897
+ var _a$5;
898
+ var primitives$5 = (_a$5 = {},
899
+ _a$5[calc.name] = calc,
900
+ _a$5[lessThan.name] = lessThan,
901
+ _a$5[greaterThan.name] = greaterThan,
902
+ _a$5[add.name] = add,
903
+ _a$5[subtract.name] = subtract,
904
+ _a$5[multiply.name] = multiply,
905
+ _a$5[divide.name] = divide,
906
+ _a$5);
907
+
908
+ var filterList = {
909
+ name: "filterList",
910
+ label: "Filter List",
911
+ description: "Filters the list by a boolean value",
912
+ inputs: {
913
+ list: "any",
914
+ keep: "boolean",
915
+ },
916
+ outputs: {
917
+ list: "any",
918
+ },
919
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
920
+ return __generator(this, function (_a) {
921
+ return [2 /*return*/, {
922
+ list: binaryOnTreeBranch(inputs.list || {}, inputs.keep || {}, function (branchA, branchB) {
923
+ return branchA.filter(function (item, index) {
924
+ return (branchB[Math.min(index, branchB.length - 1)] ===
925
+ true);
926
+ });
927
+ }),
928
+ }];
929
+ });
930
+ }); },
931
+ };
932
+
933
+ var splitGroup = {
934
+ name: "splitGroup",
935
+ label: "Split Group",
936
+ description: "Splits every item of a group into its own group",
937
+ inputs: {
938
+ tree: "any",
939
+ },
940
+ outputs: {
941
+ tree: "any", // Return the grafted nodes
942
+ },
943
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
944
+ return __generator(this, function (_a) {
945
+ return [2 /*return*/, {
946
+ tree: graftTree(inputs.tree || {}),
947
+ }];
948
+ });
949
+ }); },
950
+ };
951
+
952
+ var listItem = {
953
+ name: "listItem",
954
+ label: "List Item",
955
+ description: "Retrieve the items from the list at the specified indices",
956
+ inputs: {
957
+ list: "any",
958
+ index: {
959
+ type: "number",
960
+ default: 0,
961
+ },
962
+ },
963
+ outputs: {
964
+ item: "any",
965
+ },
966
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
967
+ return __generator(this, function (_a) {
968
+ return [2 /*return*/, {
969
+ // item: mapTreeBranch(inputs.list, (branch, path) => {
970
+ // let indices = getBranch(inputs.index, path);
971
+ // if (indices) {
972
+ // return indices.map((i) => branch[i]);
973
+ // }
974
+ // }),
975
+ item: binaryOnTreeBranch(inputs.list || {}, inputs.index || {}, function (branch, indices) {
976
+ if (indices) {
977
+ return indices.map(function (i) { return branch[i]; });
978
+ }
979
+ }),
980
+ }];
981
+ });
982
+ }); },
983
+ };
984
+
985
+ var listLength = {
986
+ name: "listLength",
987
+ label: "List Length",
988
+ description: "Get the length of a list",
989
+ inputs: {
990
+ list: "any",
991
+ },
992
+ outputs: {
993
+ length: "number",
994
+ },
995
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
996
+ return __generator(this, function (_a) {
997
+ return [2 /*return*/, {
998
+ length: mapTreeBranch(inputs.list || {}, function (branch) {
999
+ return [branch.length];
1000
+ }),
1001
+ }];
1002
+ });
1003
+ }); },
1004
+ };
1005
+
1006
+ var mergeGroup = {
1007
+ name: "mergeGroup",
1008
+ label: "Merge Group",
1009
+ description: "Merge the deepest groups into their parent.",
1010
+ inputs: {
1011
+ tree: "any",
1012
+ },
1013
+ params: {
1014
+ depth: { type: "number", default: 1 }, // Optional depth to trim the tree
1015
+ },
1016
+ outputs: {
1017
+ tree: "any", // Return the trimed nodes
1018
+ },
1019
+ impl: function (inputs, params) { return __awaiter(void 0, void 0, void 0, function () {
1020
+ var depth;
1021
+ var _a;
1022
+ return __generator(this, function (_b) {
1023
+ depth = (_a = params.depth) !== null && _a !== void 0 ? _a : 1;
1024
+ return [2 /*return*/, {
1025
+ tree: trimTree(inputs.tree, depth),
1026
+ }];
1027
+ });
1028
+ }); },
1029
+ };
1030
+
1031
+ var shiftList = {
1032
+ name: "shiftList",
1033
+ label: "Shift List",
1034
+ description: "Shifts the list to the left, removing the first element and adding it at the end if wrap is enabled",
1035
+ inputs: {
1036
+ list: "any",
1037
+ step: { type: "number", default: 1, step: 1 },
1038
+ wrap: "boolean",
1039
+ },
1040
+ outputs: {
1041
+ list: "any",
1042
+ },
1043
+ impl: function (inputs, params) { return __awaiter(void 0, void 0, void 0, function () {
1044
+ return __generator(this, function (_a) {
1045
+ return [2 /*return*/, {
1046
+ list: nAryOnTreeBranch([inputs.list || {}, inputs.step || {}, inputs.wrap || {}], function (_a) {
1047
+ var _b;
1048
+ var _c = __read(_a, 3), list = _c[0], step = _c[1], wrap = _c[2];
1049
+ var n = (_b = step[0]) !== null && _b !== void 0 ? _b : 1;
1050
+ if (wrap[0]) {
1051
+ n = n % (list.length || 1);
1052
+ }
1053
+ var shifted = list.slice(n);
1054
+ if (wrap[0]) {
1055
+ shifted.push.apply(shifted, __spreadArray([], __read(list.slice(0, n)), false));
1056
+ }
1057
+ return shifted;
1058
+ }),
1059
+ }];
1060
+ });
1061
+ }); },
1062
+ };
1063
+
1064
+ var _a$4;
1065
+ var primitives$4 = (_a$4 = {},
1066
+ _a$4[splitGroup.name] = splitGroup,
1067
+ _a$4[mergeGroup.name] = mergeGroup,
1068
+ _a$4[listItem.name] = listItem,
1069
+ _a$4[listLength.name] = listLength,
1070
+ _a$4[filterList.name] = filterList,
1071
+ _a$4[shiftList.name] = shiftList,
1072
+ _a$4);
1073
+
1074
+ var series = {
1075
+ name: "series",
1076
+ label: "Series",
1077
+ description: "Create a series of numbers.",
1078
+ inputs: {
1079
+ start: { type: "number", default: 0 },
1080
+ step: { type: "number", default: 1 },
1081
+ count: { type: "number", default: 10 },
1082
+ },
1083
+ outputs: {
1084
+ series: "number",
1085
+ },
1086
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
1087
+ return __generator(this, function (_a) {
1088
+ return [2 /*return*/, {
1089
+ series: nAryOnTreeBranch([
1090
+ graftTree(inputs.start),
1091
+ graftTree(inputs.step),
1092
+ graftTree(inputs.count),
1093
+ ], function (_a) {
1094
+ var _b = __read(_a, 3), _c = __read(_b[0], 1), _d = _c[0], start = _d === void 0 ? 0 : _d, _e = __read(_b[1], 1), _f = _e[0], step = _f === void 0 ? 1 : _f, _g = __read(_b[2], 1), _h = _g[0], count = _h === void 0 ? 10 : _h;
1095
+ var series = [];
1096
+ for (var i = 0; i < count; i++) {
1097
+ series.push(start + i * step);
1098
+ }
1099
+ return series;
1100
+ }),
1101
+ }];
1102
+ });
1103
+ }); },
1104
+ };
1105
+
1106
+ var _a$3;
1107
+ var primitives$3 = (_a$3 = {},
1108
+ _a$3[series.name] = series,
1109
+ _a$3);
1110
+
1111
+ var mergeTree = {
1112
+ name: "mergeTree",
1113
+ label: "Merge Tree",
1114
+ description: "Merge multiple trees into a single tree.",
1115
+ nodeType: "Merge",
1116
+ inputs: {},
1117
+ outputs: {
1118
+ result: "any",
1119
+ },
1120
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
1121
+ var result;
1122
+ return __generator(this, function (_a) {
1123
+ result = {};
1124
+ Object.values(inputs).forEach(function (input) {
1125
+ Object.entries(input).forEach(function (_a) {
1126
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
1127
+ if (!result[key]) {
1128
+ result[key] = value;
1129
+ }
1130
+ else {
1131
+ result[key] = __spreadArray(__spreadArray([], __read(result[key]), false), __read(value), false);
1132
+ }
1133
+ });
1134
+ });
1135
+ return [2 /*return*/, { result: result }];
1136
+ });
1137
+ }); },
1138
+ };
1139
+
1140
+ var _a$2;
1141
+ var primitives$2 = (_a$2 = {},
1142
+ _a$2[mergeTree.name] = mergeTree,
1143
+ _a$2);
1144
+
1145
+ var groupAnd = {
1146
+ name: "groupAnd",
1147
+ label: "Group and",
1148
+ description: "Returns true if all of the items in a group are true",
1149
+ inputs: {
1150
+ tree: "boolean",
1151
+ },
1152
+ outputs: {
1153
+ result: "boolean",
1154
+ },
1155
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
1156
+ return __generator(this, function (_a) {
1157
+ return [2 /*return*/, {
1158
+ result: mapTreeBranch(inputs.tree, function (branch) {
1159
+ return [branch.reduce(function (acc, val) { return acc && val; }, true)];
1160
+ }),
1161
+ }];
1162
+ });
1163
+ }); },
1164
+ };
1165
+
1166
+ var groupOr = {
1167
+ name: "groupOr",
1168
+ label: "Group or",
1169
+ description: "Returns true if any of the items in a group are true",
1170
+ inputs: {
1171
+ tree: "boolean",
1172
+ },
1173
+ outputs: {
1174
+ result: "boolean",
1175
+ },
1176
+ impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
1177
+ return __generator(this, function (_a) {
1178
+ return [2 /*return*/, {
1179
+ result: mapTreeBranch(inputs.tree, function (branch) {
1180
+ return [branch.reduce(function (acc, val) { return acc || val; }, false)];
1181
+ }),
1182
+ }];
1183
+ });
1184
+ }); },
1185
+ };
1186
+
1187
+ var _a$1;
1188
+ var primitives$1 = (_a$1 = {},
1189
+ _a$1[groupAnd.name] = groupAnd,
1190
+ _a$1[groupOr.name] = groupOr,
1191
+ _a$1);
1192
+
1193
+ var Lib = { Util: primitives$6, Math: primitives$5, List: primitives$4, Sequence: primitives$3, Tree: primitives$2, Logic: primitives$1 };
1194
+ var primitives = __assign(__assign(__assign(__assign(__assign(__assign({}, primitives$6), primitives$5), primitives$4), primitives$3), primitives$2), primitives$1);
1195
+
1196
+ function isPrimitive(node) {
1197
+ return node.impl !== undefined;
1198
+ }
1199
+
1200
+ function normalizeVarDef(varDef) {
1201
+ if (typeof varDef === "string") {
1202
+ return {
1203
+ type: varDef,
1204
+ };
1205
+ }
1206
+ return varDef;
1207
+ }
1208
+ function getReferences(inputs) {
1209
+ var references = [];
1210
+ Object.entries(inputs).forEach(function (_a) {
1211
+ var _b = __read(_a, 2), name = _b[0], value = _b[1];
1212
+ var values = Array.isArray(value) ? value : [value];
1213
+ values.forEach(function (value) {
1214
+ if (!isReference(value)) {
1215
+ return;
1216
+ }
1217
+ var path = parseReference(value);
1218
+ var parts = path.split(".");
1219
+ references.push({
1220
+ name: name,
1221
+ path: path,
1222
+ parts: parts,
1223
+ refNode: parts[0],
1224
+ refField: parts.slice(1).join("."),
1225
+ });
1226
+ });
1227
+ });
1228
+ return references;
1229
+ }
1230
+ function topSort(fn) {
1231
+ var ordered = [];
1232
+ var visiting = new Set();
1233
+ var done = new Set();
1234
+ var visit = function (id) {
1235
+ // if already done, return
1236
+ if (done.has(id))
1237
+ return;
1238
+ // if being visited, we have a loop
1239
+ if (visiting.has(id)) {
1240
+ throw new Error("Circular dependency detected: ".concat(id));
1241
+ }
1242
+ // mark as visiting
1243
+ visiting.add(id);
1244
+ var fnCall = fn.body[id];
1245
+ if (!fnCall) {
1246
+ console.warn("Function ".concat(id, " not found in body"), fn);
1247
+ }
1248
+ // check the inputs and visit them
1249
+ Object.values(fnCall.inputs || {}).forEach(function (input) {
1250
+ if (isReference(input)) {
1251
+ var _a = __read(parseReference(input).split("."), 1), id_1 = _a[0];
1252
+ // visit inputs
1253
+ if (id_1 !== "inputs") {
1254
+ visit(id_1);
1255
+ }
1256
+ }
1257
+ });
1258
+ // push to end of the list
1259
+ ordered.push(id);
1260
+ // finish visting
1261
+ visiting.delete(id);
1262
+ // mark as done
1263
+ done.add(id);
1264
+ };
1265
+ Object.keys(fn.body).forEach(visit);
1266
+ var orderedBody = Object.fromEntries(ordered.map(function (id) { return [id, fn.body[id]]; }));
1267
+ return __assign(__assign({}, fn), { body: orderedBody });
1268
+ }
1269
+ var Engine = /** @class */ (function () {
1270
+ function Engine(morePrimitives) {
1271
+ if (morePrimitives === void 0) { morePrimitives = {}; }
1272
+ this.listeners = {};
1273
+ this.cache = {};
1274
+ this.cacheMiss = Symbol("cacheMiss");
1275
+ this.fnIndex = __assign(__assign({}, primitives), morePrimitives);
1276
+ }
1277
+ Engine.prototype.checkCache = function (fnName, inputs) {
1278
+ if (!this.cache[fnName]) {
1279
+ return this.cacheMiss;
1280
+ }
1281
+ // TODO: need to check the interpolated inputs, as the references can be the same
1282
+ // however, the interpolation does create new objects
1283
+ return {};
1284
+ };
1285
+ Engine.prototype.runGraph = function (node, inputs, params) {
1286
+ return __awaiter(this, void 0, void 0, function () {
1287
+ var _a, body, executionId, context, startTime, _b, _c, _d, _i, name_1, fnCall, fn, inputs_1, params_1, result_1, cacheResult, startTime_1, endTime_1, result, endTime;
1288
+ return __generator(this, function (_e) {
1289
+ switch (_e.label) {
1290
+ case 0:
1291
+ _a = node.body, body = _a === void 0 ? {} : _a;
1292
+ executionId = uid$1();
1293
+ context = {
1294
+ scope: { inputs: inputs },
1295
+ timings: {},
1296
+ activations: {},
1297
+ };
1298
+ startTime = performance.now();
1299
+ _b = body;
1300
+ _c = [];
1301
+ for (_d in _b)
1302
+ _c.push(_d);
1303
+ _i = 0;
1304
+ _e.label = 1;
1305
+ case 1:
1306
+ if (!(_i < _c.length)) return [3 /*break*/, 5];
1307
+ _d = _c[_i];
1308
+ if (!(_d in _b)) return [3 /*break*/, 4];
1309
+ name_1 = _d;
1310
+ fnCall = body[name_1];
1311
+ fn = this.fnIndex[fnCall.name];
1312
+ if (!fn) {
1313
+ throw new Error("function ".concat(fnCall.name, " not found in index"));
1314
+ }
1315
+ inputs_1 = interpolate(fnCall.inputs || {}, context.scope);
1316
+ params_1 = fnCall.params || {};
1317
+ result_1 = {};
1318
+ cacheResult = this.checkCache(name_1, inputs_1);
1319
+ if (!(cacheResult !== this.cacheMiss)) return [3 /*break*/, 2];
1320
+ // use as result
1321
+ result_1 = cacheResult;
1322
+ // store the result in the scope
1323
+ context.scope[name_1] = result_1;
1324
+ return [3 /*break*/, 4];
1325
+ case 2:
1326
+ // cache miss, call the function implementation
1327
+ context.activations[name_1] = true;
1328
+ startTime_1 = performance.now();
1329
+ this.fireEvent("functionCall", {
1330
+ name: name_1,
1331
+ inputs: inputs_1,
1332
+ params: params_1,
1333
+ executionId: executionId,
1334
+ context: context,
1335
+ startTime: startTime_1,
1336
+ });
1337
+ return [4 /*yield*/, fn.impl(inputs_1, params_1)];
1338
+ case 3:
1339
+ result_1 = _e.sent();
1340
+ endTime_1 = performance.now();
1341
+ context.activations[name_1] = false;
1342
+ context.timings[name_1] = endTime_1 - startTime_1;
1343
+ // store the result in the scope
1344
+ context.scope[name_1] = result_1;
1345
+ this.fireEvent("functionResult", {
1346
+ name: name_1,
1347
+ inputs: inputs_1,
1348
+ params: params_1,
1349
+ executionId: executionId,
1350
+ context: context,
1351
+ result: result_1,
1352
+ startTime: startTime_1,
1353
+ endTime: endTime_1,
1354
+ duration: endTime_1 - startTime_1,
1355
+ });
1356
+ _e.label = 4;
1357
+ case 4:
1358
+ _i++;
1359
+ return [3 /*break*/, 1];
1360
+ case 5:
1361
+ result = interpolate(node.outputs || {}, context.scope);
1362
+ endTime = performance.now();
1363
+ // fire event
1364
+ this.fireEvent("result", {
1365
+ name: node.name,
1366
+ inputs: inputs,
1367
+ params: params,
1368
+ executionId: executionId,
1369
+ context: context,
1370
+ result: result,
1371
+ startTime: startTime,
1372
+ endTime: endTime,
1373
+ duration: endTime - startTime,
1374
+ });
1375
+ // console.log("Engine run done", result, context, endTime - startTime);
1376
+ return [2 /*return*/, result];
1377
+ }
1378
+ });
1379
+ });
1380
+ };
1381
+ /**
1382
+ * creates an function that can be evaluated by calling its implementation
1383
+ * @param node
1384
+ * @returns
1385
+ */
1386
+ Engine.prototype.build = function (node, id) {
1387
+ var _this = this;
1388
+ if (isPrimitive(node)) {
1389
+ // already a primitive
1390
+ return node;
1391
+ }
1392
+ var _a = node.body, body = _a === void 0 ? {} : _a, props = __rest(node, ["body"]);
1393
+ var primitive = __assign(__assign({}, props), { outputs: {}, mount: function (trigger) {
1394
+ // mount all the nodes
1395
+ var unsubs = [];
1396
+ Object.values(body).forEach(function (n) {
1397
+ var _a;
1398
+ var fn = _this.fnIndex[n.name];
1399
+ if (!fn) {
1400
+ console.warn("function ".concat(n.name, " not found in index"));
1401
+ return;
1402
+ }
1403
+ var unsub = (_a = fn.mount) === null || _a === void 0 ? void 0 : _a.call(fn, trigger);
1404
+ if (unsub) {
1405
+ unsubs.push(unsub);
1406
+ }
1407
+ });
1408
+ return function () {
1409
+ var e_1, _a;
1410
+ try {
1411
+ // console.log(`Unmounting function: ${node.name}`);
1412
+ // unmount all the nodes
1413
+ for (var unsubs_1 = __values(unsubs), unsubs_1_1 = unsubs_1.next(); !unsubs_1_1.done; unsubs_1_1 = unsubs_1.next()) {
1414
+ var unsub = unsubs_1_1.value;
1415
+ unsub();
1416
+ }
1417
+ }
1418
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1419
+ finally {
1420
+ try {
1421
+ if (unsubs_1_1 && !unsubs_1_1.done && (_a = unsubs_1.return)) _a.call(unsubs_1);
1422
+ }
1423
+ finally { if (e_1) throw e_1.error; }
1424
+ }
1425
+ };
1426
+ }, impl: function (inputs, params) { return __awaiter(_this, void 0, void 0, function () {
1427
+ return __generator(this, function (_a) {
1428
+ // console.log(
1429
+ // `Running function: ${node.name}`,
1430
+ // node,
1431
+ // inputs,
1432
+ // params
1433
+ // );
1434
+ return [2 /*return*/, this.runGraph(node, inputs, params)];
1435
+ });
1436
+ }); } });
1437
+ this.fnIndex[primitive.name] = primitive;
1438
+ return primitive;
1439
+ };
1440
+ Engine.prototype.mount = function (node) {
1441
+ var _this = this;
1442
+ var _a;
1443
+ return (_a = node.mount) === null || _a === void 0 ? void 0 : _a.call(node, function () {
1444
+ // console.log(`Triggering node: ${node.name}`);
1445
+ _this.run(node);
1446
+ });
1447
+ };
1448
+ Engine.prototype.subscribe = function (eventName, listener) {
1449
+ var _this = this;
1450
+ if (!this.listeners[eventName]) {
1451
+ this.listeners[eventName] = new Set();
1452
+ }
1453
+ if (!this.listeners[eventName].has(listener)) {
1454
+ this.listeners[eventName].add(listener);
1455
+ }
1456
+ return function () {
1457
+ _this.listeners[eventName].delete(listener);
1458
+ };
1459
+ };
1460
+ Engine.prototype.fireEvent = function (eventName, event) {
1461
+ var e_2, _a;
1462
+ try {
1463
+ for (var _b = __values(this.listeners[eventName] || []), _c = _b.next(); !_c.done; _c = _b.next()) {
1464
+ var listener = _c.value;
1465
+ listener(event);
1466
+ }
1467
+ }
1468
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1469
+ finally {
1470
+ try {
1471
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1472
+ }
1473
+ finally { if (e_2) throw e_2.error; }
1474
+ }
1475
+ };
1476
+ Engine.prototype.run = function (node_1) {
1477
+ return __awaiter(this, arguments, void 0, function (node, inputs) {
1478
+ var builtFn, mappedInputs, result;
1479
+ var _a;
1480
+ if (inputs === void 0) { inputs = {}; }
1481
+ return __generator(this, function (_b) {
1482
+ switch (_b.label) {
1483
+ case 0:
1484
+ if (!isPrimitive(node)) {
1485
+ builtFn = this.getFunction(node.name);
1486
+ if (!builtFn) {
1487
+ // not yet build
1488
+ builtFn = this.build(node);
1489
+ }
1490
+ return [2 /*return*/, this.run(builtFn, inputs)];
1491
+ }
1492
+ mappedInputs = interpolate(inputs, {});
1493
+ return [4 /*yield*/, ((_a = node.impl) === null || _a === void 0 ? void 0 : _a.call(node, mappedInputs, {}))];
1494
+ case 1:
1495
+ result = _b.sent();
1496
+ // console.log("Engine run complete", result);
1497
+ return [2 /*return*/, result];
1498
+ }
1499
+ });
1500
+ });
1501
+ };
1502
+ Engine.prototype.getFunction = function (name) {
1503
+ return this.fnIndex[name];
1504
+ };
1505
+ // node handlers
1506
+ Engine.prototype.applyNodeDelete = function (oldFn, nodeIds) {
1507
+ var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1508
+ nodeIds.forEach(function (id) {
1509
+ delete newFn.body[id];
1510
+ });
1511
+ // remove any references to the deleted nodes
1512
+ Object.entries(newFn.body).forEach(function (_a) {
1513
+ var _b = __read(_a, 2), id = _b[0], node = _b[1];
1514
+ Object.entries(node.inputs || {}).forEach(function (_a) {
1515
+ var _b;
1516
+ var _c = __read(_a, 2), name = _c[0], value = _c[1];
1517
+ if (isReference(value)) {
1518
+ var path = parseReference(value);
1519
+ var parts = path.split(".");
1520
+ if (nodeIds.includes(parts[0])) {
1521
+ (_b = newFn.body[id].inputs) === null || _b === void 0 ? true : delete _b[name];
1522
+ }
1523
+ }
1524
+ });
1525
+ });
1526
+ return newFn;
1527
+ };
1528
+ Engine.prototype.applyEdgeDelete = function (oldFn, fromNode, toNode, fromField, toField) {
1529
+ var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1530
+ var from = newFn.body[fromNode];
1531
+ var to = newFn.body[toNode];
1532
+ if (!from || !to) {
1533
+ console.warn("Invalid nodes for edge deletion");
1534
+ return newFn;
1535
+ }
1536
+ if (to.inputs && to.inputs[toField] === "<".concat(fromNode, ".").concat(fromField, ">")) {
1537
+ delete to.inputs[toField];
1538
+ }
1539
+ else {
1540
+ console.warn("No matching edge found to delete");
1541
+ }
1542
+ return newFn;
1543
+ };
1544
+ Engine.prototype.applyNodeAdd = function (oldFn, nodeName, callback) {
1545
+ var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1546
+ var id = uid$1();
1547
+ // ensure unique id
1548
+ while (newFn.body[id]) {
1549
+ id = uid$1();
1550
+ }
1551
+ // get inputs defaults
1552
+ var inputs = {};
1553
+ Object.entries(this.fnIndex[nodeName].inputs || {}).forEach(function (_a) {
1554
+ var _b = __read(_a, 2), key = _b[0], def = _b[1];
1555
+ var normDef = normalizeVarDef(def);
1556
+ if (normDef.default !== undefined) {
1557
+ inputs[key] = normDef.default;
1558
+ }
1559
+ });
1560
+ // get params defaults
1561
+ var params = {};
1562
+ Object.entries(this.fnIndex[nodeName].params || {}).forEach(function (_a) {
1563
+ var _b = __read(_a, 2), key = _b[0], def = _b[1];
1564
+ var normDef = normalizeVarDef(def);
1565
+ if (normDef.default !== undefined) {
1566
+ params[key] = normDef.default;
1567
+ }
1568
+ });
1569
+ var newCall = {
1570
+ name: nodeName,
1571
+ inputs: inputs,
1572
+ params: params,
1573
+ };
1574
+ newFn.body[id] = newCall;
1575
+ callback === null || callback === void 0 ? void 0 : callback(newCall, id);
1576
+ return topSort(newFn);
1577
+ };
1578
+ Engine.prototype.applyNodeConnect = function (oldFn, fromNode, toNode, fromField, toField) {
1579
+ var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1580
+ var from = newFn.body[fromNode];
1581
+ var to = __assign({}, newFn.body[toNode]);
1582
+ if (!from || !to) {
1583
+ console.warn("Invalid nodes for connection");
1584
+ return newFn;
1585
+ }
1586
+ if (!to.inputs) {
1587
+ to.inputs = {};
1588
+ }
1589
+ // add the reference
1590
+ to.inputs[toField] = "<".concat(fromNode, ".").concat(fromField, ">");
1591
+ newFn.body[toNode] = to;
1592
+ return topSort(newFn);
1593
+ };
1594
+ return Engine;
1595
+ }());
1596
+
1597
+ var dummyEngine = new Engine();
1598
+ var FlowContext = React.createContext({
1599
+ engine: dummyEngine,
1600
+ });
1601
+ var useEngine = function () {
1602
+ return React.useContext(FlowContext).engine;
1603
+ };
1604
+ var useControls = function () {
1605
+ return React.useContext(FlowContext).controls || {};
1606
+ };
1607
+
1608
+ var _a;
1609
+ // normalizing import
1610
+ var InputNumber = (_a = rcin.default) !== null && _a !== void 0 ? _a : rcin;
1611
+ function Control(_a) {
1612
+ var value = _a.value, vardef = _a.vardef, onChange = _a.onChange;
1613
+ var customControls = useControls();
1614
+ if (vardef.type in customControls) {
1615
+ var ControlComponent = customControls[vardef.type];
1616
+ return (React.createElement(ControlComponent, { value: value, vardef: vardef, onChange: onChange }));
1617
+ }
1618
+ if (vardef.options) {
1619
+ return (React.createElement("select", { value: value || "", onChange: function (e) { return onChange === null || onChange === void 0 ? void 0 : onChange(e.target.value); } }, vardef.options.map(function (option) { return (React.createElement("option", { key: option, value: option }, option)); })));
1620
+ }
1621
+ switch (vardef.type) {
1622
+ case "string":
1623
+ return (React.createElement("input", { type: "text", value: value !== null && value !== void 0 ? value : "", onChange: function (e) { return onChange === null || onChange === void 0 ? void 0 : onChange(e.target.value); } }));
1624
+ case "number":
1625
+ return (React.createElement(InputNumber, { value: Number(value) || 0, onChange: onChange, step: vardef.step, min: vardef.min, max: vardef.max, inputMode: "numeric" }));
1626
+ case "boolean":
1627
+ return (React.createElement("input", { type: "checkbox", checked: Boolean(value), onChange: function (e) { return onChange === null || onChange === void 0 ? void 0 : onChange(e.target.checked); } }));
1628
+ default:
1629
+ return (React.createElement("span", null,
1630
+ String(value),
1631
+ " (",
1632
+ vardef.type,
1633
+ ")"));
1634
+ }
1635
+ }
1636
+
1637
+ var styles$1 = {"Port":"Port_XWl7K","required":"required_ofB6J","Icon":"Icon_YJDC5","Input":"Input_PHp3D","Output":"Output_FMRNv","ConnectionPath":"ConnectionPath_XkXr1","valid":"valid_LGNvc","Edge":"Edge_aNtpH","Hover":"Hover_1v8QT"};
1638
+
1639
+ var Input = function (_a) {
1640
+ var _b;
1641
+ var name = _a.name, varDef = _a.varDef, id = _a.id, data = _a.data, onClick = _a.onClick;
1642
+ var normalized = normalizeVarDef(varDef);
1643
+ var value = (_b = data.inputs) === null || _b === void 0 ? void 0 : _b[name];
1644
+ var isRef = isReference(value);
1645
+ var handleInputChange = function (param) { return function (value) {
1646
+ var _a;
1647
+ data.onChange({
1648
+ inputs: __assign(__assign({}, data.inputs), (_a = {}, _a[param] = value, _a)),
1649
+ });
1650
+ }; };
1651
+ return (React.createElement(Handle, { type: "target", position: Position.Left, id: "".concat(id, "-").concat(name), className: classNames(styles$1.Input, styles$1.Port, styles$1["type-".concat(normalized.type)]), style: {
1652
+ "--type-color": "var(--color-".concat(normalized.type, ")"),
1653
+ }, onClick: onClick },
1654
+ normalized.label || name,
1655
+ !isRef && (React.createElement(Control, { vardef: normalized, value: value, onChange: handleInputChange(name) }))));
1656
+ };
1657
+
1658
+ var Param = function (_a) {
1659
+ var _b;
1660
+ _a.id; var name = _a.name, varDef = _a.varDef, data = _a.data, onClick = _a.onClick;
1661
+ var normalized = normalizeVarDef(varDef);
1662
+ var value = (_b = data.params) === null || _b === void 0 ? void 0 : _b[name];
1663
+ var isRef = isReference(value);
1664
+ var handleParamChange = function (param) { return function (value) {
1665
+ var _a;
1666
+ data.onChange({
1667
+ params: __assign(__assign({}, data.params), (_a = {}, _a[param] = value, _a)),
1668
+ });
1669
+ }; };
1670
+ return (React.createElement("div", { className: classNames(styles$1.Input, styles$1.Port, styles$1["type-".concat(normalized.type)]), style: {
1671
+ "--type-color": "var(--color-".concat(normalized.type, ")"),
1672
+ }, onClick: onClick },
1673
+ React.createElement("span", null, normalized.label || name),
1674
+ !isRef && (React.createElement(Control, { vardef: normalized, value: value, onChange: handleParamChange(name) }))));
1675
+ };
1676
+
1677
+ var Output = function (_a) {
1678
+ var name = _a.name, varDef = _a.varDef, id = _a.id, onClick = _a.onClick, focus = _a.focus;
1679
+ var normalized = normalizeVarDef(varDef);
1680
+ return (React.createElement(Handle, { type: "source", position: Position.Right, id: "".concat(id, "-").concat(name), className: classNames(styles$1.Output, styles$1.Port, styles$1["type-".concat(normalized.type)]), style: {
1681
+ "--type-color": "var(--color-".concat(normalized.type, ")"),
1682
+ }, onClick: onClick },
1683
+ React.createElement("span", null,
1684
+ focus && "👁 ",
1685
+ normalized.label || name)));
1686
+ };
1687
+
1688
+ var styles = {"DefaultNode":"DefaultNode_R2P6c","selected":"selected_VmB-F","active":"active_zjUzx","Log":"Log_dsq5e","Label":"Label_wBwWA","Description":"Description_f9s4l","PreviewHead":"PreviewHead_oFT4K","expanded":"expanded_3vnbi","Preview":"Preview_HbkZ6","Duration":"Duration_0jqWx","GroupHead":"GroupHead_QJhST","GroupChildren":"GroupChildren_NKx-B","GroupLeaf":"GroupLeaf_eliT8"};
1689
+
1690
+ function NodeContainer(_a) {
1691
+ var _b;
1692
+ var id = _a.id, label = _a.label, className = _a.className, selected = _a.selected, children = _a.children;
1693
+ var engine = useEngine();
1694
+ var _c = __read(React.useState(false), 2), active = _c[0], setActive = _c[1];
1695
+ React.useEffect(function () {
1696
+ if (!id)
1697
+ return;
1698
+ var timer;
1699
+ var removeOnCall = engine.subscribe("functionCall", function (event) {
1700
+ if (event.name === id) {
1701
+ setActive(true);
1702
+ }
1703
+ });
1704
+ var removeOnResult = engine.subscribe("functionResult", function (event) {
1705
+ if (event.name === id) {
1706
+ clearTimeout(timer);
1707
+ timer = setTimeout(function () { return setActive(false); }, Math.max(0, 1000 - (event.duration || 0)));
1708
+ }
1709
+ });
1710
+ return function () {
1711
+ removeOnCall();
1712
+ removeOnResult();
1713
+ };
1714
+ }, [id]);
1715
+ return (React.createElement("div", { className: classNames(className, styles.DefaultNode, (_b = {},
1716
+ _b[styles.selected] = selected,
1717
+ _b[styles.active] = active,
1718
+ _b)) },
1719
+ React.createElement("div", { className: styles.Label }, label),
1720
+ children));
1721
+ }
1722
+
1723
+ function createTreeStructure(tree) {
1724
+ var keys = Object.keys(tree);
1725
+ var structure = [];
1726
+ keys.forEach(function (key) {
1727
+ var path = key.split(";");
1728
+ var parent = structure;
1729
+ for (var i = 0; i < path.length; i++) {
1730
+ var part = parseInt(path[i], 10);
1731
+ if (!parent[part]) {
1732
+ parent[part] = [];
1733
+ }
1734
+ parent = parent[part];
1735
+ }
1736
+ parent.push({ items: tree[key] });
1737
+ });
1738
+ return structure;
1739
+ }
1740
+ function TreeBranchView(_a) {
1741
+ var branch = _a.branch, name = _a.name;
1742
+ return (React.createElement("div", null,
1743
+ React.createElement("div", { className: styles.GroupHead },
1744
+ React.createElement("span", null,
1745
+ "group ",
1746
+ name)),
1747
+ React.createElement("div", { className: styles.GroupChildren }, branch.map(function (item, index) {
1748
+ // sub branch
1749
+ if (Array.isArray(item)) {
1750
+ return (React.createElement(TreeBranchView, { key: index, branch: item, name: "".concat(name, ";").concat(index) }));
1751
+ }
1752
+ // items
1753
+ return (React.createElement("div", { key: index }, item.items.map(function (it, i) {
1754
+ var _a;
1755
+ var label = (_a = it === null || it === void 0 ? void 0 : it.toString) === null || _a === void 0 ? void 0 : _a.call(it);
1756
+ if (label === "[object Object]") {
1757
+ label = "{...}";
1758
+ }
1759
+ return (React.createElement("div", { key: i, className: styles.GroupLeaf, title: JSON.stringify(it, null, 2) }, label));
1760
+ })));
1761
+ }))));
1762
+ }
1763
+ function TreeView(_a) {
1764
+ var value = _a.value;
1765
+ var structure = createTreeStructure(value || {});
1766
+ return (React.createElement("div", null, structure.map(function (branch, index) { return (React.createElement(TreeBranchView, { key: index, branch: branch, name: index })); })));
1767
+ }
1768
+ var Log = React.memo(function (_a) {
1769
+ var id = _a.id, data = _a.data, selected = _a.selected;
1770
+ var engine = useEngine();
1771
+ var _b = __read(React.useState(null), 2), value = _b[0], setValue = _b[1];
1772
+ React.useEffect(function () {
1773
+ return engine.subscribe("functionResult", function (event) {
1774
+ var _a;
1775
+ if (event.name === id) {
1776
+ setValue(((_a = event.context.scope[id]) === null || _a === void 0 ? void 0 : _a.data) || null);
1777
+ }
1778
+ });
1779
+ }, []);
1780
+ return (React.createElement(NodeContainer, { id: id, label: data.name, selected: selected, className: styles.Log },
1781
+ React.createElement(TreeView, { value: value }),
1782
+ React.createElement(Handle, { type: "target", position: Position.Left, id: "".concat(id, "-data") }),
1783
+ React.createElement(Handle, { type: "source", position: Position.Right, id: "".concat(id, "-data") })));
1784
+ });
1785
+ Log.displayName = "LogNode";
1786
+
1787
+ function GenericNode(_a) {
1788
+ var _b;
1789
+ var _c;
1790
+ var id = _a.id, data = _a.data, selected = _a.selected, inputs = _a.inputs, outputs = _a.outputs, params = _a.params, children = _a.children;
1791
+ var inputEntries = Object.entries(inputs || data.inputDefs || {});
1792
+ var outputEntries = Object.entries(outputs || data.outputDefs || {});
1793
+ var paramEntries = Object.entries(params || data.paramDefs || {});
1794
+ var engine = useEngine();
1795
+ var _d = __read(React.useState({}), 2), result = _d[0], setResult = _d[1];
1796
+ var _e = __read(React.useState(null), 2), duration = _e[0], setDuration = _e[1];
1797
+ var _f = __read(React.useState(((_c = outputEntries[0]) === null || _c === void 0 ? void 0 : _c[0]) || null), 2), focus = _f[0], setFocus = _f[1];
1798
+ var _g = __read(React.useState(false), 2), showPreview = _g[0], setShowPreview = _g[1];
1799
+ var previewValue = focus ? result[focus] : Object.values(result)[0];
1800
+ React.useEffect(function () {
1801
+ return engine.subscribe("functionResult", function (event) {
1802
+ if (event.name === id) {
1803
+ setResult(event.result || {});
1804
+ setDuration(event.duration || null);
1805
+ }
1806
+ });
1807
+ }, []);
1808
+ return (React.createElement(NodeContainer, { label: data.label, selected: selected, id: id },
1809
+ React.createElement("div", { className: styles.Description }, data.description),
1810
+ children,
1811
+ React.createElement("div", { className: styles.Ports },
1812
+ outputEntries.map(function (_a) {
1813
+ var _b = __read(_a, 2), name = _b[0], varDef = _b[1];
1814
+ return (React.createElement(Output, { key: name, name: name, varDef: varDef, id: id, onClick: function () { return setFocus(name); }, focus: showPreview && focus === name }));
1815
+ }),
1816
+ inputEntries.map(function (_a) {
1817
+ var _b = __read(_a, 2), name = _b[0], varDef = _b[1];
1818
+ return (React.createElement(Input, { key: name, name: name, varDef: varDef, id: id, data: data }));
1819
+ }),
1820
+ paramEntries.map(function (_a) {
1821
+ var _b = __read(_a, 2), name = _b[0], varDef = _b[1];
1822
+ return (React.createElement(Param, { key: name, name: name, varDef: varDef, id: id, data: data }));
1823
+ })),
1824
+ React.createElement("div", { className: classNames(styles.PreviewHead, (_b = {},
1825
+ _b[styles.expanded] = showPreview,
1826
+ _b)), onClick: function () { return setShowPreview(!showPreview); } }, "Preview"),
1827
+ showPreview && (React.createElement("div", { className: styles.Preview },
1828
+ React.createElement(TreeView, { value: previewValue }),
1829
+ duration && (React.createElement("div", { className: styles.Duration },
1830
+ duration.toFixed(2),
1831
+ " ms"))))));
1832
+ }
1833
+
1834
+ var math = create(all, {});
1835
+ function MathView(_a) {
1836
+ var expr = _a.expr, _b = _a.displayMode, displayMode = _b === void 0 ? false : _b;
1837
+ var latex = "";
1838
+ try {
1839
+ latex = math.parse(expr).toTex({ parenthesis: "auto" });
1840
+ }
1841
+ catch (e) {
1842
+ latex = String(expr); // fallback on parse error
1843
+ }
1844
+ var html = katex.renderToString(latex, {
1845
+ throwOnError: false,
1846
+ displayMode: displayMode,
1847
+ });
1848
+ return React.createElement("span", { dangerouslySetInnerHTML: { __html: html } });
1849
+ }
1850
+ var Calc = React.memo(function (_a) {
1851
+ var _b;
1852
+ var id = _a.id, data = _a.data, selected = _a.selected;
1853
+ var expression = (((_b = data.params) === null || _b === void 0 ? void 0 : _b.expression) || "").toString();
1854
+ // add free variables to inputs
1855
+ var inputs = __assign({}, (data.inputDefs || {}));
1856
+ var symbols = getUnboundSymbols(expression);
1857
+ symbols.forEach(function (symbol) {
1858
+ if (!inputs[symbol]) {
1859
+ inputs[symbol] = {
1860
+ type: "number",
1861
+ };
1862
+ }
1863
+ });
1864
+ return (React.createElement(GenericNode, { id: id, data: data, selected: selected, inputs: inputs },
1865
+ React.createElement(MathView, { expr: expression, displayMode: true })));
1866
+ });
1867
+ Calc.displayName = "CalcNode";
1868
+
1869
+ var Default = React.memo(function (_a) {
1870
+ var id = _a.id, data = _a.data, selected = _a.selected;
1871
+ return React.createElement(GenericNode, { id: id, data: data, selected: selected });
1872
+ });
1873
+ Default.displayName = "DefaultNode";
1874
+
1875
+ function uid() {
1876
+ return Math.random().toString(36).substring(2, 15);
1877
+ }
1878
+ var Merge = React.memo(function (_a) {
1879
+ var id = _a.id, data = _a.data, selected = _a.selected;
1880
+ var inputs = Object.fromEntries(Object.keys(data.inputs || {}).map(function (name, i) { return [
1881
+ name,
1882
+ { type: "any", label: "D".concat(i + 1) },
1883
+ ]; }));
1884
+ var inputCount = Object.keys(inputs).length;
1885
+ inputs[uid()] = { type: "any", label: "D".concat(inputCount + 1) };
1886
+ var outputs = __assign({}, (data.outputDefs || {}));
1887
+ return (React.createElement(NodeContainer, { label: data.name, selected: selected, id: id },
1888
+ React.createElement("div", { className: styles.Ports },
1889
+ Object.entries(outputs || {}).map(function (_a) {
1890
+ var _b = __read(_a, 2), name = _b[0], varDef = _b[1];
1891
+ return (React.createElement(Output, { key: name, name: name, varDef: varDef, id: id }));
1892
+ }),
1893
+ Object.entries(inputs || {}).map(function (_a) {
1894
+ var _b = __read(_a, 2), name = _b[0], varDef = _b[1];
1895
+ return (React.createElement(Input, { key: name, name: name, varDef: varDef, id: id, data: data }));
1896
+ }))));
1897
+ });
1898
+ Merge.displayName = "MergeNode";
1899
+
1900
+ var nodeTypes = {
1901
+ Default: Default,
1902
+ Calc: Calc,
1903
+ Log: Log,
1904
+ Merge: Merge,
1905
+ };
1906
+
1907
+ var variableStore = create$1(function (set, get, api) {
1908
+ return persist(function (pset, pget) { return ({
1909
+ data: {},
1910
+ getVar: function (scope, name, persist) {
1911
+ if (persist) {
1912
+ return pget().data["".concat(scope, "|").concat(name)];
1913
+ }
1914
+ else {
1915
+ return get().data["".concat(scope, "|").concat(name)];
1916
+ }
1917
+ },
1918
+ setVar: function (scope, name, value, persist) {
1919
+ var _a, _b;
1920
+ var key = "".concat(scope, "|").concat(name);
1921
+ if (persist) {
1922
+ var oldData = pget().data;
1923
+ var newValue = typeof value === "function"
1924
+ ? value(oldData[key])
1925
+ : value;
1926
+ var data = __assign(__assign({}, oldData), (_a = {}, _a[key] = newValue, _a));
1927
+ pset({ data: data });
1928
+ }
1929
+ else {
1930
+ var oldData = get().data;
1931
+ var newValue = typeof value === "function"
1932
+ ? value(oldData[key])
1933
+ : value;
1934
+ var data = __assign(__assign({}, oldData), (_b = {}, _b[key] = newValue, _b));
1935
+ set({ data: data });
1936
+ }
1937
+ },
1938
+ }); }, {
1939
+ name: "variable-storage", // unique name
1940
+ // getStorage: () => sessionStorage, // (optional) by default the 'localStorage' is used
1941
+ })(set, get, api);
1942
+ });
1943
+ /**
1944
+ * scope restricts the variable scope, for example to a view id
1945
+ * @param scope
1946
+ * @param name
1947
+ */
1948
+ var useVariable = function (scope, name, initial, persist) {
1949
+ if (persist === void 0) { persist = true; }
1950
+ var value = variableStore(function (_a) {
1951
+ var getVar = _a.getVar;
1952
+ return getVar(scope, name, persist);
1953
+ });
1954
+ if (typeof value === "undefined")
1955
+ value = initial;
1956
+ var setVar = variableStore(function (_a) {
1957
+ var setVar = _a.setVar;
1958
+ return setVar;
1959
+ });
1960
+ var setValue = function (value) { return setVar(scope, name, value, persist); };
1961
+ return [value, setValue];
1962
+ };
1963
+
1964
+ function usePositions(fn) {
1965
+ return useVariable("rules", "".concat(fn.name, ".positions"), {});
1966
+ }
1967
+ function useUpdatePositions(fn) {
1968
+ var _a = __read(usePositions(fn), 2), positions = _a[0], setPositions = _a[1];
1969
+ return React.useCallback(function (id, position) {
1970
+ positions[id] = position;
1971
+ setPositions(positions);
1972
+ }, [positions, setPositions]);
1973
+ }
1974
+
1975
+ // helpers
1976
+ function updateNodeArguments(node, inputs, params) {
1977
+ return __assign(__assign({}, node), { data: __assign(__assign({}, node.data), { inputs: inputs, params: params }) });
1978
+ }
1979
+ /**
1980
+ * flow state stores nodes and edges for the flow graph these can be updated when the function changes
1981
+ * using setFn
1982
+ */
1983
+ var useFlowState = create$1(function (set, get) { return ({
1984
+ engine: null,
1985
+ fn: null,
1986
+ options: {},
1987
+ nodes: [],
1988
+ edges: [],
1989
+ setNodes: function (updater) {
1990
+ set(function (state) { return ({ nodes: updater(state.nodes) }); });
1991
+ },
1992
+ setEdges: function (updater) {
1993
+ set(function (state) { return ({ edges: updater(state.edges) }); });
1994
+ },
1995
+ setFn: function (fn) {
1996
+ // console.log("setFn", fn);
1997
+ var _a = get(), oldFn = _a.fn, nodes = _a.nodes, edges = _a.edges, engine = _a.engine, options = _a.options;
1998
+ // update the graph by shallow comparison
1999
+ if (!engine) {
2000
+ throw new Error("Engine not set");
2001
+ }
2002
+ var oldKeys = Object.keys((oldFn === null || oldFn === void 0 ? void 0 : oldFn.body) || {});
2003
+ var newKeys = Object.keys(fn.body || {});
2004
+ // remove all the nodes that were removed
2005
+ nodes = nodes === null || nodes === void 0 ? void 0 : nodes.filter(function (node) { return newKeys.includes(node.id); });
2006
+ // remove all the edges that were removed
2007
+ edges = edges === null || edges === void 0 ? void 0 : edges.filter(function (edge) {
2008
+ return (newKeys.includes(edge.source) && newKeys.includes(edge.target));
2009
+ });
2010
+ // create the new nodes that were added
2011
+ var addedKeys = newKeys.filter(function (key) { return !oldKeys.includes(key); });
2012
+ addedKeys.forEach(function (key, index) {
2013
+ var _a;
2014
+ var fncall = (_a = fn.body) === null || _a === void 0 ? void 0 : _a[key];
2015
+ // add the node
2016
+ nodes.push(createNode(engine, key, fncall, options));
2017
+ // add edges
2018
+ var refs = getReferences(fncall.inputs || {});
2019
+ refs.forEach(function (ref) {
2020
+ edges.push(createEdge(key, ref));
2021
+ });
2022
+ });
2023
+ // update the changed nodes
2024
+ var changedKeys = newKeys.filter(function (key) {
2025
+ var _a, _b;
2026
+ // shallow comparison
2027
+ return ((_a = fn.body) === null || _a === void 0 ? void 0 : _a[key]) !== ((_b = oldFn === null || oldFn === void 0 ? void 0 : oldFn.body) === null || _b === void 0 ? void 0 : _b[key]);
2028
+ });
2029
+ // console.log("changed keys", changedKeys);
2030
+ changedKeys.forEach(function (key) {
2031
+ var _a;
2032
+ // update the nodes that were changed
2033
+ var fncall = (_a = fn.body) === null || _a === void 0 ? void 0 : _a[key];
2034
+ nodes = nodes === null || nodes === void 0 ? void 0 : nodes.map(function (n) {
2035
+ if (n.id === key) {
2036
+ return updateNodeArguments(n, fncall.inputs, fncall.params);
2037
+ }
2038
+ return n;
2039
+ });
2040
+ // update incoming edges
2041
+ var refs = getReferences(fncall.inputs || {});
2042
+ // remove all incoming edges
2043
+ edges = edges === null || edges === void 0 ? void 0 : edges.filter(function (e) { return e.target !== key; });
2044
+ // add the edge
2045
+ refs.forEach(function (ref) {
2046
+ edges.push(createEdge(key, ref));
2047
+ });
2048
+ });
2049
+ // console.log("final graph", nodes, edges);
2050
+ // update the function, nodes and edges
2051
+ set({ fn: fn, nodes: nodes, edges: edges });
2052
+ },
2053
+ init: function (fn, engine, options) {
2054
+ // console.log("initing");
2055
+ set({ engine: engine, options: options });
2056
+ get().setFn(fn);
2057
+ },
2058
+ }); });
2059
+ /**
2060
+ * creates a flow state and provides handlers to update nodes and edges
2061
+ */
2062
+ function useFlow(fn, engine, options) {
2063
+ var state = useFlowState();
2064
+ React.useEffect(function () {
2065
+ state.init(fn, engine, options);
2066
+ }, [engine]);
2067
+ React.useEffect(function () {
2068
+ state.setFn(fn);
2069
+ }, [fn]);
2070
+ return React.useMemo(function () { return ({
2071
+ nodes: state.nodes,
2072
+ edges: state.edges,
2073
+ setNodes: state.setNodes,
2074
+ setEdges: state.setEdges,
2075
+ }); }, [state]);
2076
+ }
2077
+ function createNode(engine, id, fncall, options) {
2078
+ var _a, _b;
2079
+ var calledFn = engine.getFunction(fncall.name);
2080
+ // create a node for each function call
2081
+ return {
2082
+ id: id,
2083
+ data: {
2084
+ name: fncall.name,
2085
+ label: fncall.label || (calledFn === null || calledFn === void 0 ? void 0 : calledFn.label) || fncall.name,
2086
+ description: calledFn === null || calledFn === void 0 ? void 0 : calledFn.description,
2087
+ inputs: fncall.inputs,
2088
+ params: fncall.params,
2089
+ inputDefs: (calledFn === null || calledFn === void 0 ? void 0 : calledFn.inputs) || {},
2090
+ paramDefs: (calledFn === null || calledFn === void 0 ? void 0 : calledFn.params) || {},
2091
+ outputDefs: (calledFn === null || calledFn === void 0 ? void 0 : calledFn.outputs) || {},
2092
+ onChange: ((_a = options.onDataChange) === null || _a === void 0 ? void 0 : _a.call(options, id)) || (function () { }),
2093
+ },
2094
+ position: ((_b = options.positions) === null || _b === void 0 ? void 0 : _b[id]) || { x: 0, y: 0 },
2095
+ dragHandle: options.dragHandle,
2096
+ type: (calledFn === null || calledFn === void 0 ? void 0 : calledFn.nodeType) || "Default",
2097
+ };
2098
+ }
2099
+ function createEdge(nodeId, ref) {
2100
+ return {
2101
+ id: "".concat(ref.path, "-").concat(nodeId, ".").concat(ref.name),
2102
+ source: ref.refNode,
2103
+ target: nodeId,
2104
+ sourceHandle: "".concat(ref.refNode, "-").concat(ref.refField),
2105
+ targetHandle: "".concat(nodeId, "-").concat(ref.name),
2106
+ };
2107
+ }
2108
+
2109
+ var ConnectionLine = (function (_a) {
2110
+ var _b;
2111
+ var fromX = _a.fromX, fromY = _a.fromY, toX = _a.toX, toY = _a.toY, fromHandle = _a.fromHandle, fromNode = _a.fromNode, connectionStatus = _a.connectionStatus;
2112
+ var _c = useConnection(), toNode = _c.toNode, toHandle = _c.toHandle;
2113
+ // correcting the start point as we moved the nodes in our custom ports
2114
+ if (fromNode && fromHandle) {
2115
+ fromX = (fromNode === null || fromNode === void 0 ? void 0 : fromNode.position.x) + fromHandle.x;
2116
+ if (fromHandle.position === "right") {
2117
+ fromX += fromHandle.width;
2118
+ }
2119
+ }
2120
+ if (toNode && toHandle) {
2121
+ toX = toHandle.x - toHandle.width / 2; // align to left side of the handle
2122
+ if (toHandle.position === "right") {
2123
+ toX += toHandle.width;
2124
+ }
2125
+ }
2126
+ var d = getSimpleBezierPath({
2127
+ sourceX: fromX,
2128
+ sourceY: fromY,
2129
+ targetX: toX,
2130
+ targetY: toY,
2131
+ sourcePosition: Position.Right,
2132
+ targetPosition: Position.Left,
2133
+ });
2134
+ return (React.createElement("g", { className: classNames(styles$1.ConnectionPath, "react-flow__connection-path", (_b = {}, _b[styles$1.valid] = connectionStatus === "valid", _b)) },
2135
+ React.createElement("path", { d: d[0] })));
2136
+ });
2137
+
2138
+ function FlowInner(_a) {
2139
+ var fn = _a.function, engine = _a.engine, onChange = _a.onChange, onClick = _a.onClick, onSelect = _a.onSelect;
2140
+ var _b = __read(React.useState(null), 2), instance = _b[0], setInstance = _b[1];
2141
+ var updatePosition = useUpdatePositions(fn);
2142
+ var _c = __read(usePositions(fn), 1), positions = _c[0];
2143
+ var handleDataChange = function (id) { return function (newData) {
2144
+ onChange === null || onChange === void 0 ? void 0 : onChange(function (fn) {
2145
+ // update the function definition
2146
+ // console.log("before fn call update", Object.keys(fn.body));
2147
+ var body = __assign({}, fn.body);
2148
+ var fncall = __assign(__assign({}, (body[id] || {})), newData);
2149
+ body[id] = fncall;
2150
+ // console.log("after fn call update", Object.keys(body));
2151
+ var updatedFn = __assign(__assign({}, fn), { body: body });
2152
+ return updatedFn;
2153
+ });
2154
+ }; };
2155
+ var _d = useFlow(fn, engine, {
2156
+ dragHandle: ".".concat(styles.Label),
2157
+ positions: positions,
2158
+ onDataChange: handleDataChange,
2159
+ }), nodes = _d.nodes, edges = _d.edges, setNodes = _d.setNodes, setEdges = _d.setEdges;
2160
+ // node selection handler
2161
+ var handleSelect = React.useCallback(function (_a) {
2162
+ var nodes = _a.nodes;
2163
+ onSelect === null || onSelect === void 0 ? void 0 : onSelect(nodes.map(function (n) { return n.id; }) || []);
2164
+ }, [onSelect]);
2165
+ useOnSelectionChange({
2166
+ onChange: handleSelect,
2167
+ });
2168
+ // dropping nodes
2169
+ var _e = __read(useDrop({
2170
+ accept: "flow-node",
2171
+ drop: function (item, monitor) {
2172
+ var pos = monitor.getClientOffset();
2173
+ if (instance && pos) {
2174
+ var position_1 = instance.screenToFlowPosition(pos);
2175
+ // console.log("handle drop", position);
2176
+ onChange === null || onChange === void 0 ? void 0 : onChange(function (fn) {
2177
+ return engine.applyNodeAdd(fn, item.name, function (fnCall, id) {
2178
+ // console.log("node added", id, position);
2179
+ updatePosition(id, position_1);
2180
+ });
2181
+ });
2182
+ }
2183
+ },
2184
+ collect: function (monitor) {
2185
+ return {
2186
+ isOver: monitor.isOver(),
2187
+ };
2188
+ },
2189
+ }), 2); _e[0].isOver; var drop = _e[1];
2190
+ // connecting nodes
2191
+ var onConnect = React.useCallback(function (params) {
2192
+ var _a, _b;
2193
+ var sourceField = (_a = params.sourceHandle) === null || _a === void 0 ? void 0 : _a.split("-")[1];
2194
+ var targetField = (_b = params.targetHandle) === null || _b === void 0 ? void 0 : _b.split("-")[1];
2195
+ if (!sourceField || !targetField) {
2196
+ console.warn("Invalid connection handles", params);
2197
+ return;
2198
+ }
2199
+ onChange === null || onChange === void 0 ? void 0 : onChange(function (fn) {
2200
+ return engine.applyNodeConnect(fn, params.source, params.target, sourceField, targetField);
2201
+ });
2202
+ }, [fn, onChange]);
2203
+ // deleting nodes
2204
+ var onNodesDelete = React.useCallback(function (nodesToDelete) {
2205
+ onChange === null || onChange === void 0 ? void 0 : onChange(function (fn) {
2206
+ return engine.applyNodeDelete(fn, nodesToDelete.map(function (n) { return n.id; }));
2207
+ });
2208
+ }, [onChange, fn]);
2209
+ // deleting edges
2210
+ var onEdgesDelete = React.useCallback(function (edgesToDelete) {
2211
+ onChange === null || onChange === void 0 ? void 0 : onChange(function (fn) {
2212
+ var newFn = fn;
2213
+ edgesToDelete.forEach(function (edge) {
2214
+ var _a, _b;
2215
+ var sourceField = (_a = edge.sourceHandle) === null || _a === void 0 ? void 0 : _a.split("-")[1];
2216
+ var targetField = (_b = edge.targetHandle) === null || _b === void 0 ? void 0 : _b.split("-")[1];
2217
+ if (!sourceField || !targetField) {
2218
+ console.warn("Invalid connection handles", edge);
2219
+ return;
2220
+ }
2221
+ newFn = engine.applyEdgeDelete(newFn, edge.source, edge.target, sourceField, targetField);
2222
+ });
2223
+ return newFn;
2224
+ });
2225
+ }, [onChange, fn]);
2226
+ // handle canvas clicks to be able to place nodes
2227
+ var handleClick = function (e) {
2228
+ if (instance) {
2229
+ var position = instance.screenToFlowPosition({
2230
+ x: e.clientX,
2231
+ y: e.clientY,
2232
+ });
2233
+ onClick === null || onClick === void 0 ? void 0 : onClick(e, position);
2234
+ }
2235
+ };
2236
+ var onNodesChange = React.useCallback(function (changes) {
2237
+ return setNodes(function (nodesSnapshot) {
2238
+ return applyNodeChanges(changes, nodesSnapshot);
2239
+ });
2240
+ }, []);
2241
+ var onEdgesChange = React.useCallback(function (changes) {
2242
+ return setEdges(function (edgesSnapshot) {
2243
+ return applyEdgeChanges(changes, edgesSnapshot);
2244
+ });
2245
+ }, []);
2246
+ return (React.createElement(ReactFlow, { ref: drop, nodes: nodes, edges: edges, nodeTypes: nodeTypes, onNodesChange: onNodesChange, onEdgesChange: onEdgesChange, onNodesDelete: onNodesDelete, onEdgesDelete: onEdgesDelete, onNodeDragStop: function (e, n) { return updatePosition(n.id, n.position); }, onConnect: onConnect, onInit: setInstance, onPaneClick: handleClick, fitView: true,
2247
+ // panOnDrag={false}
2248
+ selectionOnDrag: true, minZoom: 0.1, maxZoom: 4, deleteKeyCode: "Delete", connectionLineComponent: ConnectionLine },
2249
+ React.createElement(Background, { variant: BackgroundVariant.Dots }),
2250
+ React.createElement(Controls, null)));
2251
+ }
2252
+ function Flow(_a) {
2253
+ var fn = _a.function, engine = _a.engine, _b = _a.onChange, onChange = _b === void 0 ? function () { } : _b, onClick = _a.onClick, onSelect = _a.onSelect, customControls = _a.customControls;
2254
+ return (React.createElement(FlowContext.Provider, { value: { engine: engine, controls: customControls } },
2255
+ React.createElement(ReactFlowProvider, null,
2256
+ React.createElement(FlowInner, { function: fn, engine: engine, onChange: onChange, onClick: onClick, onSelect: onSelect }))));
2257
+ }
2258
+
2259
+ function useDraggableNode(name, fn) {
2260
+ var _a = __read(useDrag({
2261
+ type: "flow-node",
2262
+ item: { name: name, fn: fn },
2263
+ collect: function (monitor) { return ({
2264
+ isDragging: monitor.isDragging(),
2265
+ }); },
2266
+ }), 2), drag = _a[1];
2267
+ return function (ref) { return drag(ref); };
2268
+ }
2269
+
2270
+ /**
2271
+ * using functions
2272
+ *
2273
+ * in React context
2274
+ * - use useFunction. This will build the function, mount it if needed and provides a run function.
2275
+ *
2276
+ *
2277
+ * in Vanilla context
2278
+ * - use engine.build(fn) to build the function
2279
+ * - use engine.mount(fn) to mount the function (if it has a mount function)
2280
+ * - use await engine.run(fn, inputs) to run the function and get the result
2281
+ */
2282
+ function useFunction(engine, fn, mount) {
2283
+ var _this = this;
2284
+ var _a = __read(React.useState(null), 2), result = _a[0], setResult = _a[1];
2285
+ var builtFn = React.useMemo(function () { return engine.build(fn); }, [fn]);
2286
+ React.useEffect(function () {
2287
+ if (mount) {
2288
+ return engine.mount(builtFn);
2289
+ }
2290
+ }, [builtFn, mount]);
2291
+ var run = React.useCallback(function (inputs) { return __awaiter(_this, void 0, void 0, function () {
2292
+ var result;
2293
+ return __generator(this, function (_a) {
2294
+ switch (_a.label) {
2295
+ case 0: return [4 /*yield*/, engine.run(builtFn, inputs)];
2296
+ case 1:
2297
+ result = _a.sent();
2298
+ setResult(result);
2299
+ return [2 /*return*/, result];
2300
+ }
2301
+ });
2302
+ }); }, [builtFn]);
2303
+ return React.useMemo(function () { return ({
2304
+ fn: builtFn,
2305
+ run: run,
2306
+ result: result,
2307
+ }); }, [builtFn, run, result]);
2308
+ }
2309
+
2310
+ export { DISCARD, Engine, Flow, Lib, binaryOnTree, binaryOnTreeBranch, broadCast, expandTree, getBranch, getReferences, getValue$1 as getValue, graftTree, interpolate, isReference, isSingleTon, isTree, mapTree, mapTreeBranch, nAryOnTree, nAryOnTreeBranch, normalizeVarDef, parseReference, primitives, sameShape, simplifyTree, toArray, topSort, treeSize, trimTree, uid$1 as uid, useDraggableNode, useFlow, useFunction, usePositions, useUpdatePositions, useVariable };
2311
+ //# sourceMappingURL=index.esm.js.map