@dxos/app-graph 0.8.4-main.406dc2a → 0.8.4-main.40e3dcdf1b

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 (46) hide show
  1. package/dist/lib/browser/index.mjs +1416 -695
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +1415 -695
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/atoms.d.ts +8 -0
  8. package/dist/types/src/atoms.d.ts.map +1 -0
  9. package/dist/types/src/graph-builder.d.ts +112 -66
  10. package/dist/types/src/graph-builder.d.ts.map +1 -1
  11. package/dist/types/src/graph.d.ts +187 -221
  12. package/dist/types/src/graph.d.ts.map +1 -1
  13. package/dist/types/src/index.d.ts +6 -3
  14. package/dist/types/src/index.d.ts.map +1 -1
  15. package/dist/types/src/node-matcher.d.ts +218 -0
  16. package/dist/types/src/node-matcher.d.ts.map +1 -0
  17. package/dist/types/src/node-matcher.test.d.ts +2 -0
  18. package/dist/types/src/node-matcher.test.d.ts.map +1 -0
  19. package/dist/types/src/node.d.ts +44 -5
  20. package/dist/types/src/node.d.ts.map +1 -1
  21. package/dist/types/src/stories/EchoGraph.stories.d.ts.map +1 -1
  22. package/dist/types/src/util.d.ts +34 -0
  23. package/dist/types/src/util.d.ts.map +1 -0
  24. package/dist/types/tsconfig.tsbuildinfo +1 -1
  25. package/package.json +36 -34
  26. package/src/atoms.ts +25 -0
  27. package/src/graph-builder.test.ts +895 -137
  28. package/src/graph-builder.ts +703 -289
  29. package/src/graph.test.ts +450 -122
  30. package/src/graph.ts +1052 -401
  31. package/src/index.ts +9 -3
  32. package/src/node-matcher.test.ts +301 -0
  33. package/src/node-matcher.ts +282 -0
  34. package/src/node.ts +56 -8
  35. package/src/stories/EchoGraph.stories.tsx +159 -120
  36. package/src/stories/Tree.tsx +1 -1
  37. package/src/util.ts +71 -0
  38. package/dist/types/src/experimental/graph-projections.test.d.ts +0 -25
  39. package/dist/types/src/experimental/graph-projections.test.d.ts.map +0 -1
  40. package/dist/types/src/signals-integration.test.d.ts +0 -2
  41. package/dist/types/src/signals-integration.test.d.ts.map +0 -1
  42. package/dist/types/src/testing.d.ts +0 -5
  43. package/dist/types/src/testing.d.ts.map +0 -1
  44. package/src/experimental/graph-projections.test.ts +0 -56
  45. package/src/signals-integration.test.ts +0 -218
  46. package/src/testing.ts +0 -20
@@ -2,224 +2,159 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Registry, Rx } from '@effect-rx/rx-react';
6
- import { effect } from '@preact/signals-core';
5
+ import { Atom, Registry } from '@effect-atom/atom-react';
7
6
  import * as Array from 'effect/Array';
7
+ import type * as Context from 'effect/Context';
8
+ import * as Effect from 'effect/Effect';
8
9
  import * as Function from 'effect/Function';
9
10
  import * as Option from 'effect/Option';
11
+ import * as Pipeable from 'effect/Pipeable';
10
12
  import * as Record from 'effect/Record';
13
+ import type * as Schema from 'effect/Schema';
14
+ import { scheduleTask, yieldOrContinue } from 'main-thread-scheduling';
11
15
 
12
- import { type CleanupFn, type MulticastObservable, type Trigger } from '@dxos/async';
16
+ import { type CleanupFn, type Trigger } from '@dxos/async';
17
+ import { type Entity, type Type } from '@dxos/echo';
13
18
  import { log } from '@dxos/log';
14
- import { type MaybePromise, type Position, byPosition, getDebugName, isNode, isNonNullable } from '@dxos/util';
19
+ import { type MaybePromise, type Position, byPosition, getDebugName, isNonNullable } from '@dxos/util';
15
20
 
16
- import { ACTION_GROUP_TYPE, ACTION_TYPE, type ExpandableGraph, Graph, type GraphParams, ROOT_ID } from './graph';
17
- import { type ActionData, type Node, type NodeArg, type Relation, actionGroupSymbol } from './node';
21
+ import * as Graph from './graph';
22
+ import * as Node from './node';
23
+ import * as NodeMatcher from './node-matcher';
24
+ import { Separators, nodeArgsUnchanged, normalizeRelation, qualifyId, validateSegmentId } from './util';
25
+
26
+ //
27
+ // Extension Types
28
+ //
18
29
 
19
30
  /**
20
31
  * Graph builder extension for adding nodes to the graph based on a node id.
21
32
  */
22
- export type ResolverExtension = (id: string) => Rx.Rx<NodeArg<any> | null>;
33
+ export type ResolverExtension = (id: string) => Atom.Atom<Node.NodeArg<any> | null>;
23
34
 
24
35
  /**
25
36
  * Graph builder extension for adding nodes to the graph based on a connection to an existing node.
26
37
  *
27
38
  * @param params.node The existing node the returned nodes will be connected to.
28
39
  */
29
- export type ConnectorExtension = (node: Rx.Rx<Option.Option<Node>>) => Rx.Rx<NodeArg<any>[]>;
40
+ export type ConnectorExtension = (node: Atom.Atom<Option.Option<Node.Node>>) => Atom.Atom<Node.NodeArg<any>[]>;
30
41
 
31
42
  /**
32
43
  * Constrained case of the connector extension for more easily adding actions to the graph.
33
44
  */
34
45
  export type ActionsExtension = (
35
- node: Rx.Rx<Option.Option<Node>>,
36
- ) => Rx.Rx<Omit<NodeArg<ActionData>, 'type' | 'nodes' | 'edges'>[]>;
46
+ node: Atom.Atom<Option.Option<Node.Node>>,
47
+ ) => Atom.Atom<Omit<Node.NodeArg<Node.ActionData<any>>, 'type' | 'nodes' | 'edges'>[]>;
37
48
 
38
49
  /**
39
50
  * Constrained case of the connector extension for more easily adding action groups to the graph.
40
51
  */
41
52
  export type ActionGroupsExtension = (
42
- node: Rx.Rx<Option.Option<Node>>,
43
- ) => Rx.Rx<Omit<NodeArg<typeof actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[]>;
53
+ node: Atom.Atom<Option.Option<Node.Node>>,
54
+ ) => Atom.Atom<Omit<Node.NodeArg<typeof Node.actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[]>;
44
55
 
45
- /**
46
- * A graph builder extension is used to add nodes to the graph.
47
- *
48
- * @param params.id The unique id of the extension.
49
- * @param params.relation The relation the graph is being expanded from the existing node.
50
- * @param params.position Affects the order the extensions are processed in.
51
- * @param params.resolver A function to add nodes to the graph based on just the node id.
52
- * @param params.connector A function to add nodes to the graph based on a connection to an existing node.
53
- * @param params.actions A function to add actions to the graph based on a connection to an existing node.
54
- * @param params.actionGroups A function to add action groups to the graph based on a connection to an existing node.
55
- */
56
- export type CreateExtensionOptions = {
56
+ export type BuilderExtension = Readonly<{
57
57
  id: string;
58
- relation?: Relation;
59
- position?: Position;
58
+ position: Position;
59
+ relation?: Node.RelationInput;
60
60
  resolver?: ResolverExtension;
61
- connector?: ConnectorExtension;
62
- actions?: ActionsExtension;
63
- actionGroups?: ActionGroupsExtension;
64
- };
65
-
66
- /**
67
- * Create a graph builder extension.
68
- */
69
- export const createExtension = (extension: CreateExtensionOptions): BuilderExtension[] => {
70
- const {
71
- id,
72
- position = 'static',
73
- relation = 'outbound',
74
- resolver: _resolver,
75
- connector: _connector,
76
- actions: _actions,
77
- actionGroups: _actionGroups,
78
- } = extension;
79
- const getId = (key: string) => `${id}/${key}`;
80
-
81
- const resolver =
82
- _resolver && Rx.family((id: string) => _resolver(id).pipe(Rx.withLabel(`graph-builder:_resolver:${id}`)));
83
-
84
- const connector =
85
- _connector &&
86
- Rx.family((node: Rx.Rx<Option.Option<Node>>) =>
87
- _connector(node).pipe(Rx.withLabel(`graph-builder:_connector:${id}`)),
88
- );
89
-
90
- const actionGroups =
91
- _actionGroups &&
92
- Rx.family((node: Rx.Rx<Option.Option<Node>>) =>
93
- _actionGroups(node).pipe(Rx.withLabel(`graph-builder:_actionGroups:${id}`)),
94
- );
61
+ connector?: (node: Atom.Atom<Option.Option<Node.Node>>) => Atom.Atom<Node.NodeArg<any>[]>;
62
+ }>;
95
63
 
96
- const actions =
97
- _actions &&
98
- Rx.family((node: Rx.Rx<Option.Option<Node>>) => _actions(node).pipe(Rx.withLabel(`graph-builder:_actions:${id}`)));
64
+ export type BuilderExtensions = BuilderExtension | BuilderExtension[] | BuilderExtensions[];
99
65
 
100
- return [
101
- resolver ? { id: getId('resolver'), position, resolver } : undefined,
102
- connector
103
- ? ({
104
- id: getId('connector'),
105
- position,
106
- relation,
107
- connector: Rx.family((node) =>
108
- Rx.make((get) => {
109
- try {
110
- return get(connector(node));
111
- } catch {
112
- log.warn('Error in connector', { id: getId('connector'), node });
113
- return [];
114
- }
115
- }).pipe(Rx.withLabel(`graph-builder:connector:${id}`)),
116
- ),
117
- } satisfies BuilderExtension)
118
- : undefined,
119
- actionGroups
120
- ? ({
121
- id: getId('actionGroups'),
122
- position,
123
- relation: 'outbound',
124
- connector: Rx.family((node) =>
125
- Rx.make((get) => {
126
- try {
127
- return get(actionGroups(node)).map((arg) => ({
128
- ...arg,
129
- data: actionGroupSymbol,
130
- type: ACTION_GROUP_TYPE,
131
- }));
132
- } catch {
133
- log.warn('Error in actionGroups', { id: getId('actionGroups'), node });
134
- return [];
135
- }
136
- }).pipe(Rx.withLabel(`graph-builder:connector:actionGroups:${id}`)),
137
- ),
138
- } satisfies BuilderExtension)
139
- : undefined,
140
- actions
141
- ? ({
142
- id: getId('actions'),
143
- position,
144
- relation: 'outbound',
145
- connector: Rx.family((node) =>
146
- Rx.make((get) => {
147
- try {
148
- return get(actions(node)).map((arg) => ({ ...arg, type: ACTION_TYPE }));
149
- } catch {
150
- log.warn('Error in actions', { id: getId('actions'), node });
151
- return [];
152
- }
153
- }).pipe(Rx.withLabel(`graph-builder:connector:actions:${id}`)),
154
- ),
155
- } satisfies BuilderExtension)
156
- : undefined,
157
- ].filter(isNonNullable);
158
- };
66
+ //
67
+ // GraphBuilder Core
68
+ //
159
69
 
160
70
  export type GraphBuilderTraverseOptions = {
161
- visitor: (node: Node, path: string[]) => MaybePromise<boolean | void>;
71
+ visitor: (node: Node.Node, path: string[]) => MaybePromise<boolean | void>;
162
72
  registry?: Registry.Registry;
163
73
  source?: string;
164
- relation?: Relation;
74
+ relation: Node.RelationInput | Node.RelationInput[];
165
75
  };
166
76
 
167
- export type BuilderExtension = Readonly<{
168
- id: string;
169
- position: Position;
170
- relation?: Relation; // Only for connector.
171
- resolver?: ResolverExtension;
172
- connector?: (node: Rx.Rx<Option.Option<Node>>) => Rx.Rx<NodeArg<any>[]>;
173
- }>;
174
-
175
- export type BuilderExtensions = BuilderExtension | BuilderExtension[] | BuilderExtensions[];
77
+ /**
78
+ * Identifier denoting a GraphBuilder.
79
+ */
80
+ export const GraphBuilderTypeId: unique symbol = Symbol.for('@dxos/app-graph/GraphBuilder');
81
+ export type GraphBuilderTypeId = typeof GraphBuilderTypeId;
176
82
 
177
- export const flattenExtensions = (extension: BuilderExtensions, acc: BuilderExtension[] = []): BuilderExtension[] => {
178
- if (Array.isArray(extension)) {
179
- return [...acc, ...extension.flatMap((ext) => flattenExtensions(ext, acc))];
180
- } else {
181
- return [...acc, extension];
182
- }
183
- };
83
+ /**
84
+ * GraphBuilder interface.
85
+ */
86
+ export interface GraphBuilder extends Pipeable.Pipeable {
87
+ readonly [GraphBuilderTypeId]: GraphBuilderTypeId;
88
+ readonly graph: Graph.ExpandableGraph;
89
+ readonly extensions: Atom.Atom<Record<string, BuilderExtension>>;
90
+ }
184
91
 
185
92
  /**
186
93
  * The builder provides an extensible way to compose the construction of the graph.
94
+ * @internal
187
95
  */
188
96
  // TODO(wittjosiah): Add api for setting subscription set and/or radius.
189
97
  // Should unsubscribe from nodes that are not in the set/radius.
190
98
  // Should track LRU nodes that are not in the set/radius and remove them beyond a certain threshold.
191
- export class GraphBuilder {
99
+ class GraphBuilderImpl implements GraphBuilder {
100
+ readonly [GraphBuilderTypeId]: GraphBuilderTypeId = GraphBuilderTypeId;
101
+
102
+ pipe() {
103
+ // eslint-disable-next-line prefer-rest-params
104
+ return Pipeable.pipeArguments(this, arguments);
105
+ }
106
+
192
107
  // TODO(wittjosiah): Use Context.
193
- private readonly _subscriptions = new Map<string, CleanupFn>();
194
- private readonly _extensions = Rx.make(Record.empty<string, BuilderExtension>()).pipe(
195
- Rx.keepAlive,
196
- Rx.withLabel('graph-builder:extensions'),
108
+ /** Active subscriptions keyed by composite ID, cleaned up on node removal. */
109
+ readonly _subscriptions = new Map<string, CleanupFn>();
110
+ /** Connector updates pending flush, keyed by connector key. */
111
+ readonly _dirtyConnectors = new Map<
112
+ string,
113
+ {
114
+ nodes: Node.NodeArg<any>[];
115
+ previous: string[];
116
+ }
117
+ >();
118
+ /** Last-flushed node IDs per connector key, used for edge removal on update. */
119
+ readonly _connectorPrevious = new Map<string, string[]>();
120
+ /** Last-flushed node args per connector key, used for change detection. */
121
+ readonly _connectorPreviousArgs = new Map<string, Node.NodeArg<any>[]>();
122
+ /** Whether a dirty-flush task is already scheduled. */
123
+ _flushScheduled = false;
124
+ /** Resolves when the current flush completes. */
125
+ _flushPromise: Promise<void> = Promise.resolve();
126
+ /** Registered builder extensions keyed by extension ID. */
127
+ readonly _extensions = Atom.make(Record.empty<string, BuilderExtension>()).pipe(
128
+ Atom.keepAlive,
129
+ Atom.withLabel('graph-builder:extensions'),
197
130
  );
198
- private readonly _initialized: Record<string, Trigger> = {};
199
- private readonly _registry: Registry.Registry;
200
- private readonly _graph: Graph;
201
-
202
- constructor({ registry, ...params }: Pick<GraphParams, 'registry' | 'nodes' | 'edges'> = {}) {
131
+ /** Triggers signalling that a node's resolver has fired at least once. */
132
+ readonly _initialized: Record<string, Trigger> = {};
133
+ /** Shared atom registry for reactive subscriptions. */
134
+ readonly _registry: Registry.Registry;
135
+ /** Backing graph with internal accessors for node atoms and construction. */
136
+ readonly _graph: Graph.Graph & {
137
+ _node: (id: string) => Atom.Writable<Option.Option<Node.Node>>;
138
+ _constructNode: (node: Node.NodeArg<any>) => Option.Option<Node.Node>;
139
+ };
140
+
141
+ constructor({ registry, ...params }: Pick<Graph.GraphProps, 'registry' | 'nodes' | 'edges'> = {}) {
203
142
  this._registry = registry ?? Registry.make();
204
- this._graph = new Graph({
143
+ const graph = Graph.make({
205
144
  ...params,
206
145
  registry: this._registry,
207
146
  onExpand: (id, relation) => this._onExpand(id, relation),
208
147
  onInitialize: (id) => this._onInitialize(id),
209
148
  onRemoveNode: (id) => this._onRemoveNode(id),
210
149
  });
150
+ // Access internal methods via type assertion since GraphBuilder needs them
151
+ this._graph = graph as Graph.Graph & {
152
+ _node: (id: string) => Atom.Writable<Option.Option<Node.Node>>;
153
+ _constructNode: (node: Node.NodeArg<any>) => Option.Option<Node.Node>;
154
+ };
211
155
  }
212
156
 
213
- static from(pickle?: string, registry?: Registry.Registry): GraphBuilder {
214
- if (!pickle) {
215
- return new GraphBuilder({ registry });
216
- }
217
-
218
- const { nodes, edges } = JSON.parse(pickle);
219
- return new GraphBuilder({ nodes, edges, registry });
220
- }
221
-
222
- get graph(): ExpandableGraph {
157
+ get graph(): Graph.ExpandableGraph {
223
158
  return this._graph;
224
159
  }
225
160
 
@@ -227,71 +162,58 @@ export class GraphBuilder {
227
162
  return this._extensions;
228
163
  }
229
164
 
230
- addExtension(extensions: BuilderExtensions): GraphBuilder {
231
- flattenExtensions(extensions).forEach((extension) => {
232
- const extensions = this._registry.get(this._extensions);
233
- this._registry.set(this._extensions, Record.set(extensions, extension.id, extension));
234
- });
235
- return this;
236
- }
237
-
238
- removeExtension(id: string): GraphBuilder {
239
- const extensions = this._registry.get(this._extensions);
240
- this._registry.set(this._extensions, Record.remove(extensions, id));
241
- return this;
242
- }
243
-
244
- async explore(
245
- // TODO(wittjosiah): Currently defaulting to new registry.
246
- // Currently unsure about how to handle nodes which are expanded in the background.
247
- // This seems like a good place to start.
248
- { registry = Registry.make(), source = ROOT_ID, relation = 'outbound', visitor }: GraphBuilderTraverseOptions,
249
- path: string[] = [],
250
- ): Promise<void> {
251
- // Break cycles.
252
- if (path.includes(source)) {
253
- return;
254
- }
255
-
256
- // TODO(wittjosiah): This is a workaround for esm not working in the test runner.
257
- // Switching to vitest is blocked by having node esm versions of echo-schema & echo-signals.
258
- if (!isNode()) {
259
- const { yieldOrContinue } = await import('main-thread-scheduling');
260
- await yieldOrContinue('idle');
261
- }
262
-
263
- const node = registry.get(this._graph.nodeOrThrow(source));
264
- const shouldContinue = await visitor(node, [...path, node.id]);
265
- if (shouldContinue === false) {
266
- return;
267
- }
268
-
269
- const nodes = Object.values(this._registry.get(this._extensions))
270
- .filter((extension) => relation === (extension.relation ?? 'outbound'))
271
- .map((extension) => extension.connector)
272
- .filter(isNonNullable)
273
- .flatMap((connector) => registry.get(connector(this._graph.node(source))));
274
-
275
- await Promise.all(
276
- nodes.map((nodeArg) => {
277
- registry.set(this._graph._node(nodeArg.id), this._graph._constructNode(nodeArg));
278
- return this.explore({ registry, source: nodeArg.id, relation, visitor }, [...path, node.id]);
279
- }),
165
+ /** Apply a set of node changes for a single connector key. */
166
+ private _applyConnectorUpdate(key: string, nodes: Node.NodeArg<any>[], previous: string[]): void {
167
+ const { id, relation } = relationFromConnectorKey(key);
168
+ const ids = nodes.map((node) => node.id);
169
+ const removed = previous.filter((pid) => !ids.includes(pid));
170
+ this._connectorPrevious.set(key, ids);
171
+ this._connectorPreviousArgs.set(key, nodes);
172
+
173
+ Graph.removeEdges(
174
+ this._graph,
175
+ removed.map((target) => ({ source: id, target, relation })),
176
+ true,
280
177
  );
281
-
282
- if (registry !== this._registry) {
283
- registry.reset();
284
- registry.dispose();
178
+ Graph.addNodes(this._graph, nodes);
179
+ Graph.addEdges(
180
+ this._graph,
181
+ nodes.map((node) => ({ source: id, target: node.id, relation })),
182
+ );
183
+ if (ids.length > 0) {
184
+ const sortedIds = [...nodes]
185
+ .sort((a, b) =>
186
+ byPosition(a.properties ?? ({} as { position?: Position }), b.properties ?? ({} as { position?: Position })),
187
+ )
188
+ .map((n) => n.id);
189
+ Graph.sortEdges(this._graph, id, relation, sortedIds);
285
190
  }
286
191
  }
287
192
 
288
- destroy(): void {
289
- this._subscriptions.forEach((unsubscribe) => unsubscribe());
290
- this._subscriptions.clear();
193
+ private _scheduleDirtyFlush(): void {
194
+ if (!this._flushScheduled) {
195
+ this._flushScheduled = true;
196
+ this._flushPromise = scheduleTask(
197
+ () => {
198
+ this._flushScheduled = false;
199
+ while (this._dirtyConnectors.size > 0) {
200
+ const entries = [...this._dirtyConnectors.entries()];
201
+ this._dirtyConnectors.clear();
202
+
203
+ Atom.batch(() => {
204
+ for (const [key, { nodes, previous }] of entries) {
205
+ this._applyConnectorUpdate(key, nodes, previous);
206
+ }
207
+ });
208
+ }
209
+ },
210
+ { strategy: 'smooth' },
211
+ );
212
+ }
291
213
  }
292
214
 
293
- private readonly _resolvers = Rx.family<string, Rx.Rx<Option.Option<NodeArg<any>>>>((id) => {
294
- return Rx.make((get) => {
215
+ private readonly _resolvers = Atom.family<string, Atom.Atom<Option.Option<Node.NodeArg<any>>>>((id) => {
216
+ return Atom.make((get) => {
295
217
  return Function.pipe(
296
218
  get(this._extensions),
297
219
  Record.values,
@@ -305,69 +227,72 @@ export class GraphBuilder {
305
227
  });
306
228
  });
307
229
 
308
- private readonly _connectors = Rx.family<string, Rx.Rx<NodeArg<any>[]>>((key) => {
309
- return Rx.make((get) => {
310
- const [id, relation] = key.split('+');
230
+ private readonly _connectors = Atom.family<string, Atom.Atom<Node.NodeArg<any>[]>>((key) => {
231
+ return Atom.make((get) => {
232
+ const { id, relation } = relationFromConnectorKey(key);
311
233
  const node = this._graph.node(id);
312
234
 
313
- return Function.pipe(
235
+ const sourceNode = Option.getOrElse(get(node), () => undefined);
236
+ if (!sourceNode) {
237
+ return [];
238
+ }
239
+
240
+ const extensions = Function.pipe(
314
241
  get(this._extensions),
315
242
  Record.values,
316
- // TODO(wittjosiah): Sort on write rather than read.
317
243
  Array.sortBy(byPosition),
318
- Array.filter(({ relation: _relation = 'outbound' }) => _relation === relation),
319
- Array.map(({ connector }) => connector?.(node)),
320
- Array.filter(isNonNullable),
321
- Array.flatMap((result) => get(result)),
244
+ Array.filter(
245
+ (ext): ext is BuilderExtension & { connector: NonNullable<BuilderExtension['connector']> } =>
246
+ Graph.relationKey(ext.relation ?? 'child') === Graph.relationKey(relation) && ext.connector != null,
247
+ ),
322
248
  );
323
- }).pipe(Rx.withLabel(`graph-builder:connectors:${key}`));
249
+
250
+ const nodes: Node.NodeArg<any>[] = [];
251
+ for (const ext of extensions) {
252
+ const result = get(ext.connector(node));
253
+ nodes.push(...result);
254
+ }
255
+
256
+ return nodes;
257
+ }).pipe(Atom.withLabel(`graph-builder:connectors:${key}`));
324
258
  });
325
259
 
326
- private _onExpand(id: string, relation: Relation): void {
260
+ private _onExpand(id: string, relation: Node.Relation): void {
327
261
  log('onExpand', { id, relation, registry: getDebugName(this._registry) });
328
- const connectors = this._connectors(`${id}+${relation}`);
262
+ this._expandRelation(id, relation);
263
+
264
+ // TODO(wittjosiah): Remove. This is for backwards compatibility.
265
+ if (relation.kind === 'child' && relation.direction === 'outbound') {
266
+ Graph.expand(this._graph, id, 'action');
267
+ }
268
+ }
269
+
270
+ private _expandRelation(id: string, relation: Node.RelationInput): void {
271
+ const key = connectorKey(id, relation);
272
+ const connectors = this._connectors(key);
329
273
 
330
- let previous: string[] = [];
331
274
  const cancel = this._registry.subscribe(
332
275
  connectors,
333
- (nodes) => {
276
+ (rawNodes) => {
277
+ const nodes = qualifyNodeArgs(id)(rawNodes);
278
+ const previous = this._connectorPrevious.get(key) ?? [];
334
279
  const ids = nodes.map((n) => n.id);
335
- const removed = previous.filter((id) => !ids.includes(id));
336
- previous = ids;
337
-
338
- log('update', { id, relation, ids, removed });
339
- const update = () => {
340
- Rx.batch(() => {
341
- this._graph.removeEdges(
342
- removed.map((target) => ({ source: id, target })),
343
- true,
344
- );
345
- this._graph.addNodes(nodes);
346
- this._graph.addEdges(
347
- nodes.map((node) =>
348
- relation === 'outbound' ? { source: id, target: node.id } : { source: node.id, target: id },
349
- ),
350
- );
351
- this._graph.sortEdges(
352
- id,
353
- relation,
354
- nodes.map(({ id }) => id),
355
- );
356
- });
357
- };
358
-
359
- // TODO(wittjosiah): Remove `requestAnimationFrame` once we have a better solution.
360
- // This is a workaround to avoid a race condition where the graph is updated during React render.
361
- if (typeof requestAnimationFrame === 'function') {
362
- requestAnimationFrame(update);
363
- } else {
364
- update();
280
+
281
+ if (ids.length === previous.length && ids.every((nodeId, idx) => nodeId === previous[idx])) {
282
+ const prevArgs = this._connectorPreviousArgs.get(key);
283
+ if (prevArgs && nodeArgsUnchanged(prevArgs, nodes)) {
284
+ return;
285
+ }
365
286
  }
287
+
288
+ log('update', { id, relation, ids });
289
+ this._dirtyConnectors.set(key, { nodes, previous });
290
+ this._scheduleDirtyFlush();
366
291
  },
367
292
  { immediate: true },
368
293
  );
369
294
 
370
- this._subscriptions.set(id, cancel);
295
+ this._subscriptions.set(subscriptionKey(id, 'expand', key), cancel);
371
296
  }
372
297
 
373
298
  // TODO(wittjosiah): If the same node is added by a connector, the resolver should probably cancel itself?
@@ -381,57 +306,546 @@ export class GraphBuilder {
381
306
  const trigger = this._initialized[id];
382
307
  Option.match(node, {
383
308
  onSome: (node) => {
384
- this._graph.addNodes([node]);
309
+ const connectorOwned = [...this._connectorPrevious.values()].some((ids) => ids.includes(id));
310
+ if (!connectorOwned) {
311
+ Graph.addNodes(this._graph, [node]);
312
+ }
385
313
  trigger?.wake();
386
314
  },
387
315
  onNone: () => {
388
316
  trigger?.wake();
389
- this._graph.removeNodes([id]);
317
+ Graph.removeNodes(this._graph, [id]);
390
318
  },
391
319
  });
392
320
  },
393
321
  { immediate: true },
394
322
  );
395
323
 
396
- this._subscriptions.set(id, cancel);
324
+ this._subscriptions.set(subscriptionKey(id, 'init'), cancel);
397
325
  }
398
326
 
399
327
  private _onRemoveNode(id: string): void {
400
- this._subscriptions.get(id)?.();
401
- this._subscriptions.delete(id);
328
+ const prefix = `${id}${Separators.primary}`;
329
+ for (const [key, cleanup] of this._subscriptions) {
330
+ if (key.startsWith(prefix)) {
331
+ cleanup();
332
+ this._subscriptions.delete(key);
333
+ }
334
+ }
402
335
  }
403
336
  }
404
337
 
405
338
  /**
406
- * Creates an Rx.Rx<T> from a callback which accesses signals.
407
- * Will return a new rx instance each time.
339
+ * Creates a new GraphBuilder instance.
408
340
  */
409
- export const rxFromSignal = <T>(cb: () => T): Rx.Rx<T> => {
410
- return Rx.make((get) => {
411
- const dispose = effect(() => {
412
- get.setSelf(cb());
413
- });
341
+ export const make = (params?: Pick<Graph.GraphProps, 'registry' | 'nodes' | 'edges'>): GraphBuilder => {
342
+ return new GraphBuilderImpl(params);
343
+ };
414
344
 
415
- get.addFinalizer(() => dispose());
345
+ /**
346
+ * Creates a GraphBuilder from a serialized pickle string.
347
+ */
348
+ export const from = (pickle?: string, registry?: Registry.Registry): GraphBuilder => {
349
+ if (!pickle) {
350
+ return make({ registry });
351
+ }
416
352
 
417
- return cb();
353
+ const { nodes, edges } = JSON.parse(pickle);
354
+ return make({ nodes, edges, registry });
355
+ };
356
+
357
+ /**
358
+ * Implementation helper for addExtension.
359
+ */
360
+ const addExtensionImpl = (builder: GraphBuilder, extensions: BuilderExtensions): GraphBuilder => {
361
+ const internal = builder as GraphBuilderImpl;
362
+ flattenExtensions(extensions).forEach((extension) => {
363
+ const extensions = internal._registry.get(internal._extensions);
364
+ internal._registry.set(internal._extensions, Record.set(extensions, extension.id, extension));
418
365
  });
366
+ return builder;
419
367
  };
420
368
 
421
- const observableFamily = Rx.family((observable: MulticastObservable<any>) => {
422
- return Rx.make((get) => {
423
- const subscription = observable.subscribe((value) => get.setSelf(value));
369
+ /**
370
+ * Add extensions to the graph builder.
371
+ */
372
+ export function addExtension(builder: GraphBuilder, extensions: BuilderExtensions): GraphBuilder;
373
+ export function addExtension(extensions: BuilderExtensions): (builder: GraphBuilder) => GraphBuilder;
374
+ export function addExtension(
375
+ builderOrExtensions: GraphBuilder | BuilderExtensions,
376
+ extensions?: BuilderExtensions,
377
+ ): GraphBuilder | ((builder: GraphBuilder) => GraphBuilder) {
378
+ if (extensions === undefined) {
379
+ // Curried: addExtension(extensions)
380
+ const extensions = builderOrExtensions as BuilderExtensions;
381
+ return (builder: GraphBuilder) => addExtensionImpl(builder, extensions);
382
+ } else {
383
+ // Direct: addExtension(builder, extensions)
384
+ const builder = builderOrExtensions as GraphBuilder;
385
+ return addExtensionImpl(builder, extensions);
386
+ }
387
+ }
424
388
 
425
- get.addFinalizer(() => subscription.unsubscribe());
389
+ /**
390
+ * Implementation helper for removeExtension.
391
+ */
392
+ const removeExtensionImpl = (builder: GraphBuilder, id: string): GraphBuilder => {
393
+ const internal = builder as GraphBuilderImpl;
394
+ const extensions = internal._registry.get(internal._extensions);
395
+ internal._registry.set(internal._extensions, Record.remove(extensions, id));
396
+ return builder;
397
+ };
398
+
399
+ /**
400
+ * Remove an extension from the graph builder.
401
+ */
402
+ export function removeExtension(builder: GraphBuilder, id: string): GraphBuilder;
403
+ export function removeExtension(id: string): (builder: GraphBuilder) => GraphBuilder;
404
+ export function removeExtension(
405
+ builderOrId: GraphBuilder | string,
406
+ id?: string,
407
+ ): GraphBuilder | ((builder: GraphBuilder) => GraphBuilder) {
408
+ if (typeof builderOrId === 'string') {
409
+ // Curried: removeExtension(id)
410
+ const id = builderOrId;
411
+ return (builder: GraphBuilder) => removeExtensionImpl(builder, id);
412
+ } else {
413
+ // Direct: removeExtension(builder, id)
414
+ const builder = builderOrId;
415
+ return removeExtensionImpl(builder, id!);
416
+ }
417
+ }
426
418
 
427
- return observable.get();
419
+ /**
420
+ * Implementation helper for explore.
421
+ */
422
+ const exploreImpl = async (
423
+ builder: GraphBuilder,
424
+ options: GraphBuilderTraverseOptions,
425
+ path: string[] = [],
426
+ ): Promise<void> => {
427
+ const internal = builder as GraphBuilderImpl;
428
+ const { registry = Registry.make(), source = Node.RootId, relation, visitor } = options;
429
+ // Break cycles.
430
+ if (path.includes(source)) {
431
+ return;
432
+ }
433
+
434
+ await yieldOrContinue('idle');
435
+
436
+ const node = registry.get(internal._graph.nodeOrThrow(source));
437
+ const shouldContinue = await visitor(node, [...path, node.id]);
438
+ if (shouldContinue === false) {
439
+ return;
440
+ }
441
+
442
+ const nodes = Function.pipe(
443
+ internal._registry.get(internal._extensions),
444
+ Record.values,
445
+ Array.map((extension) => extension.connector),
446
+ Array.filter(isNonNullable),
447
+ Array.flatMap((connector) => registry.get(connector(internal._graph.node(source)))),
448
+ qualifyNodeArgs(source),
449
+ );
450
+
451
+ await Promise.all(
452
+ nodes.map((nodeArg) => {
453
+ registry.set(internal._graph._node(nodeArg.id), internal._graph._constructNode(nodeArg));
454
+ return exploreImpl(builder, { registry, source: nodeArg.id, relation, visitor }, [...path, node.id]);
455
+ }),
456
+ );
457
+
458
+ if (registry !== internal._registry) {
459
+ registry.reset();
460
+ registry.dispose();
461
+ }
462
+ };
463
+
464
+ /**
465
+ * Explore the graph by traversing it with the given options.
466
+ */
467
+ export function explore(builder: GraphBuilder, options: GraphBuilderTraverseOptions, path?: string[]): Promise<void>;
468
+ export function explore(
469
+ options: GraphBuilderTraverseOptions,
470
+ path?: string[],
471
+ ): (builder: GraphBuilder) => Promise<void>;
472
+ export function explore(
473
+ builderOrOptions: GraphBuilder | GraphBuilderTraverseOptions,
474
+ optionsOrPath?: GraphBuilderTraverseOptions | string[],
475
+ path?: string[],
476
+ ): Promise<void> | ((builder: GraphBuilder) => Promise<void>) {
477
+ if (typeof builderOrOptions === 'object' && 'visitor' in builderOrOptions) {
478
+ // Curried: explore(options, path?)
479
+ const options = builderOrOptions as GraphBuilderTraverseOptions;
480
+ const path = Array.isArray(optionsOrPath) ? optionsOrPath : undefined;
481
+ return (builder: GraphBuilder) => exploreImpl(builder, options, path);
482
+ } else {
483
+ // Direct: explore(builder, options, path?)
484
+ const builder = builderOrOptions as GraphBuilder;
485
+ const options = optionsOrPath as GraphBuilderTraverseOptions;
486
+ const pathArg = path ?? (Array.isArray(optionsOrPath) ? optionsOrPath : undefined);
487
+ return exploreImpl(builder, options, pathArg);
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Implementation helper for destroy.
493
+ */
494
+ const destroyImpl = (builder: GraphBuilder): void => {
495
+ const internal = builder as GraphBuilderImpl;
496
+ internal._subscriptions.forEach((unsubscribe) => unsubscribe());
497
+ internal._subscriptions.clear();
498
+ };
499
+
500
+ /**
501
+ * Destroy the graph builder and clean up resources.
502
+ */
503
+ export function destroy(builder: GraphBuilder): void;
504
+ export function destroy(): (builder: GraphBuilder) => void;
505
+ export function destroy(builder?: GraphBuilder): void | ((builder: GraphBuilder) => void) {
506
+ if (builder === undefined) {
507
+ // Curried: destroy()
508
+ return (builder: GraphBuilder) => destroyImpl(builder);
509
+ } else {
510
+ // Direct: destroy(builder)
511
+ return destroyImpl(builder);
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Wait for all pending connector updates to be flushed.
517
+ */
518
+ export const flush = (builder: GraphBuilder): Promise<void> => {
519
+ return (builder as GraphBuilderImpl)._flushPromise;
520
+ };
521
+
522
+ //
523
+ // Extension Creation
524
+ //
525
+
526
+ /**
527
+ * A graph builder extension is used to add nodes to the graph.
528
+ *
529
+ * @param params.id The unique id of the extension.
530
+ * @param params.relation The relation the graph is being expanded from the existing node.
531
+ * @param params.position Affects the order the extensions are processed in.
532
+ * @param params.resolver A function to add nodes to the graph based on just the node id.
533
+ * @param params.connector A function to add nodes to the graph based on a connection to an existing node.
534
+ * @param params.actions A function to add actions to the graph based on a connection to an existing node.
535
+ * @param params.actionGroups A function to add action groups to the graph based on a connection to an existing node.
536
+ */
537
+ export type CreateExtensionRawOptions = {
538
+ id: string;
539
+ relation?: Node.RelationInput;
540
+ position?: Position;
541
+ resolver?: ResolverExtension;
542
+ connector?: ConnectorExtension;
543
+ actions?: ActionsExtension;
544
+ actionGroups?: ActionGroupsExtension;
545
+ };
546
+
547
+ /**
548
+ * Create a graph builder extension (low-level API that works directly with Atoms).
549
+ */
550
+ export const createExtensionRaw = (extension: CreateExtensionRawOptions): BuilderExtension[] => {
551
+ const {
552
+ id,
553
+ position = 'static',
554
+ relation = 'child',
555
+ resolver: _resolver,
556
+ connector: _connector,
557
+ actions: _actions,
558
+ actionGroups: _actionGroups,
559
+ } = extension;
560
+ const normalizedRelation = normalizeRelation(relation);
561
+ const getId = (key: string) => `${id}/${key}`;
562
+
563
+ const resolver =
564
+ _resolver && Atom.family((id: string) => _resolver(id).pipe(Atom.withLabel(`graph-builder:_resolver:${id}`)));
565
+
566
+ const connector =
567
+ _connector &&
568
+ Atom.family((node: Atom.Atom<Option.Option<Node.Node>>) =>
569
+ _connector(node).pipe(Atom.withLabel(`graph-builder:_connector:${id}`)),
570
+ );
571
+
572
+ const actionGroups =
573
+ _actionGroups &&
574
+ Atom.family((node: Atom.Atom<Option.Option<Node.Node>>) =>
575
+ _actionGroups(node).pipe(Atom.withLabel(`graph-builder:_actionGroups:${id}`)),
576
+ );
577
+
578
+ const actions =
579
+ _actions &&
580
+ Atom.family((node: Atom.Atom<Option.Option<Node.Node>>) =>
581
+ _actions(node).pipe(Atom.withLabel(`graph-builder:_actions:${id}`)),
582
+ );
583
+
584
+ return [
585
+ resolver ? { id: getId('resolver'), position, resolver } : undefined,
586
+ connector
587
+ ? ({
588
+ id: getId('connector'),
589
+ position,
590
+ relation: normalizedRelation,
591
+ connector: Atom.family((node) =>
592
+ Atom.make((get) => {
593
+ try {
594
+ return get(connector(node));
595
+ } catch (error) {
596
+ log.warn('Error in connector', { id: getId('connector'), node, error });
597
+ return [];
598
+ }
599
+ }).pipe(Atom.withLabel(`graph-builder:connector:${id}`)),
600
+ ),
601
+ } satisfies BuilderExtension)
602
+ : undefined,
603
+ actionGroups
604
+ ? ({
605
+ id: getId('actionGroups'),
606
+ position,
607
+ relation: Node.actionRelation(),
608
+ connector: Atom.family((node) =>
609
+ Atom.make((get) => {
610
+ try {
611
+ return get(actionGroups(node)).map((arg) => ({
612
+ ...arg,
613
+ data: Node.actionGroupSymbol,
614
+ type: Node.ActionGroupType,
615
+ }));
616
+ } catch (error) {
617
+ log.warn('Error in actionGroups', { id: getId('actionGroups'), node, error });
618
+ return [];
619
+ }
620
+ }).pipe(Atom.withLabel(`graph-builder:connector:actionGroups:${id}`)),
621
+ ),
622
+ } satisfies BuilderExtension)
623
+ : undefined,
624
+ actions
625
+ ? ({
626
+ id: getId('actions'),
627
+ position,
628
+ relation: Node.actionRelation(),
629
+ connector: Atom.family((node) =>
630
+ Atom.make((get) => {
631
+ try {
632
+ return get(actions(node)).map((arg) => ({ ...arg, type: Node.ActionType }));
633
+ } catch (error) {
634
+ log.warn('Error in actions', { id: getId('actions'), node, error });
635
+ return [];
636
+ }
637
+ }).pipe(Atom.withLabel(`graph-builder:connector:actions:${id}`)),
638
+ ),
639
+ } satisfies BuilderExtension)
640
+ : undefined,
641
+ ].filter(isNonNullable);
642
+ };
643
+
644
+ /**
645
+ * Options for creating a graph builder extension with simplified API.
646
+ * All callbacks must return Effects for dependency injection.
647
+ * Effects may fail - errors are caught, logged, and the extension returns empty results.
648
+ */
649
+ export type CreateExtensionOptions<TMatched = Node.Node, R = never> = {
650
+ id: string;
651
+ match: (node: Node.Node) => Option.Option<TMatched>;
652
+ actions?: (
653
+ matched: TMatched,
654
+ get: Atom.Context,
655
+ ) => Effect.Effect<Omit<Node.NodeArg<Node.ActionData<any>, any>, 'type'>[], Error, R>;
656
+ connector?: (matched: TMatched, get: Atom.Context) => Effect.Effect<Node.NodeArg<any, any>[], Error, R>;
657
+ resolver?: (id: string, get: Atom.Context) => Effect.Effect<Node.NodeArg<any, any> | null, Error, R>;
658
+ relation?: Node.RelationInput;
659
+ position?: Position;
660
+ };
661
+
662
+ /**
663
+ * Run an Effect synchronously with the provided context.
664
+ * If the effect fails, logs the error and returns the fallback value.
665
+ * @internal
666
+ */
667
+ const runEffectSyncWithFallback = <T, R>(
668
+ effect: Effect.Effect<T, Error, R>,
669
+ context: Context.Context<R>,
670
+ extensionId: string,
671
+ fallback: T,
672
+ ): T => {
673
+ return Effect.runSync(
674
+ effect.pipe(
675
+ Effect.provide(context),
676
+ Effect.catchAll((error) => {
677
+ log.warn('Extension failed', { extension: extensionId, error });
678
+ return Effect.succeed(fallback);
679
+ }),
680
+ ),
681
+ );
682
+ };
683
+
684
+ /**
685
+ * Create a graph builder extension with simplified API.
686
+ * Returns an Effect to allow callbacks to access services via dependency injection.
687
+ */
688
+ export const createExtension = <TMatched = Node.Node, R = never>(
689
+ options: CreateExtensionOptions<TMatched, R>,
690
+ ): Effect.Effect<BuilderExtension[], never, R> =>
691
+ Effect.map(Effect.context<R>(), (context) => {
692
+ const { id, match, actions, connector, resolver, relation, position } = options;
693
+
694
+ const connectorExtension = connector ? createConnectorWithRuntime(id, match, connector, context) : undefined;
695
+
696
+ const actionsExtension = actions
697
+ ? (node: Atom.Atom<Option.Option<Node.Node>>) =>
698
+ Atom.make((get) =>
699
+ Function.pipe(
700
+ get(node),
701
+ Option.flatMap(match),
702
+ Option.map((matched) =>
703
+ runEffectSyncWithFallback(actions(matched, get), context, id, []).map((action) => ({
704
+ ...action,
705
+ // Attach captured context for action execution.
706
+ _actionContext: context,
707
+ })),
708
+ ),
709
+ Option.getOrElse(() => []),
710
+ ),
711
+ )
712
+ : undefined;
713
+
714
+ const resolverExtension = resolver
715
+ ? (nodeId: string) =>
716
+ Atom.make((get) => runEffectSyncWithFallback(resolver(nodeId, get), context, id, null) ?? null)
717
+ : undefined;
718
+
719
+ return createExtensionRaw({
720
+ id,
721
+ relation,
722
+ position,
723
+ connector: connectorExtension,
724
+ actions: actionsExtension,
725
+ resolver: resolverExtension,
726
+ });
727
+ });
728
+
729
+ /**
730
+ * Create a connector extension from a matcher and factory function.
731
+ * The factory's data type is inferred from the matcher's return type.
732
+ */
733
+ export const createConnector = <TData>(
734
+ matcher: (node: Node.Node) => Option.Option<TData>,
735
+ factory: (data: TData, get: Atom.Context) => Node.NodeArg<any>[],
736
+ ): ConnectorExtension => {
737
+ return (node: Atom.Atom<Option.Option<Node.Node>>) =>
738
+ Atom.make((get) =>
739
+ Function.pipe(
740
+ get(node),
741
+ Option.flatMap(matcher),
742
+ Option.map((data) => factory(data, get)),
743
+ Option.getOrElse(() => []),
744
+ ),
745
+ );
746
+ };
747
+
748
+ /**
749
+ * Create a connector extension from a matcher and factory function with Effect support.
750
+ * The factory must return an Effect. Errors are caught and logged.
751
+ * @internal
752
+ */
753
+ const createConnectorWithRuntime = <TData, R>(
754
+ extensionId: string,
755
+ matcher: (node: Node.Node) => Option.Option<TData>,
756
+ factory: (data: TData, get: Atom.Context) => Effect.Effect<Node.NodeArg<any>[], Error, R>,
757
+ context: Context.Context<R>,
758
+ ): ConnectorExtension => {
759
+ return (node: Atom.Atom<Option.Option<Node.Node>>) =>
760
+ Atom.make((get) =>
761
+ Function.pipe(
762
+ get(node),
763
+ Option.flatMap(matcher),
764
+ Option.map((data) => runEffectSyncWithFallback(factory(data, get), context, extensionId, [])),
765
+ Option.getOrElse(() => []),
766
+ ),
767
+ );
768
+ };
769
+
770
+ /**
771
+ * Options for creating a type-based extension.
772
+ * All callbacks must return Effects for dependency injection.
773
+ * Effects may fail - errors are caught, logged, and the extension returns empty results.
774
+ */
775
+ export type CreateTypeExtensionOptions<T extends Type.AnyEntity = Type.AnyEntity, R = never> = {
776
+ id: string;
777
+ type: T;
778
+ actions?: (
779
+ object: Entity.Entity<Schema.Schema.Type<T>>,
780
+ get: Atom.Context,
781
+ ) => Effect.Effect<Omit<Node.NodeArg<Node.ActionData<any>>, 'type'>[], Error, R>;
782
+ connector?: (
783
+ object: Entity.Entity<Schema.Schema.Type<T>>,
784
+ get: Atom.Context,
785
+ ) => Effect.Effect<Node.NodeArg<any>[], Error, R>;
786
+ relation?: Node.RelationInput;
787
+ position?: Position;
788
+ };
789
+
790
+ /**
791
+ * Create an extension that matches nodes by schema type.
792
+ * The entity type is inferred from the schema type and works for both object and relation schemas.
793
+ * Returns an Effect to allow callbacks to access services via dependency injection.
794
+ */
795
+ export const createTypeExtension = <T extends Type.AnyEntity, R = never>(
796
+ options: CreateTypeExtensionOptions<T, R>,
797
+ ): Effect.Effect<BuilderExtension[], never, R> => {
798
+ const { id, type, actions, connector, relation, position } = options;
799
+ return createExtension<Entity.Entity<Schema.Schema.Type<T>>, R>({
800
+ id,
801
+ match: NodeMatcher.whenEchoType(type),
802
+ actions,
803
+ connector,
804
+ relation,
805
+ position,
428
806
  });
429
- });
807
+ };
808
+
809
+ //
810
+ // Extension Utilities
811
+ //
430
812
 
431
813
  /**
432
- * Creates an Rx.Rx<T> from a MulticastObservable<T>
433
- * Will return the same rx instance for the same observable.
814
+ * Qualify node IDs by prefixing with the parent path.
815
+ * Validates that segment IDs do not contain the path separator.
816
+ * Recursively qualifies inline child nodes.
434
817
  */
435
- export const rxFromObservable = <T>(observable: MulticastObservable<T>): Rx.Rx<T> => {
436
- return observableFamily(observable) as Rx.Rx<T>;
818
+ const qualifyNodeArgs =
819
+ (parentId: string) =>
820
+ (nodes: Node.NodeArg<any>[]): Node.NodeArg<any>[] =>
821
+ nodes.map((node) => {
822
+ validateSegmentId(node.id);
823
+ const qualified = qualifyId(parentId, node.id);
824
+ return {
825
+ ...node,
826
+ id: qualified,
827
+ nodes: node.nodes ? qualifyNodeArgs(qualified)(node.nodes) : undefined,
828
+ };
829
+ });
830
+
831
+ const connectorKey = (id: string, relation: Node.RelationInput): string =>
832
+ `${id}${Separators.primary}${Graph.relationKey(relation)}`;
833
+
834
+ const relationFromConnectorKey = (key: string): { id: string; relation: Node.Relation } => {
835
+ const separatorIndex = key.indexOf(Separators.primary);
836
+ const id = key.slice(0, separatorIndex);
837
+ return { id, relation: Graph.relationFromKey(key.slice(separatorIndex + 1)) };
838
+ };
839
+
840
+ const subscriptionKey = (id: string, kind: string, detail?: string): string =>
841
+ detail != null
842
+ ? `${id}${Separators.primary}${kind}${Separators.primary}${detail}`
843
+ : `${id}${Separators.primary}${kind}`;
844
+
845
+ export const flattenExtensions = (extension: BuilderExtensions, acc: BuilderExtension[] = []): BuilderExtension[] => {
846
+ if (Array.isArray(extension)) {
847
+ return [...acc, ...extension.flatMap((ext) => flattenExtensions(ext, acc))];
848
+ } else {
849
+ return [...acc, extension];
850
+ }
437
851
  };