@n3rdw1z4rd/core 0.20.0 → 0.21.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.
Files changed (44) hide show
  1. package/dist/graph/doc.d.ts +141 -0
  2. package/dist/graph/doc.js +173 -0
  3. package/dist/graph/evaluate.d.ts +114 -0
  4. package/dist/graph/evaluate.js +319 -0
  5. package/dist/graph/index.d.ts +9 -0
  6. package/dist/graph/index.js +9 -0
  7. package/dist/graph/node.d.ts +153 -0
  8. package/dist/graph/node.js +94 -0
  9. package/dist/graph/nodes.d.ts +11 -0
  10. package/dist/graph/nodes.js +399 -0
  11. package/dist/graph/script.d.ts +56 -0
  12. package/dist/graph/script.js +98 -0
  13. package/dist/graph/sources.d.ts +11 -0
  14. package/dist/graph/sources.js +263 -0
  15. package/dist/graph/subgraph.d.ts +36 -0
  16. package/dist/graph/subgraph.js +280 -0
  17. package/dist/graph/types.d.ts +56 -0
  18. package/dist/graph/types.js +67 -0
  19. package/dist/graph.cjs +1709 -0
  20. package/dist/graph.d.cts +568 -0
  21. package/dist/index.cjs +53 -52
  22. package/dist/rng-Dhqq7owV.cjs +642 -0
  23. package/dist/{spatial-partition-3d-Ba-VBveM.cjs → spatial-partition-3d-CmSCL87Z.cjs} +19 -660
  24. package/dist/three/adaptive-grid.d.ts +43 -0
  25. package/dist/three/adaptive-grid.js +127 -0
  26. package/dist/three/ecs.d.ts +5 -3
  27. package/dist/three/ecs.js +5 -3
  28. package/dist/three/editor-camera.d.ts +93 -0
  29. package/dist/three/editor-camera.js +174 -0
  30. package/dist/three/index.d.ts +6 -1
  31. package/dist/three/index.js +6 -1
  32. package/dist/three/picking.d.ts +34 -0
  33. package/dist/three/picking.js +59 -0
  34. package/dist/three/schema.d.ts +139 -0
  35. package/dist/three/schema.js +214 -0
  36. package/dist/three/world.d.ts +192 -0
  37. package/dist/three/world.js +363 -0
  38. package/dist/three.cjs +970 -23
  39. package/dist/three.d.cts +497 -5
  40. package/dist/vite.cjs +40 -0
  41. package/dist/vite.d.cts +35 -0
  42. package/dist/vite.d.ts +35 -0
  43. package/dist/vite.js +39 -0
  44. package/package.json +21 -1
@@ -0,0 +1,319 @@
1
+ import { getNode, linksInto } from "./doc.js";
2
+ //#region src/graph/evaluate.ts
3
+ /**
4
+ * Evaluates a graph: runs the nodes the outputs depend on, in dependency order, passing
5
+ * values along the links.
6
+ *
7
+ * - **Lazy:** only output nodes (`output: true`) and what they depend on run, unless you
8
+ * name other targets.
9
+ * - **Memoized:** a node re-runs only when its params / input values, an upstream result or
10
+ * its type changed since the last evaluation; otherwise its previous outputs are reused.
11
+ * - **List broadcasting:** a list wired into a single-value input runs the node once per
12
+ * item (several lists: longest wins, shorter ones repeat their last item) and every
13
+ * output becomes a list. A list port (`vec2[]`) takes the whole list instead; one value
14
+ * wired into it arrives as a one-item list. A list output of a broadcast node is
15
+ * flattened into the result list.
16
+ * - **Animation (optional):** a node with `animate` on (per node, or its type's default)
17
+ * re-runs on every evaluation that passes a new `frame`, and so does everything downstream
18
+ * of it; the rest stays cached. {@link GraphEvaluator.animated} tells the host whether any
19
+ * output depends on an animated node — if not, there's nothing to re-evaluate per frame.
20
+ * - **Disabled nodes** (`GraphNode.disabled`) don't run; downstream they count as failed
21
+ * (blocked, or left out of a multi input).
22
+ * - **Errors stay local:** a throwing node gets an `error`; nodes downstream of it are
23
+ * `blocked` (skipped) and don't run; the rest of the graph still evaluates. A **multi**
24
+ * input leaves failed sources out instead (listed in `skipped`), so one broken branch
25
+ * doesn't take down everything it feeds into.
26
+ *
27
+ * Nodes must treat their inputs as read-only: values are shared with upstream caches.
28
+ *
29
+ * @category Graph
30
+ */
31
+ var GraphEvaluator = class {
32
+ registry;
33
+ cache = /* @__PURE__ */ new Map();
34
+ stamp = 0;
35
+ constructor(registry) {
36
+ this.registry = registry;
37
+ }
38
+ /** The last result of a node. */
39
+ result(nodeId) {
40
+ return this.cache.get(nodeId);
41
+ }
42
+ /** Forgets cached results (all, or one node's), so they re-run next time. */
43
+ invalidate(nodeId) {
44
+ if (nodeId === void 0) this.cache.clear();
45
+ else this.cache.delete(nodeId);
46
+ }
47
+ /** The animated nodes the outputs (or `targets`) depend on; empty: no need to evaluate per frame. */
48
+ animated(doc, targets) {
49
+ const { order } = this.order(doc, targets ?? this.defaultTargets(doc));
50
+ return order.filter((id) => {
51
+ const node = getNode(doc, id);
52
+ return !node.disabled && (node.animate ?? this.registry.get(node.type)?.animate ?? false);
53
+ });
54
+ }
55
+ async evaluate(doc, options = {}) {
56
+ const env = options.env ?? {};
57
+ const frame = options.frame ?? {
58
+ time: 0,
59
+ dt: 0,
60
+ frame: 0
61
+ };
62
+ const scope = options.scope ? `${options.scope}/` : "";
63
+ const targets = options.targets ?? this.defaultTargets(doc);
64
+ const { order, cyclic } = this.order(doc, targets);
65
+ const ran = [];
66
+ const results = /* @__PURE__ */ new Map();
67
+ for (const id of order) {
68
+ const node = getNode(doc, id);
69
+ const def = this.registry.get(node.type);
70
+ if (!def) {
71
+ results.set(id, this.store(id, "", fail(`unknown node type "${node.type}"`)));
72
+ continue;
73
+ }
74
+ if (cyclic.has(id)) {
75
+ results.set(id, this.store(id, "", fail("part of a loop")));
76
+ continue;
77
+ }
78
+ if (node.disabled) {
79
+ results.set(id, this.store(id, "", {
80
+ outputs: {},
81
+ lists: {},
82
+ disabled: true,
83
+ ms: 0
84
+ }));
85
+ continue;
86
+ }
87
+ const values = {};
88
+ const isList = {};
89
+ const keyParts = [def.type, def.revision];
90
+ if (node.animate ?? def.animate) keyParts.push([
91
+ "frame",
92
+ frame.frame,
93
+ frame.time
94
+ ]);
95
+ let blocked;
96
+ let missing;
97
+ const skipped = [];
98
+ for (const p of def.inputs) {
99
+ const links = linksInto(doc, id, p.name);
100
+ const external = options.externals?.get(`${id}:${p.name}`);
101
+ if (!links.length && external?.length) {
102
+ keyParts.push([
103
+ p.name,
104
+ "external",
105
+ options.externalsStamp ?? 0
106
+ ]);
107
+ if (p.multi) {
108
+ values[p.name] = external.flatMap((x) => x.list ? x.value : x.value === void 0 ? [] : [x.value]);
109
+ isList[p.name] = true;
110
+ } else {
111
+ values[p.name] = external[0].value;
112
+ isList[p.name] = external[0].list;
113
+ }
114
+ } else if (links.length) {
115
+ const gathered = [];
116
+ for (const link of p.multi ? links : links.slice(0, 1)) {
117
+ const src = results.get(link.from.node);
118
+ if (!src || src.error || src.blocked || src.disabled) {
119
+ if (p.multi) skipped.push(link.from.node);
120
+ else blocked ??= link.from.node;
121
+ keyParts.push([
122
+ p.name,
123
+ link.from.node,
124
+ "failed"
125
+ ]);
126
+ continue;
127
+ }
128
+ const v = src.outputs[link.from.port];
129
+ const list = !!src.lists[link.from.port];
130
+ keyParts.push([
131
+ p.name,
132
+ link.from.node,
133
+ src.stamp,
134
+ link.from.port
135
+ ]);
136
+ if (!p.multi) {
137
+ values[p.name] = v;
138
+ isList[p.name] = list;
139
+ } else if (list) gathered.push(...v);
140
+ else if (v !== void 0) gathered.push(v);
141
+ }
142
+ if (p.multi) {
143
+ values[p.name] = gathered;
144
+ isList[p.name] = true;
145
+ }
146
+ } else {
147
+ const v = node.values[p.name] ?? p.default;
148
+ values[p.name] = v;
149
+ isList[p.name] = p.list && Array.isArray(v);
150
+ keyParts.push([p.name, v]);
151
+ if (v === void 0 && !p.optional) missing ??= p.name;
152
+ }
153
+ }
154
+ if (blocked) {
155
+ results.set(id, this.store(id, "", {
156
+ ...fail(""),
157
+ error: void 0,
158
+ blocked
159
+ }));
160
+ continue;
161
+ }
162
+ if (missing) {
163
+ results.set(id, this.store(id, "", fail(`input "${missing}" needs a value or a link`)));
164
+ continue;
165
+ }
166
+ const params = {};
167
+ for (const p of def.params) params[p.name] = node.values[p.name] ?? p.default;
168
+ keyParts.push(params);
169
+ const key = safeKey(keyParts);
170
+ const prev = this.cache.get(id);
171
+ if (prev && key && prev.key === key && !prev.error) {
172
+ results.set(id, prev);
173
+ continue;
174
+ }
175
+ const res = await this.run(def, scope + id, values, isList, params, env, frame);
176
+ if (skipped.length) res.skipped = skipped;
177
+ ran.push(id);
178
+ results.set(id, this.store(id, key, res));
179
+ }
180
+ for (const id of [...this.cache.keys()]) if (!getNode(doc, id)) this.cache.delete(id);
181
+ return {
182
+ order,
183
+ ran,
184
+ results
185
+ };
186
+ }
187
+ defaultTargets(doc) {
188
+ const outputs = doc.nodes.filter((n) => this.registry.get(n.type)?.output).map((n) => n.id);
189
+ return outputs.length ? outputs : doc.nodes.map((n) => n.id);
190
+ }
191
+ /** Dependency order (upstream first) of the targets and everything they depend on. */
192
+ order(doc, targets) {
193
+ const order = [];
194
+ const done = /* @__PURE__ */ new Set();
195
+ const active = /* @__PURE__ */ new Set();
196
+ const cyclic = /* @__PURE__ */ new Set();
197
+ const visit = (id) => {
198
+ if (done.has(id)) return;
199
+ if (active.has(id)) {
200
+ for (const a of active) cyclic.add(a);
201
+ return;
202
+ }
203
+ if (!getNode(doc, id)) return;
204
+ active.add(id);
205
+ for (const l of doc.links) if (l.to.node === id) visit(l.from.node);
206
+ active.delete(id);
207
+ done.add(id);
208
+ order.push(id);
209
+ };
210
+ for (const t of targets) visit(t);
211
+ return {
212
+ order,
213
+ cyclic
214
+ };
215
+ }
216
+ async run(def, nodeId, values, isList, params, env, frame) {
217
+ const t0 = now();
218
+ const broadcast = [];
219
+ for (const p of def.inputs) if (p.list) {
220
+ if (!isList[p.name]) values[p.name] = values[p.name] === void 0 ? [] : [values[p.name]];
221
+ } else if (isList[p.name]) broadcast.push(p);
222
+ const outputs = {};
223
+ const lists = {};
224
+ try {
225
+ if (broadcast.length === 0) {
226
+ const r = await def.run(values, params, {
227
+ nodeId,
228
+ type: def.type,
229
+ source: def.source,
230
+ index: 0,
231
+ count: 1,
232
+ env,
233
+ ...frame
234
+ }) ?? {};
235
+ const said = r[OUTPUT_LISTS];
236
+ for (const o of def.outputs) {
237
+ outputs[o.name] = r[o.name];
238
+ lists[o.name] = said?.[o.name] ?? o.list;
239
+ }
240
+ } else {
241
+ const lens = broadcast.map((p) => values[p.name].length);
242
+ const count = lens.some((n) => n === 0) ? 0 : Math.max(...lens);
243
+ for (const o of def.outputs) {
244
+ outputs[o.name] = [];
245
+ lists[o.name] = true;
246
+ }
247
+ for (let i = 0; i < count; i++) {
248
+ const args = { ...values };
249
+ broadcast.forEach((p, k) => {
250
+ const list = values[p.name];
251
+ args[p.name] = list[Math.min(i, lens[k] - 1)];
252
+ });
253
+ const r = await def.run(args, params, {
254
+ nodeId,
255
+ type: def.type,
256
+ source: def.source,
257
+ index: i,
258
+ count,
259
+ env,
260
+ ...frame
261
+ }) ?? {};
262
+ for (const o of def.outputs) {
263
+ const v = r[o.name];
264
+ if (o.list && Array.isArray(v)) outputs[o.name].push(...v);
265
+ else outputs[o.name].push(v);
266
+ }
267
+ }
268
+ }
269
+ } catch (err) {
270
+ return {
271
+ ...fail(describe(err)),
272
+ ms: now() - t0
273
+ };
274
+ }
275
+ return {
276
+ outputs,
277
+ lists,
278
+ ms: now() - t0
279
+ };
280
+ }
281
+ store(id, key, res) {
282
+ const r = {
283
+ ...res,
284
+ stamp: ++this.stamp,
285
+ key
286
+ };
287
+ this.cache.set(id, r);
288
+ return r;
289
+ }
290
+ };
291
+ /**
292
+ * A key a node's `run` may add to its result: `{ [OUTPUT_LISTS]: { out: true } }` marks outputs
293
+ * as lists regardless of their declared type.
294
+ *
295
+ * @category Graph
296
+ */
297
+ const OUTPUT_LISTS = "__lists";
298
+ function fail(error) {
299
+ return {
300
+ outputs: {},
301
+ lists: {},
302
+ error,
303
+ ms: 0
304
+ };
305
+ }
306
+ function describe(err) {
307
+ return err instanceof Error ? `${err.name}: ${err.message}` : String(err);
308
+ }
309
+ /** A cache key; '' (never matches) if something in it can't be serialized. */
310
+ function safeKey(parts) {
311
+ try {
312
+ return JSON.stringify(parts);
313
+ } catch {
314
+ return "";
315
+ }
316
+ }
317
+ const now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
318
+ //#endregion
319
+ export { GraphEvaluator, OUTPUT_LISTS };
@@ -0,0 +1,9 @@
1
+ import { ParsedType, PortTypeDef, TypeRegistry, parseType, portTypes } from "./types.js";
2
+ import { NodeDef, NodeRegistry, NodeSpec, Param, ParamSpec, Port, PortSpec, RunContext, RunFn, WidgetSpec, defineNode } from "./node.js";
3
+ import { ConnectCheck, GRAPH_FORMAT, GRAPH_VERSION, GraphDoc, GraphGroup, GraphLink, GraphNode, PortRef, SubgraphDef, addNode, canConnect, connect, createGraph, disconnect, getNode, graphId, linkInto, linksInto, normalizeGraph, removeNode } from "./doc.js";
4
+ import { EvaluateOptions, EvaluateResult, FrameInfo, GraphEvaluator, NodeResult, OUTPUT_LISTS } from "./evaluate.js";
5
+ import { BUILTIN_NODES, createNodeRegistry } from "./nodes.js";
6
+ import { BehaviorValue, SCRIPT_NODE_TEMPLATE, behaviorRun, compileNodeScript } from "./script.js";
7
+ import { BUILTIN_SOURCES } from "./sources.js";
8
+ import { collapseToSubgraph, expandSubgraph, freeSubgraphType, registerSubgraphs, subgraphSpec } from "./subgraph.js";
9
+ export { BUILTIN_NODES, BUILTIN_SOURCES, BehaviorValue, ConnectCheck, EvaluateOptions, EvaluateResult, FrameInfo, GRAPH_FORMAT, GRAPH_VERSION, GraphDoc, GraphEvaluator, GraphGroup, GraphLink, GraphNode, NodeDef, NodeRegistry, NodeResult, NodeSpec, OUTPUT_LISTS, Param, ParamSpec, ParsedType, Port, PortRef, PortSpec, PortTypeDef, RunContext, RunFn, SCRIPT_NODE_TEMPLATE, SubgraphDef, TypeRegistry, WidgetSpec, addNode, behaviorRun, canConnect, collapseToSubgraph, compileNodeScript, connect, createGraph, createNodeRegistry, defineNode, disconnect, expandSubgraph, freeSubgraphType, getNode, graphId, linkInto, linksInto, normalizeGraph, parseType, portTypes, registerSubgraphs, removeNode, subgraphSpec };
@@ -0,0 +1,9 @@
1
+ import { TypeRegistry, parseType, portTypes } from "./types.js";
2
+ import { GRAPH_FORMAT, GRAPH_VERSION, addNode, canConnect, connect, createGraph, disconnect, getNode, graphId, linkInto, linksInto, normalizeGraph, removeNode } from "./doc.js";
3
+ import { GraphEvaluator, OUTPUT_LISTS } from "./evaluate.js";
4
+ import { NodeRegistry, defineNode } from "./node.js";
5
+ import { BUILTIN_SOURCES } from "./sources.js";
6
+ import { BUILTIN_NODES, createNodeRegistry } from "./nodes.js";
7
+ import { SCRIPT_NODE_TEMPLATE, behaviorRun, compileNodeScript } from "./script.js";
8
+ import { collapseToSubgraph, expandSubgraph, freeSubgraphType, registerSubgraphs, subgraphSpec } from "./subgraph.js";
9
+ export { BUILTIN_NODES, BUILTIN_SOURCES, GRAPH_FORMAT, GRAPH_VERSION, GraphEvaluator, NodeRegistry, OUTPUT_LISTS, SCRIPT_NODE_TEMPLATE, TypeRegistry, addNode, behaviorRun, canConnect, collapseToSubgraph, compileNodeScript, connect, createGraph, createNodeRegistry, defineNode, disconnect, expandSubgraph, freeSubgraphType, getNode, graphId, linkInto, linksInto, normalizeGraph, parseType, portTypes, registerSubgraphs, removeNode, subgraphSpec };
@@ -0,0 +1,153 @@
1
+ import { ParsedType } from "./types.js";
2
+ //#region src/graph/node.d.ts
3
+ /**
4
+ * Node definitions: a node is a function with a typed interface.
5
+ *
6
+ * - **inputs** are pins wired from other nodes' outputs. An unconnected input uses the
7
+ * value set on the node in the editor (an inline widget), or its `default`.
8
+ * - **params** are settings shown as widgets on the node; they can't be wired.
9
+ * - **outputs** are what `run` returns.
10
+ *
11
+ * Built-in nodes are written in TypeScript with {@link defineNode}; script nodes are plain
12
+ * ES modules with the same exports (see {@link compileNodeScript}), so logic is code you
13
+ * write by hand and the graph only wires data between functions.
14
+ *
15
+ * ```ts
16
+ * defineNode({
17
+ * type: 'shapes/ball',
18
+ * inputs: { at: 'vec2', radius: { type: 'number', default: 8, min: 0.5 } },
19
+ * params: { color: { type: 'color', default: '#e8554e' } },
20
+ * outputs: { entity: 'entity' },
21
+ * run: ({ at, radius }, { color }) => ({ entity: { shape: 'ball', x: at.x, y: at.y, r: radius, color } }),
22
+ * });
23
+ * ```
24
+ *
25
+ * @module
26
+ */
27
+ /** How a value is edited in the editor (for params, and unconnected inputs). @category Graph */
28
+ export interface WidgetSpec {
29
+ default?: unknown;
30
+ label?: string;
31
+ min?: number;
32
+ max?: number;
33
+ step?: number;
34
+ /** choices for `enum` */
35
+ options?: readonly string[];
36
+ /** `string` params: a multi-line editor (code, text) */
37
+ multiline?: boolean;
38
+ }
39
+ /** An input or output: a type string, or a type with widget settings. @category Graph */
40
+ export type PortSpec = string | ({
41
+ type: string;
42
+ optional?: boolean;
43
+ description?: string;
44
+ /** list inputs only: accept several links, concatenated in the order they were made */
45
+ multi?: boolean;
46
+ } & WidgetSpec);
47
+ /** A param: a widget on the node. Types: number, boolean, string, color, enum, vec2. @category Graph */
48
+ export type ParamSpec = {
49
+ type: string;
50
+ description?: string;
51
+ } & WidgetSpec;
52
+ /** What `run` gets besides its inputs and params. @category Graph */
53
+ export interface RunContext {
54
+ /** the node instance's id */
55
+ nodeId: string;
56
+ /** the node's type, and its source module (if it has one) — behaviour nodes pass these on */
57
+ type: string;
58
+ source?: string;
59
+ /** while broadcasting over lists: this call's index (else 0) and the call count (else 1) */
60
+ index: number;
61
+ count: number;
62
+ /** anything the host passes to the evaluator (e.g. a seed) */
63
+ env: Record<string, unknown>;
64
+ /** seconds since play started, the last frame's duration and the frame number (all 0 outside animation) */
65
+ time: number;
66
+ dt: number;
67
+ frame: number;
68
+ }
69
+ /** @category Graph */
70
+ export type RunFn = (inputs: Record<string, any>, params: Record<string, any>, ctx: RunContext) => Record<string, unknown> | void | Promise<Record<string, unknown> | void>;
71
+ /** A node type, as declared. @category Graph */
72
+ export interface NodeSpec {
73
+ /** unique, e.g. `math/add`; the key nodes are saved with */
74
+ type: string;
75
+ title?: string;
76
+ /** for the add-node menu, e.g. `math` */
77
+ category?: string;
78
+ description?: string;
79
+ inputs?: Record<string, PortSpec>;
80
+ params?: Record<string, ParamSpec>;
81
+ outputs?: Record<string, PortSpec>;
82
+ run: RunFn;
83
+ /**
84
+ * An output node (a viewport, an exporter…): what evaluation is for. By default the
85
+ * evaluator only runs output nodes and what they depend on.
86
+ */
87
+ output?: boolean;
88
+ /**
89
+ * Re-run every frame (with `ctx.time` / `ctx.dt`) while the host animates the graph.
90
+ * The type's default; each node can switch it (`GraphNode.animate`). Default false.
91
+ */
92
+ animate?: boolean;
93
+ /**
94
+ * An equivalent ES module (see {@link compileNodeScript}): a script node's own code, or a
95
+ * built-in's code written out so it can be viewed and forked into a custom node.
96
+ */
97
+ source?: string;
98
+ }
99
+ /** @category Graph */
100
+ export interface Port extends ParsedType, WidgetSpec {
101
+ name: string;
102
+ /** as declared, e.g. `vec2[]` */
103
+ type: string;
104
+ optional: boolean;
105
+ /** accepts several links (list inputs) */
106
+ multi: boolean;
107
+ description?: string;
108
+ }
109
+ /** @category Graph */
110
+ export interface Param extends WidgetSpec {
111
+ name: string;
112
+ type: string;
113
+ description?: string;
114
+ }
115
+ /** A node type with its ports parsed. @category Graph */
116
+ export interface NodeDef {
117
+ readonly type: string;
118
+ readonly title: string;
119
+ readonly category: string;
120
+ readonly description: string;
121
+ readonly inputs: readonly Port[];
122
+ readonly params: readonly Param[];
123
+ readonly outputs: readonly Port[];
124
+ readonly run: RunFn;
125
+ readonly output: boolean;
126
+ readonly animate: boolean;
127
+ readonly source?: string;
128
+ /** bumped whenever a type is re-registered, so cached results are dropped */
129
+ readonly revision: number;
130
+ }
131
+ /**
132
+ * Checks and normalizes a node spec.
133
+ *
134
+ * @category Graph
135
+ */
136
+ export declare function defineNode(spec: NodeSpec): NodeDef;
137
+ /**
138
+ * Node types by name.
139
+ *
140
+ * @category Graph
141
+ */
142
+ export declare class NodeRegistry {
143
+ private readonly defs;
144
+ private readonly listeners;
145
+ register(spec: NodeSpec | NodeDef): NodeDef;
146
+ unregister(type: string): void;
147
+ get(type: string): NodeDef | undefined;
148
+ has(type: string): boolean;
149
+ all(): NodeDef[];
150
+ /** Called when a type is registered (or replaced) or removed; returns an unsubscribe. */
151
+ onChange(listener: (def: NodeDef, removed: boolean) => void): () => void;
152
+ }
153
+ //#endregion
@@ -0,0 +1,94 @@
1
+ import { parseType } from "./types.js";
2
+ //#region src/graph/node.ts
3
+ let revisionCounter = 0;
4
+ function port(name, spec) {
5
+ const s = typeof spec === "string" ? { type: spec } : spec;
6
+ if (typeof s.type !== "string" || !s.type.trim()) throw new Error(`port "${name}": missing type`);
7
+ const parsed = parseType(s.type);
8
+ const multi = !!s.multi;
9
+ if (multi && !parsed.list) throw new Error(`port "${name}": only list ports (type[]) can be multi`);
10
+ return {
11
+ ...s,
12
+ name,
13
+ ...parsed,
14
+ type: s.type.trim(),
15
+ optional: !!s.optional,
16
+ multi
17
+ };
18
+ }
19
+ /**
20
+ * Checks and normalizes a node spec.
21
+ *
22
+ * @category Graph
23
+ */
24
+ function defineNode(spec) {
25
+ if (!spec || typeof spec.type !== "string" || !spec.type.trim()) throw new Error("defineNode: `type` is required");
26
+ if (typeof spec.run !== "function") throw new Error(`node "${spec.type}": \`run\` must be a function`);
27
+ const names = /* @__PURE__ */ new Set();
28
+ const unique = (n, what) => {
29
+ if (names.has(`${what}:${n}`)) throw new Error(`node "${spec.type}": duplicate ${what} "${n}"`);
30
+ names.add(`${what}:${n}`);
31
+ };
32
+ const inputs = Object.entries(spec.inputs ?? {}).map(([n, s]) => (unique(n, "input"), port(n, s)));
33
+ const outputs = Object.entries(spec.outputs ?? {}).map(([n, s]) => (unique(n, "output"), port(n, s)));
34
+ const params = Object.entries(spec.params ?? {}).map(([n, s]) => {
35
+ unique(n, "input");
36
+ if (!s || typeof s.type !== "string") throw new Error(`node "${spec.type}": param "${n}" needs a type`);
37
+ return {
38
+ ...s,
39
+ name: n
40
+ };
41
+ });
42
+ const type = spec.type.trim();
43
+ return {
44
+ type,
45
+ title: spec.title ?? type.split("/").pop(),
46
+ category: spec.category ?? (type.includes("/") ? type.slice(0, type.lastIndexOf("/")) : "misc"),
47
+ description: spec.description ?? "",
48
+ inputs,
49
+ params,
50
+ outputs,
51
+ run: spec.run,
52
+ output: !!spec.output,
53
+ animate: !!spec.animate,
54
+ source: spec.source,
55
+ revision: ++revisionCounter
56
+ };
57
+ }
58
+ /**
59
+ * Node types by name.
60
+ *
61
+ * @category Graph
62
+ */
63
+ var NodeRegistry = class {
64
+ defs = /* @__PURE__ */ new Map();
65
+ listeners = /* @__PURE__ */ new Set();
66
+ register(spec) {
67
+ const def = "revision" in spec ? spec : defineNode(spec);
68
+ this.defs.set(def.type, def);
69
+ for (const l of this.listeners) l(def, false);
70
+ return def;
71
+ }
72
+ unregister(type) {
73
+ const def = this.defs.get(type);
74
+ if (!def) return;
75
+ this.defs.delete(type);
76
+ for (const l of this.listeners) l(def, true);
77
+ }
78
+ get(type) {
79
+ return this.defs.get(type);
80
+ }
81
+ has(type) {
82
+ return this.defs.has(type);
83
+ }
84
+ all() {
85
+ return [...this.defs.values()];
86
+ }
87
+ /** Called when a type is registered (or replaced) or removed; returns an unsubscribe. */
88
+ onChange(listener) {
89
+ this.listeners.add(listener);
90
+ return () => this.listeners.delete(listener);
91
+ }
92
+ };
93
+ //#endregion
94
+ export { NodeRegistry, defineNode };
@@ -0,0 +1,11 @@
1
+ import { NodeRegistry, NodeSpec } from "./node.js";
2
+ //#region src/graph/nodes.d.ts
3
+ /** @category Graph */
4
+ export declare const BUILTIN_NODES: NodeSpec[];
5
+ /**
6
+ * A registry with the built-in nodes.
7
+ *
8
+ * @category Graph
9
+ */
10
+ export declare function createNodeRegistry(): NodeRegistry;
11
+ //#endregion