@dxos/app-graph 0.8.4-main.bc674ce → 0.8.4-main.bcb3aa67d6

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 (45) hide show
  1. package/dist/lib/browser/chunk-AKBGYELG.mjs +1603 -0
  2. package/dist/lib/browser/chunk-AKBGYELG.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +17 -1276
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +39 -0
  7. package/dist/lib/browser/testing/index.mjs.map +7 -0
  8. package/dist/lib/node-esm/chunk-HR5S4XYH.mjs +1604 -0
  9. package/dist/lib/node-esm/chunk-HR5S4XYH.mjs.map +7 -0
  10. package/dist/lib/node-esm/index.mjs +17 -1276
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/lib/node-esm/testing/index.mjs +40 -0
  14. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  15. package/dist/types/src/graph-builder.d.ts +11 -7
  16. package/dist/types/src/graph-builder.d.ts.map +1 -1
  17. package/dist/types/src/graph.d.ts +13 -17
  18. package/dist/types/src/graph.d.ts.map +1 -1
  19. package/dist/types/src/index.d.ts +1 -0
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/node-matcher.d.ts +43 -17
  22. package/dist/types/src/node-matcher.d.ts.map +1 -1
  23. package/dist/types/src/node.d.ts +21 -5
  24. package/dist/types/src/node.d.ts.map +1 -1
  25. package/dist/types/src/stories/EchoGraph.stories.d.ts.map +1 -1
  26. package/dist/types/src/testing/index.d.ts +2 -0
  27. package/dist/types/src/testing/index.d.ts.map +1 -0
  28. package/dist/types/src/testing/setup-graph-builder.d.ts +31 -0
  29. package/dist/types/src/testing/setup-graph-builder.d.ts.map +1 -0
  30. package/dist/types/src/util.d.ts +39 -0
  31. package/dist/types/src/util.d.ts.map +1 -0
  32. package/dist/types/tsconfig.tsbuildinfo +1 -1
  33. package/package.json +36 -26
  34. package/src/graph-builder.test.ts +569 -102
  35. package/src/graph-builder.ts +202 -74
  36. package/src/graph.test.ts +187 -52
  37. package/src/graph.ts +174 -98
  38. package/src/index.ts +1 -0
  39. package/src/node-matcher.ts +58 -28
  40. package/src/node.ts +46 -5
  41. package/src/stories/EchoGraph.stories.tsx +90 -61
  42. package/src/stories/Tree.tsx +1 -1
  43. package/src/testing/index.ts +5 -0
  44. package/src/testing/setup-graph-builder.ts +41 -0
  45. package/src/util.ts +95 -0
@@ -0,0 +1,1603 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/node.ts
8
+ var node_exports = {};
9
+ __export(node_exports, {
10
+ ActionGroupType: () => ActionGroupType,
11
+ ActionType: () => ActionType,
12
+ RootId: () => RootId,
13
+ RootType: () => RootType,
14
+ actionGroupSymbol: () => actionGroupSymbol,
15
+ actionRelation: () => actionRelation,
16
+ childRelation: () => childRelation,
17
+ isAction: () => isAction,
18
+ isActionGroup: () => isActionGroup,
19
+ isActionLike: () => isActionLike,
20
+ isGraphNode: () => isGraphNode,
21
+ make: () => make,
22
+ makeAction: () => makeAction,
23
+ makeActionGroup: () => makeActionGroup,
24
+ relation: () => relation
25
+ });
26
+ var RootId = "root";
27
+ var RootType = "org.dxos.type.graphRoot";
28
+ var ActionType = "org.dxos.type.graphAction";
29
+ var ActionGroupType = "org.dxos.type.graphActionGroup";
30
+ var relation = (kind, direction = "outbound") => ({
31
+ kind,
32
+ direction
33
+ });
34
+ var childRelation = (direction = "outbound") => relation("child", direction);
35
+ var actionRelation = (direction = "outbound") => relation("action", direction);
36
+ var isGraphNode = (data) => data && typeof data === "object" && "id" in data && "properties" in data && data.properties ? typeof data.properties === "object" && "data" in data : false;
37
+ var isAction = (data) => isGraphNode(data) ? typeof data.data === "function" && data.type === ActionType : false;
38
+ var actionGroupSymbol = /* @__PURE__ */ Symbol("ActionGroup");
39
+ var isActionGroup = (data) => isGraphNode(data) ? data.data === actionGroupSymbol && data.type === ActionGroupType : false;
40
+ var isActionLike = (data) => isAction(data) || isActionGroup(data);
41
+ var make = (arg) => arg;
42
+ var makeAction = (arg) => ({
43
+ ...arg,
44
+ type: ActionType
45
+ });
46
+ var makeActionGroup = (arg) => ({
47
+ ...arg,
48
+ type: ActionGroupType,
49
+ data: actionGroupSymbol
50
+ });
51
+
52
+ // src/util.ts
53
+ import { invariant } from "@dxos/invariant";
54
+ var __dxlog_file = "/__w/dxos/dxos/packages/sdk/app-graph/src/util.ts";
55
+ var PRIMARY = "";
56
+ var SECONDARY = "";
57
+ var PATH = "/";
58
+ var primaryKey = (...parts) => parts.join(PRIMARY);
59
+ var primaryParts = (key) => key.split(PRIMARY);
60
+ var secondaryKey = (...parts) => parts.join(SECONDARY);
61
+ var secondaryParts = (key) => key.split(SECONDARY);
62
+ var normalizeRelation = (relation2) => relation2 == null ? childRelation() : typeof relation2 === "string" ? relation(relation2) : relation2;
63
+ var shallowEqual = (a, b) => {
64
+ if (a === b) return true;
65
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
66
+ const keysA = Object.keys(a);
67
+ const keysB = Object.keys(b);
68
+ if (keysA.length !== keysB.length) {
69
+ return false;
70
+ }
71
+ return keysA.every((k) => a[k] === b[k]);
72
+ };
73
+ var nodeArgsUnchanged = (prev, next) => {
74
+ if (prev.length !== next.length) {
75
+ return false;
76
+ }
77
+ return prev.every((prevNode, idx) => {
78
+ const nextNode = next[idx];
79
+ return prevNode.id === nextNode.id && prevNode.type === nextNode.type && shallowEqual(prevNode.data, nextNode.data) && shallowEqual(prevNode.properties, nextNode.properties);
80
+ });
81
+ };
82
+ var qualifyId = (parentId, ...segmentIds) => [
83
+ parentId,
84
+ ...segmentIds
85
+ ].join(PATH);
86
+ var validateSegmentId = (id) => {
87
+ invariant(!id.includes(PATH), `Node segment ID must not contain '${PATH}': ${id}`, {
88
+ F: __dxlog_file,
89
+ L: 78,
90
+ S: void 0,
91
+ A: [
92
+ "!id.includes(PATH)",
93
+ "`Node segment ID must not contain '${PATH}': ${id}`"
94
+ ]
95
+ });
96
+ };
97
+ var getParentId = (qualifiedId) => {
98
+ const lastSlash = qualifiedId.lastIndexOf(PATH);
99
+ return lastSlash > 0 ? qualifiedId.slice(0, lastSlash) : void 0;
100
+ };
101
+ var getSegmentId = (qualifiedId) => {
102
+ return qualifiedId.split(PATH).pop() ?? qualifiedId;
103
+ };
104
+
105
+ // src/graph.ts
106
+ var graph_exports = {};
107
+ __export(graph_exports, {
108
+ GraphKind: () => GraphKind,
109
+ GraphTypeId: () => GraphTypeId,
110
+ addEdge: () => addEdge,
111
+ addEdges: () => addEdges,
112
+ addNode: () => addNode,
113
+ addNodes: () => addNodes,
114
+ expand: () => expand,
115
+ getActions: () => getActions,
116
+ getConnections: () => getConnections,
117
+ getEdges: () => getEdges,
118
+ getGraph: () => getGraph,
119
+ getNode: () => getNode,
120
+ getNodeOrThrow: () => getNodeOrThrow,
121
+ getPath: () => getPath,
122
+ getRoot: () => getRoot,
123
+ initialize: () => initialize,
124
+ make: () => make2,
125
+ relationFromKey: () => relationFromKey,
126
+ relationKey: () => relationKey,
127
+ removeEdge: () => removeEdge,
128
+ removeEdges: () => removeEdges,
129
+ removeNode: () => removeNode,
130
+ removeNodes: () => removeNodes,
131
+ sortEdges: () => sortEdges,
132
+ toJSON: () => toJSON,
133
+ traverse: () => traverse,
134
+ waitForPath: () => waitForPath
135
+ });
136
+ import { Atom, Registry } from "@effect-atom/atom-react";
137
+ import * as Function from "effect/Function";
138
+ import * as Option from "effect/Option";
139
+ import * as Pipeable from "effect/Pipeable";
140
+ import * as Record from "effect/Record";
141
+ import { Event, Trigger } from "@dxos/async";
142
+ import { todo } from "@dxos/debug";
143
+ import { invariant as invariant2 } from "@dxos/invariant";
144
+ import { log } from "@dxos/log";
145
+ import { isNonNullable } from "@dxos/util";
146
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/sdk/app-graph/src/graph.ts";
147
+ var graphSymbol = /* @__PURE__ */ Symbol("graph");
148
+ var getGraph = (node) => {
149
+ const graph = node[graphSymbol];
150
+ invariant2(graph, "Node is not associated with a graph.", {
151
+ F: __dxlog_file2,
152
+ L: 33,
153
+ S: void 0,
154
+ A: [
155
+ "graph",
156
+ "'Node is not associated with a graph.'"
157
+ ]
158
+ });
159
+ return graph;
160
+ };
161
+ var GraphTypeId = /* @__PURE__ */ Symbol.for("@dxos/app-graph/Graph");
162
+ var GraphKind = /* @__PURE__ */ Symbol.for("@dxos/app-graph/GraphKind");
163
+ var GraphImpl = class {
164
+ [GraphTypeId] = GraphTypeId;
165
+ [GraphKind] = "writable";
166
+ pipe() {
167
+ return Pipeable.pipeArguments(this, arguments);
168
+ }
169
+ onNodeChanged = new Event();
170
+ _onExpand;
171
+ _onInitialize;
172
+ _onRemoveNode;
173
+ _registry;
174
+ _expanded = Record.empty();
175
+ _pendingExpands = /* @__PURE__ */ new Set();
176
+ _initialized = Record.empty();
177
+ _initialEdges = Record.empty();
178
+ _initialNodes = Record.fromEntries([
179
+ [
180
+ RootId,
181
+ this._constructNode({
182
+ id: RootId,
183
+ type: RootType,
184
+ data: null,
185
+ properties: {}
186
+ })
187
+ ]
188
+ ]);
189
+ /** @internal */
190
+ _node = Atom.family((id) => {
191
+ const initial = Option.flatten(Record.get(this._initialNodes, id));
192
+ return Atom.make(initial).pipe(Atom.keepAlive, Atom.withLabel(`graph:node:${id}`));
193
+ });
194
+ _nodeOrThrow = Atom.family((id) => {
195
+ return Atom.make((get2) => {
196
+ const node = get2(this._node(id));
197
+ invariant2(Option.isSome(node), `Node not available: ${id}`, {
198
+ F: __dxlog_file2,
199
+ L: 172,
200
+ S: this,
201
+ A: [
202
+ "Option.isSome(node)",
203
+ "`Node not available: ${id}`"
204
+ ]
205
+ });
206
+ return node.value;
207
+ });
208
+ });
209
+ _edges = Atom.family((id) => {
210
+ const initial = Record.get(this._initialEdges, id).pipe(Option.getOrElse(() => ({})));
211
+ return Atom.make(initial).pipe(Atom.keepAlive, Atom.withLabel(`graph:edges:${id}`));
212
+ });
213
+ // NOTE: Currently the argument to the family needs to be referentially stable for the atom to be referentially stable.
214
+ // TODO(wittjosiah): Atom feature request, support for something akin to `ComplexMap` to allow for complex arguments.
215
+ _connections = Atom.family((key) => {
216
+ return Atom.make((get2) => {
217
+ if (!key || primaryParts(key).length < 2) {
218
+ return [];
219
+ }
220
+ const { id, relation: relation2 } = relationFromConnectionKey(key);
221
+ const edges = get2(this._edges(id));
222
+ return (edges[relationKey(relation2)] ?? []).map((id2) => get2(this._node(id2))).filter(Option.isSome).map((o) => o.value);
223
+ }).pipe(Atom.withLabel(`graph:connections:${key}`));
224
+ });
225
+ _actions = Atom.family((id) => {
226
+ return Atom.make((get2) => {
227
+ if (!id) {
228
+ return [];
229
+ }
230
+ return get2(this._connections(connectionKey(id, actionRelation())));
231
+ }).pipe(Atom.withLabel(`graph:actions:${id}`));
232
+ });
233
+ _json = Atom.family((id) => {
234
+ return Atom.make((get2) => {
235
+ const toJSON2 = (node, seen = []) => {
236
+ const nodes = get2(this._connections(connectionKey(node.id, "child")));
237
+ const obj = {
238
+ id: node.id,
239
+ type: node.type
240
+ };
241
+ if (node.properties.label) {
242
+ obj.label = node.properties.label;
243
+ }
244
+ if (nodes.length) {
245
+ obj.nodes = nodes.map((n) => {
246
+ const nextSeen = [
247
+ ...seen,
248
+ node.id
249
+ ];
250
+ return nextSeen.includes(n.id) ? void 0 : toJSON2(n, nextSeen);
251
+ }).filter(isNonNullable);
252
+ }
253
+ return obj;
254
+ };
255
+ const root = get2(this._nodeOrThrow(id));
256
+ return toJSON2(root);
257
+ }).pipe(Atom.withLabel(`graph:json:${id}`));
258
+ });
259
+ constructor({ registry, nodes, edges, onInitialize, onExpand, onRemoveNode } = {}) {
260
+ this._registry = registry ?? Registry.make();
261
+ this._onInitialize = onInitialize;
262
+ this._onExpand = onExpand;
263
+ this._onRemoveNode = onRemoveNode;
264
+ if (nodes) {
265
+ nodes.forEach((node) => {
266
+ Record.set(this._initialNodes, node.id, this._constructNode(node));
267
+ });
268
+ }
269
+ if (edges) {
270
+ Object.entries(edges).forEach(([source, edges2]) => {
271
+ Record.set(this._initialEdges, source, edges2);
272
+ });
273
+ }
274
+ }
275
+ json(id = RootId) {
276
+ return jsonImpl(this, id);
277
+ }
278
+ node(id) {
279
+ return nodeImpl(this, id);
280
+ }
281
+ nodeOrThrow(id) {
282
+ return nodeOrThrowImpl(this, id);
283
+ }
284
+ connections(id, relation2) {
285
+ return connectionsImpl(this, id, relation2);
286
+ }
287
+ actions(id) {
288
+ return actionsImpl(this, id);
289
+ }
290
+ edges(id) {
291
+ return edgesImpl(this, id);
292
+ }
293
+ /** @internal */
294
+ _constructNode(node) {
295
+ return Option.some({
296
+ [graphSymbol]: this,
297
+ data: null,
298
+ properties: {},
299
+ ...node
300
+ });
301
+ }
302
+ };
303
+ var getInternal = (graph) => {
304
+ return graph;
305
+ };
306
+ var toJSON = (graph, id = RootId) => {
307
+ const internal = getInternal(graph);
308
+ return internal._registry.get(internal._json(id));
309
+ };
310
+ var jsonImpl = (graph, id = RootId) => {
311
+ const internal = getInternal(graph);
312
+ return internal._json(id);
313
+ };
314
+ var nodeImpl = (graph, id) => {
315
+ const internal = getInternal(graph);
316
+ return internal._node(id);
317
+ };
318
+ var nodeOrThrowImpl = (graph, id) => {
319
+ const internal = getInternal(graph);
320
+ return internal._nodeOrThrow(id);
321
+ };
322
+ var connectionsImpl = (graph, id, relation2) => {
323
+ const internal = getInternal(graph);
324
+ return internal._connections(connectionKey(id, relation2));
325
+ };
326
+ var actionsImpl = (graph, id) => {
327
+ const internal = getInternal(graph);
328
+ return internal._actions(id);
329
+ };
330
+ var edgesImpl = (graph, id) => {
331
+ const internal = getInternal(graph);
332
+ return internal._edges(id);
333
+ };
334
+ var getNodeImpl = (graph, id) => {
335
+ const internal = getInternal(graph);
336
+ return internal._registry.get(nodeImpl(graph, id));
337
+ };
338
+ function getNode(graphOrId, id) {
339
+ if (typeof graphOrId === "string") {
340
+ const id2 = graphOrId;
341
+ return (graph) => getNodeImpl(graph, id2);
342
+ } else {
343
+ const graph = graphOrId;
344
+ return getNodeImpl(graph, id);
345
+ }
346
+ }
347
+ var getNodeOrThrowImpl = (graph, id) => {
348
+ const internal = getInternal(graph);
349
+ return internal._registry.get(nodeOrThrowImpl(graph, id));
350
+ };
351
+ function getNodeOrThrow(graphOrId, id) {
352
+ if (typeof graphOrId === "string") {
353
+ const id2 = graphOrId;
354
+ return (graph) => getNodeOrThrowImpl(graph, id2);
355
+ } else {
356
+ const graph = graphOrId;
357
+ return getNodeOrThrowImpl(graph, id);
358
+ }
359
+ }
360
+ function getRoot(graph) {
361
+ return getNodeOrThrowImpl(graph, RootId);
362
+ }
363
+ var getConnectionsImpl = (graph, id, relation2) => {
364
+ const internal = getInternal(graph);
365
+ return internal._registry.get(connectionsImpl(graph, id, relation2));
366
+ };
367
+ function getConnections(graphOrId, idOrRelation, relation2) {
368
+ if (typeof graphOrId === "string") {
369
+ const id = graphOrId;
370
+ const rel = idOrRelation;
371
+ return (graph) => getConnectionsImpl(graph, id, rel);
372
+ } else {
373
+ const graph = graphOrId;
374
+ const id = idOrRelation;
375
+ invariant2(relation2 !== void 0, "Relation is required.", {
376
+ F: __dxlog_file2,
377
+ L: 446,
378
+ S: this,
379
+ A: [
380
+ "relation !== undefined",
381
+ "'Relation is required.'"
382
+ ]
383
+ });
384
+ const rel = relation2;
385
+ return getConnectionsImpl(graph, id, rel);
386
+ }
387
+ }
388
+ var getActionsImpl = (graph, id) => {
389
+ const internal = getInternal(graph);
390
+ return internal._registry.get(actionsImpl(graph, id));
391
+ };
392
+ function getActions(graphOrId, id) {
393
+ if (typeof graphOrId === "string") {
394
+ const id2 = graphOrId;
395
+ return (graph) => getActionsImpl(graph, id2);
396
+ } else {
397
+ const graph = graphOrId;
398
+ return getActionsImpl(graph, id);
399
+ }
400
+ }
401
+ var getEdgesImpl = (graph, id) => {
402
+ const internal = getInternal(graph);
403
+ return internal._registry.get(edgesImpl(graph, id));
404
+ };
405
+ function getEdges(graphOrId, id) {
406
+ if (typeof graphOrId === "string") {
407
+ const id2 = graphOrId;
408
+ return (graph) => getEdgesImpl(graph, id2);
409
+ } else {
410
+ const graph = graphOrId;
411
+ return getEdgesImpl(graph, id);
412
+ }
413
+ }
414
+ var traverseImpl = (graph, options, path = []) => {
415
+ const { visitor, source = RootId, relation: relation2 } = options;
416
+ if (path.includes(source)) {
417
+ return;
418
+ }
419
+ const node = getNodeOrThrow(graph, source);
420
+ const shouldContinue = visitor(node, [
421
+ ...path,
422
+ source
423
+ ]);
424
+ if (shouldContinue === false) {
425
+ return;
426
+ }
427
+ const relations = Array.isArray(relation2) ? relation2 : [
428
+ relation2
429
+ ];
430
+ const seen = /* @__PURE__ */ new Set();
431
+ for (const rel of relations) {
432
+ for (const connected of getConnections(graph, source, rel)) {
433
+ if (!seen.has(connected.id)) {
434
+ seen.add(connected.id);
435
+ traverseImpl(graph, {
436
+ source: connected.id,
437
+ relation: relation2,
438
+ visitor
439
+ }, [
440
+ ...path,
441
+ source
442
+ ]);
443
+ }
444
+ }
445
+ }
446
+ };
447
+ function traverse(graphOrOptions, optionsOrPath, path) {
448
+ if (typeof graphOrOptions === "object" && "visitor" in graphOrOptions) {
449
+ const options = graphOrOptions;
450
+ const pathArg = Array.isArray(optionsOrPath) ? optionsOrPath : void 0;
451
+ return (graph) => traverseImpl(graph, options, pathArg);
452
+ } else {
453
+ const graph = graphOrOptions;
454
+ const options = optionsOrPath;
455
+ const pathArg = path ?? (Array.isArray(optionsOrPath) ? optionsOrPath : void 0);
456
+ return traverseImpl(graph, options, pathArg);
457
+ }
458
+ }
459
+ var getPathImpl = (graph, params) => {
460
+ return Function.pipe(getNode(graph, params.source ?? "root"), Option.flatMap((node) => {
461
+ let found = Option.none();
462
+ traverseImpl(graph, {
463
+ source: node.id,
464
+ relation: "child",
465
+ visitor: (node2, path) => {
466
+ if (Option.isSome(found)) {
467
+ return false;
468
+ }
469
+ if (node2.id === params.target) {
470
+ found = Option.some(path);
471
+ }
472
+ }
473
+ });
474
+ return found;
475
+ }));
476
+ };
477
+ function getPath(graphOrParams, params) {
478
+ if (params === void 0 && typeof graphOrParams === "object" && "target" in graphOrParams) {
479
+ const params2 = graphOrParams;
480
+ return (graph) => getPathImpl(graph, params2);
481
+ } else {
482
+ const graph = graphOrParams;
483
+ return getPathImpl(graph, params);
484
+ }
485
+ }
486
+ var waitForPathImpl = (graph, params, options) => {
487
+ const { timeout = 5e3, interval = 500 } = options ?? {};
488
+ const path = getPathImpl(graph, params);
489
+ if (Option.isSome(path)) {
490
+ return Promise.resolve(path.value);
491
+ }
492
+ const trigger = new Trigger();
493
+ const i = setInterval(() => {
494
+ const path2 = getPathImpl(graph, params);
495
+ if (Option.isSome(path2)) {
496
+ trigger.wake(path2.value);
497
+ }
498
+ }, interval);
499
+ return trigger.wait({
500
+ timeout
501
+ }).finally(() => clearInterval(i));
502
+ };
503
+ function waitForPath(graphOrParams, paramsOrOptions, options) {
504
+ if (typeof graphOrParams === "object" && "target" in graphOrParams) {
505
+ const params = graphOrParams;
506
+ const opts = typeof paramsOrOptions === "object" && !("target" in paramsOrOptions) ? paramsOrOptions : void 0;
507
+ return (graph) => waitForPathImpl(graph, params, opts);
508
+ } else {
509
+ const graph = graphOrParams;
510
+ const params = paramsOrOptions;
511
+ return waitForPathImpl(graph, params, options);
512
+ }
513
+ }
514
+ var initializeImpl = async (graph, id) => {
515
+ const internal = getInternal(graph);
516
+ const initialized = Record.get(internal._initialized, id).pipe(Option.getOrElse(() => false));
517
+ log("initialize", {
518
+ id,
519
+ initialized
520
+ }, {
521
+ F: __dxlog_file2,
522
+ L: 668,
523
+ S: void 0,
524
+ C: (f, a) => f(...a)
525
+ });
526
+ if (!initialized) {
527
+ Record.set(internal._initialized, id, true);
528
+ await internal._onInitialize?.(id);
529
+ }
530
+ return graph;
531
+ };
532
+ function initialize(graphOrId, id) {
533
+ if (typeof graphOrId === "string") {
534
+ const id2 = graphOrId;
535
+ return (graph) => initializeImpl(graph, id2);
536
+ } else {
537
+ const graph = graphOrId;
538
+ return initializeImpl(graph, id);
539
+ }
540
+ }
541
+ var expandImpl = (graph, id, relation2) => {
542
+ const internal = getInternal(graph);
543
+ const normalizedRelation = normalizeRelation(relation2);
544
+ const key = primaryKey(id, relationKey(normalizedRelation));
545
+ const nodeOpt = internal._registry.get(internal._node(id));
546
+ if (Option.isNone(nodeOpt)) {
547
+ internal._pendingExpands.add(key);
548
+ log("expand", {
549
+ key,
550
+ deferred: true
551
+ }, {
552
+ F: __dxlog_file2,
553
+ L: 714,
554
+ S: void 0,
555
+ C: (f, a) => f(...a)
556
+ });
557
+ return graph;
558
+ }
559
+ const expanded = Record.get(internal._expanded, key).pipe(Option.getOrElse(() => false));
560
+ log("expand", {
561
+ key,
562
+ expanded
563
+ }, {
564
+ F: __dxlog_file2,
565
+ L: 719,
566
+ S: void 0,
567
+ C: (f, a) => f(...a)
568
+ });
569
+ if (!expanded) {
570
+ Record.set(internal._expanded, key, true);
571
+ internal._onExpand?.(id, normalizedRelation);
572
+ }
573
+ return graph;
574
+ };
575
+ function expand(graphOrId, idOrRelation, relation2) {
576
+ if (typeof graphOrId === "string") {
577
+ const id = graphOrId;
578
+ const rel = idOrRelation;
579
+ return (graph) => expandImpl(graph, id, rel);
580
+ } else {
581
+ const graph = graphOrId;
582
+ const id = idOrRelation;
583
+ invariant2(relation2 !== void 0, "Relation is required.", {
584
+ F: __dxlog_file2,
585
+ L: 755,
586
+ S: this,
587
+ A: [
588
+ "relation !== undefined",
589
+ "'Relation is required.'"
590
+ ]
591
+ });
592
+ const rel = relation2;
593
+ return expandImpl(graph, id, rel);
594
+ }
595
+ }
596
+ var sortEdgesImpl = (graph, id, relation2, order) => {
597
+ const internal = getInternal(graph);
598
+ const edgesAtom = internal._edges(id);
599
+ const edges = internal._registry.get(edgesAtom);
600
+ const relationId = relationKey(relation2);
601
+ const current = edges[relationId] ?? [];
602
+ const unsorted = current.filter((id2) => !order.includes(id2));
603
+ const sorted = order.filter((id2) => current.includes(id2));
604
+ const newOrder = [
605
+ ...sorted,
606
+ ...unsorted
607
+ ];
608
+ if (newOrder.length === current.length && newOrder.every((id2, i) => id2 === current[i])) {
609
+ return graph;
610
+ }
611
+ internal._registry.set(edgesAtom, {
612
+ ...edges,
613
+ [relationId]: newOrder
614
+ });
615
+ return graph;
616
+ };
617
+ function sortEdges(graphOrId, idOrRelation, relationOrOrder, order) {
618
+ if (typeof graphOrId === "string") {
619
+ const id = graphOrId;
620
+ const relation2 = idOrRelation;
621
+ const order2 = relationOrOrder;
622
+ return (graph) => sortEdgesImpl(graph, id, relation2, order2);
623
+ } else {
624
+ const graph = graphOrId;
625
+ const id = idOrRelation;
626
+ const relation2 = relationOrOrder;
627
+ return sortEdgesImpl(graph, id, relation2, order);
628
+ }
629
+ }
630
+ var addNodesImpl = (graph, nodes) => {
631
+ Atom.batch(() => {
632
+ nodes.map((node) => addNodeImpl(graph, node));
633
+ });
634
+ return graph;
635
+ };
636
+ function addNodes(graphOrNodes, nodes) {
637
+ if (nodes === void 0) {
638
+ const nodes2 = graphOrNodes;
639
+ return (graph) => addNodesImpl(graph, nodes2);
640
+ } else {
641
+ const graph = graphOrNodes;
642
+ return addNodesImpl(graph, nodes);
643
+ }
644
+ }
645
+ var addNodeImpl = (graph, nodeArg) => {
646
+ const internal = getInternal(graph);
647
+ const { nodes, edges, id, type, data = null, properties = {}, ...rest } = nodeArg;
648
+ const nodeAtom = internal._node(id);
649
+ const existingNode = internal._registry.get(nodeAtom);
650
+ Option.match(existingNode, {
651
+ onSome: (existing) => {
652
+ const typeChanged = existing.type !== type;
653
+ const dataChanged = !shallowEqual(existing.data, data);
654
+ const propertiesChanged = Object.keys(properties).some((key) => existing.properties[key] !== properties[key]);
655
+ log("existing node", {
656
+ id,
657
+ typeChanged,
658
+ dataChanged,
659
+ propertiesChanged
660
+ }, {
661
+ F: __dxlog_file2,
662
+ L: 877,
663
+ S: void 0,
664
+ C: (f, a) => f(...a)
665
+ });
666
+ if (typeChanged || dataChanged || propertiesChanged) {
667
+ log("updating node", {
668
+ id,
669
+ type,
670
+ data,
671
+ properties
672
+ }, {
673
+ F: __dxlog_file2,
674
+ L: 884,
675
+ S: void 0,
676
+ C: (f, a) => f(...a)
677
+ });
678
+ const newNode = Option.some({
679
+ ...existing,
680
+ ...rest,
681
+ type,
682
+ data,
683
+ properties: {
684
+ ...existing.properties,
685
+ ...properties
686
+ }
687
+ });
688
+ internal._registry.set(nodeAtom, newNode);
689
+ graph.onNodeChanged.emit({
690
+ id,
691
+ node: newNode
692
+ });
693
+ }
694
+ },
695
+ onNone: () => {
696
+ log("new node", {
697
+ id,
698
+ type,
699
+ data,
700
+ properties
701
+ }, {
702
+ F: __dxlog_file2,
703
+ L: 897,
704
+ S: void 0,
705
+ C: (f, a) => f(...a)
706
+ });
707
+ const newNode = internal._constructNode({
708
+ id,
709
+ type,
710
+ data,
711
+ properties,
712
+ ...rest
713
+ });
714
+ internal._registry.set(nodeAtom, newNode);
715
+ graph.onNodeChanged.emit({
716
+ id,
717
+ node: newNode
718
+ });
719
+ const toApply = [
720
+ ...internal._pendingExpands
721
+ ].filter((k) => primaryParts(k)[0] === id);
722
+ for (const pendingKey of toApply) {
723
+ internal._pendingExpands.delete(pendingKey);
724
+ const relation2 = relationFromKey(primaryParts(pendingKey)[1]);
725
+ Record.set(internal._expanded, pendingKey, true);
726
+ internal._onExpand?.(id, relation2);
727
+ }
728
+ }
729
+ });
730
+ if (nodes) {
731
+ addNodesImpl(graph, nodes);
732
+ const _edges = nodes.map((node) => ({
733
+ source: id,
734
+ target: node.id,
735
+ relation: "child"
736
+ }));
737
+ addEdgesImpl(graph, _edges);
738
+ }
739
+ if (edges) {
740
+ todo();
741
+ }
742
+ return graph;
743
+ };
744
+ function addNode(graphOrNodeArg, nodeArg) {
745
+ if (nodeArg === void 0) {
746
+ const nodeArg2 = graphOrNodeArg;
747
+ return (graph) => addNodeImpl(graph, nodeArg2);
748
+ } else {
749
+ const graph = graphOrNodeArg;
750
+ return addNodeImpl(graph, nodeArg);
751
+ }
752
+ }
753
+ var removeNodesImpl = (graph, ids, edges = false) => {
754
+ Atom.batch(() => {
755
+ ids.map((id) => removeNodeImpl(graph, id, edges));
756
+ });
757
+ return graph;
758
+ };
759
+ function removeNodes(graphOrIds, idsOrEdges, edges) {
760
+ if (Array.isArray(graphOrIds)) {
761
+ const ids = graphOrIds;
762
+ const edgesArg = typeof idsOrEdges === "boolean" ? idsOrEdges : false;
763
+ return (graph) => removeNodesImpl(graph, ids, edgesArg);
764
+ } else {
765
+ const graph = graphOrIds;
766
+ const ids = idsOrEdges;
767
+ const edgesArg = edges ?? false;
768
+ return removeNodesImpl(graph, ids, edgesArg);
769
+ }
770
+ }
771
+ var removeNodeImpl = (graph, id, edges = false) => {
772
+ const internal = getInternal(graph);
773
+ const nodeAtom = internal._node(id);
774
+ internal._registry.set(nodeAtom, Option.none());
775
+ graph.onNodeChanged.emit({
776
+ id,
777
+ node: Option.none()
778
+ });
779
+ if (edges) {
780
+ const nodeEdges = internal._registry.get(internal._edges(id));
781
+ const edgesToRemove = [];
782
+ for (const [relationKeyValue, relatedIds] of Object.entries(nodeEdges)) {
783
+ const relation2 = relationFromKey(relationKeyValue);
784
+ const isInboundRelation = relation2.direction === "inbound";
785
+ for (const relatedId of relatedIds) {
786
+ if (isInboundRelation) {
787
+ edgesToRemove.push({
788
+ source: relatedId,
789
+ target: id,
790
+ relation: inverseRelation(relation2)
791
+ });
792
+ } else {
793
+ edgesToRemove.push({
794
+ source: id,
795
+ target: relatedId,
796
+ relation: relation2
797
+ });
798
+ }
799
+ }
800
+ }
801
+ removeEdgesImpl(graph, edgesToRemove);
802
+ }
803
+ internal._onRemoveNode?.(id);
804
+ return graph;
805
+ };
806
+ function removeNode(graphOrId, idOrEdges, edges) {
807
+ if (typeof graphOrId === "string") {
808
+ const id = graphOrId;
809
+ const edgesArg = typeof idOrEdges === "boolean" ? idOrEdges : false;
810
+ return (graph) => removeNodeImpl(graph, id, edgesArg);
811
+ } else {
812
+ const graph = graphOrId;
813
+ const id = idOrEdges;
814
+ const edgesArg = edges ?? false;
815
+ return removeNodeImpl(graph, id, edgesArg);
816
+ }
817
+ }
818
+ var addEdgesImpl = (graph, edges) => {
819
+ Atom.batch(() => {
820
+ edges.map((edge) => addEdgeImpl(graph, edge));
821
+ });
822
+ return graph;
823
+ };
824
+ function addEdges(graphOrEdges, edges) {
825
+ if (edges === void 0) {
826
+ const edges2 = graphOrEdges;
827
+ return (graph) => addEdgesImpl(graph, edges2);
828
+ } else {
829
+ const graph = graphOrEdges;
830
+ return addEdgesImpl(graph, edges);
831
+ }
832
+ }
833
+ var addEdgeImpl = (graph, edgeArg) => {
834
+ const relation2 = normalizeRelation(edgeArg.relation);
835
+ const relationId = relationKey(relation2);
836
+ const inverse = inverseRelation(relation2);
837
+ const inverseId = relationKey(inverse);
838
+ const internal = getInternal(graph);
839
+ const sourceAtom = internal._edges(edgeArg.source);
840
+ const source = internal._registry.get(sourceAtom);
841
+ const sourceList = source[relationId] ?? [];
842
+ if (!sourceList.includes(edgeArg.target)) {
843
+ log("add edge", {
844
+ source: edgeArg.source,
845
+ target: edgeArg.target,
846
+ relation: relationId
847
+ }, {
848
+ F: __dxlog_file2,
849
+ L: 1080,
850
+ S: void 0,
851
+ C: (f, a) => f(...a)
852
+ });
853
+ internal._registry.set(sourceAtom, {
854
+ ...source,
855
+ [relationId]: [
856
+ ...sourceList,
857
+ edgeArg.target
858
+ ]
859
+ });
860
+ }
861
+ const targetAtom = internal._edges(edgeArg.target);
862
+ const target = internal._registry.get(targetAtom);
863
+ const targetList = target[inverseId] ?? [];
864
+ if (!targetList.includes(edgeArg.source)) {
865
+ log("add inverse edge", {
866
+ source: edgeArg.source,
867
+ target: edgeArg.target,
868
+ relation: inverseId
869
+ }, {
870
+ F: __dxlog_file2,
871
+ L: 1088,
872
+ S: void 0,
873
+ C: (f, a) => f(...a)
874
+ });
875
+ internal._registry.set(targetAtom, {
876
+ ...target,
877
+ [inverseId]: [
878
+ ...targetList,
879
+ edgeArg.source
880
+ ]
881
+ });
882
+ }
883
+ return graph;
884
+ };
885
+ function addEdge(graphOrEdgeArg, edgeArg) {
886
+ if (edgeArg === void 0) {
887
+ const edgeArg2 = graphOrEdgeArg;
888
+ return (graph) => addEdgeImpl(graph, edgeArg2);
889
+ } else {
890
+ const graph = graphOrEdgeArg;
891
+ return addEdgeImpl(graph, edgeArg);
892
+ }
893
+ }
894
+ var removeEdgesImpl = (graph, edges, removeOrphans = false) => {
895
+ Atom.batch(() => {
896
+ edges.map((edge) => removeEdgeImpl(graph, edge, removeOrphans));
897
+ });
898
+ return graph;
899
+ };
900
+ function removeEdges(graphOrEdges, edgesOrRemoveOrphans, removeOrphans) {
901
+ if (Array.isArray(graphOrEdges)) {
902
+ const edges = graphOrEdges;
903
+ const removeOrphansArg = typeof edgesOrRemoveOrphans === "boolean" ? edgesOrRemoveOrphans : false;
904
+ return (graph) => removeEdgesImpl(graph, edges, removeOrphansArg);
905
+ } else {
906
+ const graph = graphOrEdges;
907
+ const edges = edgesOrRemoveOrphans;
908
+ const removeOrphansArg = removeOrphans ?? false;
909
+ return removeEdgesImpl(graph, edges, removeOrphansArg);
910
+ }
911
+ }
912
+ var removeEdgeImpl = (graph, edgeArg, removeOrphans = false) => {
913
+ const relation2 = normalizeRelation(edgeArg.relation);
914
+ const relationId = relationKey(relation2);
915
+ const inverse = inverseRelation(relation2);
916
+ const inverseId = relationKey(inverse);
917
+ const internal = getInternal(graph);
918
+ const sourceAtom = internal._edges(edgeArg.source);
919
+ const source = internal._registry.get(sourceAtom);
920
+ const sourceList = source[relationId] ?? [];
921
+ if (sourceList.includes(edgeArg.target)) {
922
+ internal._registry.set(sourceAtom, {
923
+ ...source,
924
+ [relationId]: sourceList.filter((id) => id !== edgeArg.target)
925
+ });
926
+ }
927
+ const targetAtom = internal._edges(edgeArg.target);
928
+ const target = internal._registry.get(targetAtom);
929
+ const targetList = target[inverseId] ?? [];
930
+ if (targetList.includes(edgeArg.source)) {
931
+ internal._registry.set(targetAtom, {
932
+ ...target,
933
+ [inverseId]: targetList.filter((id) => id !== edgeArg.source)
934
+ });
935
+ }
936
+ if (removeOrphans) {
937
+ const sourceAfter = internal._registry.get(sourceAtom);
938
+ const targetAfter = internal._registry.get(targetAtom);
939
+ const isEmpty = (edges) => Object.values(edges).every((ids) => ids.length === 0);
940
+ if (isEmpty(sourceAfter) && edgeArg.source !== RootId) {
941
+ removeNodesImpl(graph, [
942
+ edgeArg.source
943
+ ]);
944
+ }
945
+ if (isEmpty(targetAfter) && edgeArg.target !== RootId) {
946
+ removeNodesImpl(graph, [
947
+ edgeArg.target
948
+ ]);
949
+ }
950
+ }
951
+ return graph;
952
+ };
953
+ function removeEdge(graphOrEdgeArg, edgeArgOrRemoveOrphans, removeOrphans) {
954
+ if (edgeArgOrRemoveOrphans === void 0 || typeof edgeArgOrRemoveOrphans === "boolean" || "source" in graphOrEdgeArg) {
955
+ const edgeArg = graphOrEdgeArg;
956
+ const removeOrphansArg = typeof edgeArgOrRemoveOrphans === "boolean" ? edgeArgOrRemoveOrphans : false;
957
+ return (graph) => removeEdgeImpl(graph, edgeArg, removeOrphansArg);
958
+ } else {
959
+ const graph = graphOrEdgeArg;
960
+ const edgeArg = edgeArgOrRemoveOrphans;
961
+ const removeOrphansArg = removeOrphans ?? false;
962
+ return removeEdgeImpl(graph, edgeArg, removeOrphansArg);
963
+ }
964
+ }
965
+ var make2 = (params) => {
966
+ return new GraphImpl(params);
967
+ };
968
+ var relationKey = (relation2) => {
969
+ const normalized = normalizeRelation(relation2);
970
+ return secondaryKey(normalized.kind, normalized.direction);
971
+ };
972
+ var relationFromKey = (encoded) => {
973
+ const parts = secondaryParts(encoded);
974
+ invariant2(parts.length === 2 && parts[0].length > 0 && parts[1].length > 0, `Invalid relation key: ${encoded}`, {
975
+ F: __dxlog_file2,
976
+ L: 1233,
977
+ S: void 0,
978
+ A: [
979
+ "parts.length === 2 && parts[0].length > 0 && parts[1].length > 0",
980
+ "`Invalid relation key: ${encoded}`"
981
+ ]
982
+ });
983
+ const [kind, directionRaw] = parts;
984
+ invariant2(directionRaw === "outbound" || directionRaw === "inbound", `Invalid relation direction: ${directionRaw}`, {
985
+ F: __dxlog_file2,
986
+ L: 1235,
987
+ S: void 0,
988
+ A: [
989
+ "directionRaw === 'outbound' || directionRaw === 'inbound'",
990
+ "`Invalid relation direction: ${directionRaw}`"
991
+ ]
992
+ });
993
+ return relation(kind, directionRaw);
994
+ };
995
+ var connectionKey = (id, relation2) => primaryKey(id, relationKey(relation2));
996
+ var relationFromConnectionKey = (key) => {
997
+ const [id, encodedRelation] = primaryParts(key);
998
+ invariant2(id && encodedRelation, `Invalid connection key: ${key}`, {
999
+ F: __dxlog_file2,
1000
+ L: 1243,
1001
+ S: void 0,
1002
+ A: [
1003
+ "id && encodedRelation",
1004
+ "`Invalid connection key: ${key}`"
1005
+ ]
1006
+ });
1007
+ return {
1008
+ id,
1009
+ relation: relationFromKey(encodedRelation)
1010
+ };
1011
+ };
1012
+ var inverseRelation = (relation2) => {
1013
+ const normalized = normalizeRelation(relation2);
1014
+ return relation(normalized.kind, normalized.direction === "outbound" ? "inbound" : "outbound");
1015
+ };
1016
+
1017
+ // src/node-matcher.ts
1018
+ var node_matcher_exports = {};
1019
+ __export(node_matcher_exports, {
1020
+ whenAll: () => whenAll,
1021
+ whenAny: () => whenAny,
1022
+ whenEchoObject: () => whenEchoObject,
1023
+ whenEchoObjectMatches: () => whenEchoObjectMatches,
1024
+ whenEchoType: () => whenEchoType,
1025
+ whenEchoTypeMatches: () => whenEchoTypeMatches,
1026
+ whenId: () => whenId,
1027
+ whenNodeType: () => whenNodeType,
1028
+ whenNot: () => whenNot,
1029
+ whenRoot: () => whenRoot
1030
+ });
1031
+ import * as Option2 from "effect/Option";
1032
+ import { Obj } from "@dxos/echo";
1033
+ var whenRoot = (node) => node.id === RootId ? Option2.some(node) : Option2.none();
1034
+ var whenId = (id) => (node) => node.id === id ? Option2.some(node) : Option2.none();
1035
+ var whenNodeType = (type) => (node) => node.type === type ? Option2.some(node) : Option2.none();
1036
+ var whenEchoType = (type) => (node) => Obj.instanceOf(type, node.data) ? Option2.some(node.data) : Option2.none();
1037
+ var whenEchoObject = (node) => Obj.isObject(node.data) ? Option2.some(node.data) : Option2.none();
1038
+ var whenAll = (...matchers) => (node) => {
1039
+ let first = Option2.none();
1040
+ for (const candidate of matchers) {
1041
+ const result = candidate(node);
1042
+ if (Option2.isNone(result)) {
1043
+ return Option2.none();
1044
+ }
1045
+ if (Option2.isNone(first)) {
1046
+ first = result;
1047
+ }
1048
+ }
1049
+ return first;
1050
+ };
1051
+ var whenAny = (...matchers) => (node) => {
1052
+ for (const candidate of matchers) {
1053
+ const result = candidate(node);
1054
+ if (Option2.isSome(result)) {
1055
+ return result;
1056
+ }
1057
+ }
1058
+ return Option2.none();
1059
+ };
1060
+ var whenEchoTypeMatches = (type) => (node) => Obj.instanceOf(type, node.data) ? Option2.some(node) : Option2.none();
1061
+ var whenEchoObjectMatches = (node) => Obj.isObject(node.data) ? Option2.some(node) : Option2.none();
1062
+ var whenNot = (matcher) => (node) => Option2.isNone(matcher(node)) ? Option2.some(node) : Option2.none();
1063
+
1064
+ // src/graph-builder.ts
1065
+ var graph_builder_exports = {};
1066
+ __export(graph_builder_exports, {
1067
+ GraphBuilderTypeId: () => GraphBuilderTypeId,
1068
+ addExtension: () => addExtension,
1069
+ createConnector: () => createConnector,
1070
+ createExtension: () => createExtension,
1071
+ createExtensionRaw: () => createExtensionRaw,
1072
+ createTypeExtension: () => createTypeExtension,
1073
+ destroy: () => destroy,
1074
+ explore: () => explore,
1075
+ flattenExtensions: () => flattenExtensions,
1076
+ flush: () => flush,
1077
+ from: () => from,
1078
+ make: () => make3,
1079
+ removeExtension: () => removeExtension
1080
+ });
1081
+ import { Atom as Atom2, Registry as Registry2 } from "@effect-atom/atom-react";
1082
+ import * as Array2 from "effect/Array";
1083
+ import * as Effect from "effect/Effect";
1084
+ import * as Function2 from "effect/Function";
1085
+ import * as Option3 from "effect/Option";
1086
+ import * as Pipeable2 from "effect/Pipeable";
1087
+ import * as Record2 from "effect/Record";
1088
+ import { scheduleTask, yieldOrContinue } from "main-thread-scheduling";
1089
+ import { log as log2 } from "@dxos/log";
1090
+ import { byPosition, getDebugName, isNonNullable as isNonNullable2 } from "@dxos/util";
1091
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/sdk/app-graph/src/graph-builder.ts";
1092
+ var GraphBuilderTypeId = /* @__PURE__ */ Symbol.for("@dxos/app-graph/GraphBuilder");
1093
+ var GraphBuilderImpl = class {
1094
+ [GraphBuilderTypeId] = GraphBuilderTypeId;
1095
+ pipe() {
1096
+ return Pipeable2.pipeArguments(this, arguments);
1097
+ }
1098
+ // TODO(wittjosiah): Use Context.
1099
+ /** Active subscriptions keyed by composite ID, cleaned up on node removal. */
1100
+ _subscriptions = /* @__PURE__ */ new Map();
1101
+ /** Connector updates pending flush, keyed by connector key. */
1102
+ _dirtyConnectors = /* @__PURE__ */ new Map();
1103
+ /** Last-flushed node IDs per connector key, used for edge removal on update. */
1104
+ _connectorPrevious = /* @__PURE__ */ new Map();
1105
+ /** Last-flushed node args per connector key, used for change detection. */
1106
+ _connectorPreviousArgs = /* @__PURE__ */ new Map();
1107
+ /** Whether a dirty-flush task is already scheduled. */
1108
+ _flushScheduled = false;
1109
+ /** Resolves when the current flush completes. */
1110
+ _flushPromise = Promise.resolve();
1111
+ /** Registered builder extensions keyed by extension ID. */
1112
+ _extensions = Atom2.make(Record2.empty()).pipe(Atom2.keepAlive, Atom2.withLabel("graph-builder:extensions"));
1113
+ /** Triggers signalling that a node's resolver has fired at least once. */
1114
+ _initialized = {};
1115
+ /** Shared atom registry for reactive subscriptions. */
1116
+ _registry;
1117
+ /** Backing graph with internal accessors for node atoms and construction. */
1118
+ _graph;
1119
+ constructor({ registry, ...params } = {}) {
1120
+ this._registry = registry ?? Registry2.make();
1121
+ const graph = make2({
1122
+ ...params,
1123
+ registry: this._registry,
1124
+ onExpand: (id, relation2) => this._onExpand(id, relation2),
1125
+ onInitialize: (id) => this._onInitialize(id),
1126
+ onRemoveNode: (id) => this._onRemoveNode(id)
1127
+ });
1128
+ this._graph = graph;
1129
+ }
1130
+ get graph() {
1131
+ return this._graph;
1132
+ }
1133
+ get extensions() {
1134
+ return this._extensions;
1135
+ }
1136
+ /** Apply a set of node changes for a single connector key. */
1137
+ _applyConnectorUpdate(key, nodes, previous) {
1138
+ const { id, relation: relation2 } = relationFromConnectorKey(key);
1139
+ const ids = nodes.map((node) => node.id);
1140
+ const removed = previous.filter((pid) => !ids.includes(pid));
1141
+ this._connectorPrevious.set(key, ids);
1142
+ this._connectorPreviousArgs.set(key, nodes);
1143
+ removeEdges(this._graph, removed.map((target) => ({
1144
+ source: id,
1145
+ target,
1146
+ relation: relation2
1147
+ })), true);
1148
+ addNodes(this._graph, nodes);
1149
+ addEdges(this._graph, nodes.map((node) => ({
1150
+ source: id,
1151
+ target: node.id,
1152
+ relation: relation2
1153
+ })));
1154
+ if (ids.length > 0) {
1155
+ const sortedIds = [
1156
+ ...nodes
1157
+ ].sort((a, b) => byPosition(a.properties ?? {}, b.properties ?? {})).map((n) => n.id);
1158
+ sortEdges(this._graph, id, relation2, sortedIds);
1159
+ }
1160
+ }
1161
+ _scheduleDirtyFlush() {
1162
+ if (!this._flushScheduled) {
1163
+ this._flushScheduled = true;
1164
+ this._flushPromise = scheduleTask(() => {
1165
+ this._flushScheduled = false;
1166
+ while (this._dirtyConnectors.size > 0) {
1167
+ const entries = [
1168
+ ...this._dirtyConnectors.entries()
1169
+ ];
1170
+ this._dirtyConnectors.clear();
1171
+ Atom2.batch(() => {
1172
+ for (const [key, { nodes, previous }] of entries) {
1173
+ this._applyConnectorUpdate(key, nodes, previous);
1174
+ }
1175
+ });
1176
+ }
1177
+ }, {
1178
+ strategy: "smooth"
1179
+ });
1180
+ }
1181
+ }
1182
+ _resolvers = Atom2.family((id) => {
1183
+ return Atom2.make((get2) => {
1184
+ return Function2.pipe(get2(this._extensions), Record2.values, Array2.sortBy(byPosition), Array2.map(({ resolver }) => resolver), Array2.filter(isNonNullable2), Array2.map((resolver) => get2(resolver(id))), Array2.filter(isNonNullable2), Array2.head);
1185
+ });
1186
+ });
1187
+ _connectors = Atom2.family((key) => {
1188
+ return Atom2.make((get2) => {
1189
+ const { id, relation: relation2 } = relationFromConnectorKey(key);
1190
+ const node = this._graph.node(id);
1191
+ const sourceNode = Option3.getOrElse(get2(node), () => void 0);
1192
+ if (!sourceNode) {
1193
+ return [];
1194
+ }
1195
+ const extensions = Function2.pipe(get2(this._extensions), Record2.values, Array2.sortBy(byPosition), Array2.filter((ext) => relationKey(ext.relation ?? "child") === relationKey(relation2) && ext.connector != null));
1196
+ const nodes = [];
1197
+ for (const ext of extensions) {
1198
+ const result = get2(ext.connector(node));
1199
+ nodes.push(...result);
1200
+ }
1201
+ return nodes;
1202
+ }).pipe(Atom2.withLabel(`graph-builder:connectors:${key}`));
1203
+ });
1204
+ _onExpand(id, relation2) {
1205
+ log2("onExpand", {
1206
+ id,
1207
+ relation: relation2,
1208
+ registry: getDebugName(this._registry)
1209
+ }, {
1210
+ F: __dxlog_file3,
1211
+ L: 269,
1212
+ S: this,
1213
+ C: (f, a) => f(...a)
1214
+ });
1215
+ this._expandRelation(id, relation2);
1216
+ if (relation2.kind === "child" && relation2.direction === "outbound") {
1217
+ expand(this._graph, id, "action");
1218
+ }
1219
+ }
1220
+ _expandRelation(id, relation2) {
1221
+ const key = connectorKey(id, relation2);
1222
+ const connectors = this._connectors(key);
1223
+ const cancel = this._registry.subscribe(connectors, (rawNodes) => {
1224
+ const nodes = qualifyNodeArgs(id)(rawNodes);
1225
+ const previous = this._connectorPrevious.get(key) ?? [];
1226
+ const ids = nodes.map((n) => n.id);
1227
+ if (ids.length === previous.length && ids.every((nodeId, idx) => nodeId === previous[idx])) {
1228
+ const prevArgs = this._connectorPreviousArgs.get(key);
1229
+ if (prevArgs && nodeArgsUnchanged(prevArgs, nodes)) {
1230
+ return;
1231
+ }
1232
+ }
1233
+ log2("update", {
1234
+ id,
1235
+ relation: relation2,
1236
+ ids
1237
+ }, {
1238
+ F: __dxlog_file3,
1239
+ L: 296,
1240
+ S: this,
1241
+ C: (f, a) => f(...a)
1242
+ });
1243
+ this._dirtyConnectors.set(key, {
1244
+ nodes,
1245
+ previous
1246
+ });
1247
+ this._scheduleDirtyFlush();
1248
+ }, {
1249
+ immediate: true
1250
+ });
1251
+ this._subscriptions.set(subscriptionKey(id, "expand", key), cancel);
1252
+ }
1253
+ async _onInitialize(id) {
1254
+ log2("onInitialize", {
1255
+ id
1256
+ }, {
1257
+ F: __dxlog_file3,
1258
+ L: 307,
1259
+ S: this,
1260
+ C: (f, a) => f(...a)
1261
+ });
1262
+ const resolver = this._resolvers(id);
1263
+ const cancel = this._registry.subscribe(resolver, (node) => {
1264
+ const trigger = this._initialized[id];
1265
+ const connectorOwned = [
1266
+ ...this._connectorPrevious.values()
1267
+ ].some((ids) => ids.includes(id));
1268
+ Option3.match(node, {
1269
+ onSome: (node2) => {
1270
+ if (!connectorOwned) {
1271
+ addNodes(this._graph, [
1272
+ node2
1273
+ ]);
1274
+ const parentId = getParentId(id);
1275
+ if (parentId) {
1276
+ addEdges(this._graph, [
1277
+ {
1278
+ source: parentId,
1279
+ target: id,
1280
+ relation: "child"
1281
+ }
1282
+ ]);
1283
+ }
1284
+ }
1285
+ trigger?.wake();
1286
+ },
1287
+ onNone: () => {
1288
+ trigger?.wake();
1289
+ if (!connectorOwned) {
1290
+ removeNodes(this._graph, [
1291
+ id
1292
+ ]);
1293
+ }
1294
+ }
1295
+ });
1296
+ }, {
1297
+ immediate: true
1298
+ });
1299
+ this._subscriptions.set(subscriptionKey(id, "init"), cancel);
1300
+ }
1301
+ _onRemoveNode(id) {
1302
+ for (const [key, cleanup] of this._subscriptions) {
1303
+ if (primaryParts(key)[0] === id) {
1304
+ cleanup();
1305
+ this._subscriptions.delete(key);
1306
+ }
1307
+ }
1308
+ }
1309
+ };
1310
+ var make3 = (params) => {
1311
+ return new GraphBuilderImpl(params);
1312
+ };
1313
+ var from = (pickle, registry) => {
1314
+ if (!pickle) {
1315
+ return make3({
1316
+ registry
1317
+ });
1318
+ }
1319
+ const { nodes, edges } = JSON.parse(pickle);
1320
+ return make3({
1321
+ nodes,
1322
+ edges,
1323
+ registry
1324
+ });
1325
+ };
1326
+ var addExtensionImpl = (builder, extensions) => {
1327
+ const internal = builder;
1328
+ flattenExtensions(extensions).forEach((extension) => {
1329
+ const extensions2 = internal._registry.get(internal._extensions);
1330
+ internal._registry.set(internal._extensions, Record2.set(extensions2, extension.id, extension));
1331
+ });
1332
+ return builder;
1333
+ };
1334
+ function addExtension(builderOrExtensions, extensions) {
1335
+ if (extensions === void 0) {
1336
+ const extensions2 = builderOrExtensions;
1337
+ return (builder) => addExtensionImpl(builder, extensions2);
1338
+ } else {
1339
+ const builder = builderOrExtensions;
1340
+ return addExtensionImpl(builder, extensions);
1341
+ }
1342
+ }
1343
+ var removeExtensionImpl = (builder, id) => {
1344
+ const internal = builder;
1345
+ const extensions = internal._registry.get(internal._extensions);
1346
+ internal._registry.set(internal._extensions, Record2.remove(extensions, id));
1347
+ return builder;
1348
+ };
1349
+ function removeExtension(builderOrId, id) {
1350
+ if (typeof builderOrId === "string") {
1351
+ const id2 = builderOrId;
1352
+ return (builder) => removeExtensionImpl(builder, id2);
1353
+ } else {
1354
+ const builder = builderOrId;
1355
+ return removeExtensionImpl(builder, id);
1356
+ }
1357
+ }
1358
+ var exploreImpl = async (builder, options, path = []) => {
1359
+ const internal = builder;
1360
+ const { registry = Registry2.make(), source = RootId, relation: relation2, visitor } = options;
1361
+ if (path.includes(source)) {
1362
+ return;
1363
+ }
1364
+ await yieldOrContinue("idle");
1365
+ const node = registry.get(internal._graph.nodeOrThrow(source));
1366
+ const shouldContinue = await visitor(node, [
1367
+ ...path,
1368
+ node.id
1369
+ ]);
1370
+ if (shouldContinue === false) {
1371
+ return;
1372
+ }
1373
+ const nodes = Function2.pipe(internal._registry.get(internal._extensions), Record2.values, Array2.map((extension) => extension.connector), Array2.filter(isNonNullable2), Array2.flatMap((connector) => registry.get(connector(internal._graph.node(source)))), qualifyNodeArgs(source));
1374
+ await Promise.all(nodes.map((nodeArg) => {
1375
+ registry.set(internal._graph._node(nodeArg.id), internal._graph._constructNode(nodeArg));
1376
+ return exploreImpl(builder, {
1377
+ registry,
1378
+ source: nodeArg.id,
1379
+ relation: relation2,
1380
+ visitor
1381
+ }, [
1382
+ ...path,
1383
+ node.id
1384
+ ]);
1385
+ }));
1386
+ if (registry !== internal._registry) {
1387
+ registry.reset();
1388
+ registry.dispose();
1389
+ }
1390
+ };
1391
+ function explore(builderOrOptions, optionsOrPath, path) {
1392
+ if (typeof builderOrOptions === "object" && "visitor" in builderOrOptions) {
1393
+ const options = builderOrOptions;
1394
+ const path2 = Array2.isArray(optionsOrPath) ? optionsOrPath : void 0;
1395
+ return (builder) => exploreImpl(builder, options, path2);
1396
+ } else {
1397
+ const builder = builderOrOptions;
1398
+ const options = optionsOrPath;
1399
+ const pathArg = path ?? (Array2.isArray(optionsOrPath) ? optionsOrPath : void 0);
1400
+ return exploreImpl(builder, options, pathArg);
1401
+ }
1402
+ }
1403
+ var destroyImpl = (builder) => {
1404
+ const internal = builder;
1405
+ internal._subscriptions.forEach((unsubscribe) => unsubscribe());
1406
+ internal._subscriptions.clear();
1407
+ };
1408
+ function destroy(builder) {
1409
+ if (builder === void 0) {
1410
+ return (builder2) => destroyImpl(builder2);
1411
+ } else {
1412
+ return destroyImpl(builder);
1413
+ }
1414
+ }
1415
+ var flush = (builder) => {
1416
+ return builder._flushPromise;
1417
+ };
1418
+ var createExtensionRaw = (extension) => {
1419
+ const { id, position = "static", relation: relation2 = "child", resolver: _resolver, connector: _connector, actions: _actions, actionGroups: _actionGroups } = extension;
1420
+ const normalizedRelation = normalizeRelation(relation2);
1421
+ const getId = (key) => `${id}/${key}`;
1422
+ const resolver = _resolver && Atom2.family((id2) => _resolver(id2).pipe(Atom2.withLabel(`graph-builder:_resolver:${id2}`)));
1423
+ const connector = _connector && Atom2.family((node) => _connector(node).pipe(Atom2.withLabel(`graph-builder:_connector:${id}`)));
1424
+ const actionGroups = _actionGroups && Atom2.family((node) => _actionGroups(node).pipe(Atom2.withLabel(`graph-builder:_actionGroups:${id}`)));
1425
+ const actions = _actions && Atom2.family((node) => _actions(node).pipe(Atom2.withLabel(`graph-builder:_actions:${id}`)));
1426
+ return [
1427
+ resolver ? {
1428
+ id: getId("resolver"),
1429
+ position,
1430
+ resolver
1431
+ } : void 0,
1432
+ connector ? {
1433
+ id: getId("connector"),
1434
+ position,
1435
+ relation: normalizedRelation,
1436
+ connector: Atom2.family((node) => Atom2.make((get2) => {
1437
+ try {
1438
+ return get2(connector(node));
1439
+ } catch (error) {
1440
+ log2.warn("Error in connector", {
1441
+ id: getId("connector"),
1442
+ node,
1443
+ error
1444
+ }, {
1445
+ F: __dxlog_file3,
1446
+ L: 609,
1447
+ S: void 0,
1448
+ C: (f, a) => f(...a)
1449
+ });
1450
+ return [];
1451
+ }
1452
+ }).pipe(Atom2.withLabel(`graph-builder:connector:${id}`)))
1453
+ } : void 0,
1454
+ actionGroups ? {
1455
+ id: getId("actionGroups"),
1456
+ position,
1457
+ relation: actionRelation(),
1458
+ connector: Atom2.family((node) => Atom2.make((get2) => {
1459
+ try {
1460
+ return get2(actionGroups(node)).map((arg) => ({
1461
+ ...arg,
1462
+ data: actionGroupSymbol,
1463
+ type: ActionGroupType
1464
+ }));
1465
+ } catch (error) {
1466
+ log2.warn("Error in actionGroups", {
1467
+ id: getId("actionGroups"),
1468
+ node,
1469
+ error
1470
+ }, {
1471
+ F: __dxlog_file3,
1472
+ L: 630,
1473
+ S: void 0,
1474
+ C: (f, a) => f(...a)
1475
+ });
1476
+ return [];
1477
+ }
1478
+ }).pipe(Atom2.withLabel(`graph-builder:connector:actionGroups:${id}`)))
1479
+ } : void 0,
1480
+ actions ? {
1481
+ id: getId("actions"),
1482
+ position,
1483
+ relation: actionRelation(),
1484
+ connector: Atom2.family((node) => Atom2.make((get2) => {
1485
+ try {
1486
+ return get2(actions(node)).map((arg) => ({
1487
+ ...arg,
1488
+ type: ActionType
1489
+ }));
1490
+ } catch (error) {
1491
+ log2.warn("Error in actions", {
1492
+ id: getId("actions"),
1493
+ node,
1494
+ error
1495
+ }, {
1496
+ F: __dxlog_file3,
1497
+ L: 647,
1498
+ S: void 0,
1499
+ C: (f, a) => f(...a)
1500
+ });
1501
+ return [];
1502
+ }
1503
+ }).pipe(Atom2.withLabel(`graph-builder:connector:actions:${id}`)))
1504
+ } : void 0
1505
+ ].filter(isNonNullable2);
1506
+ };
1507
+ var runEffectSyncWithFallback = (effect, context2, extensionId, fallback) => {
1508
+ return Effect.runSync(effect.pipe(Effect.provide(context2), Effect.catchAll((error) => {
1509
+ log2.warn("Extension failed", {
1510
+ extension: extensionId,
1511
+ error
1512
+ }, {
1513
+ F: __dxlog_file3,
1514
+ L: 690,
1515
+ S: void 0,
1516
+ C: (f, a) => f(...a)
1517
+ });
1518
+ return Effect.succeed(fallback);
1519
+ })));
1520
+ };
1521
+ var createExtension = (options) => Effect.map(Effect.context(), (context2) => {
1522
+ const { id, match: match3, actions, connector, resolver, relation: relation2, position } = options;
1523
+ const connectorExtension = connector ? createConnectorWithRuntime(id, match3, connector, context2) : void 0;
1524
+ const actionsExtension = actions ? (node) => Atom2.make((get2) => Function2.pipe(get2(node), Option3.flatMap(match3), Option3.map((matched) => runEffectSyncWithFallback(actions(matched, get2), context2, id, []).map((action) => ({
1525
+ ...action,
1526
+ // Attach captured context for action execution.
1527
+ _actionContext: context2
1528
+ }))), Option3.getOrElse(() => []))) : void 0;
1529
+ const resolverExtension = resolver ? (nodeId) => Atom2.make((get2) => runEffectSyncWithFallback(resolver(nodeId, get2), context2, id, null) ?? null) : void 0;
1530
+ return createExtensionRaw({
1531
+ id,
1532
+ relation: relation2,
1533
+ position,
1534
+ connector: connectorExtension,
1535
+ actions: actionsExtension,
1536
+ resolver: resolverExtension
1537
+ });
1538
+ });
1539
+ var createConnector = (matcher, factory) => {
1540
+ return (node) => Atom2.make((get2) => Function2.pipe(get2(node), Option3.flatMap(matcher), Option3.map((data) => factory(data, get2)), Option3.getOrElse(() => [])));
1541
+ };
1542
+ var createConnectorWithRuntime = (extensionId, matcher, factory, context2) => {
1543
+ return (node) => Atom2.make((get2) => Function2.pipe(get2(node), Option3.flatMap(matcher), Option3.map((data) => runEffectSyncWithFallback(factory(data, get2), context2, extensionId, [])), Option3.getOrElse(() => [])));
1544
+ };
1545
+ var createTypeExtension = (options) => {
1546
+ const { id, type, actions, connector, relation: relation2, position } = options;
1547
+ return createExtension({
1548
+ id,
1549
+ match: whenEchoType(type),
1550
+ actions,
1551
+ connector,
1552
+ relation: relation2,
1553
+ position
1554
+ });
1555
+ };
1556
+ var qualifyNodeArgs = (parentId) => (nodes) => nodes.map((node) => {
1557
+ validateSegmentId(node.id);
1558
+ const qualified = qualifyId(parentId, node.id);
1559
+ return {
1560
+ ...node,
1561
+ id: qualified,
1562
+ nodes: node.nodes ? qualifyNodeArgs(qualified)(node.nodes) : void 0
1563
+ };
1564
+ });
1565
+ var connectorKey = (id, relation2) => primaryKey(id, relationKey(relation2));
1566
+ var relationFromConnectorKey = (key) => {
1567
+ const [id, encodedRelation] = primaryParts(key);
1568
+ return {
1569
+ id,
1570
+ relation: relationFromKey(encodedRelation)
1571
+ };
1572
+ };
1573
+ var subscriptionKey = (id, kind, detail) => detail != null ? primaryKey(id, kind, detail) : primaryKey(id, kind);
1574
+ var flattenExtensions = (extension, acc = []) => {
1575
+ if (Array2.isArray(extension)) {
1576
+ return [
1577
+ ...acc,
1578
+ ...extension.flatMap((ext) => flattenExtensions(ext, acc))
1579
+ ];
1580
+ } else {
1581
+ return [
1582
+ ...acc,
1583
+ extension
1584
+ ];
1585
+ }
1586
+ };
1587
+
1588
+ export {
1589
+ __export,
1590
+ node_exports,
1591
+ qualifyId,
1592
+ getParentId,
1593
+ getSegmentId,
1594
+ getNode,
1595
+ expand,
1596
+ graph_exports,
1597
+ node_matcher_exports,
1598
+ make3 as make,
1599
+ addExtension,
1600
+ flush,
1601
+ graph_builder_exports
1602
+ };
1603
+ //# sourceMappingURL=chunk-AKBGYELG.mjs.map