@dxos/graph 0.7.5-main.e9bb01b → 0.7.5-staging.2ff1350

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/types.ts CHANGED
@@ -3,11 +3,7 @@
3
3
  //
4
4
 
5
5
  import { S } from '@dxos/echo-schema';
6
-
7
- // Prior art:
8
- // - https://graphology.github.io (TS, tree-shakable, multiple packages for extensions)
9
- // - https://github.com/dagrejs/graphlib (mature, extensive)
10
- // - https://github.com/avoidwork/tiny-graph
6
+ import { type Specialize } from '@dxos/util';
11
7
 
12
8
  export const BaseGraphNode = S.Struct({
13
9
  id: S.String,
@@ -15,28 +11,51 @@ export const BaseGraphNode = S.Struct({
15
11
  data: S.optional(S.Any),
16
12
  });
17
13
 
14
+ /** Raw base type. */
18
15
  export type BaseGraphNode = S.Schema.Type<typeof BaseGraphNode>;
19
- export type GraphNode<Data extends object | void = void> = BaseGraphNode & { data: Data };
16
+ /** Typed node data. */
17
+ export type GraphNode<Data = any, Optional extends boolean = false> = Specialize<
18
+ BaseGraphNode,
19
+ Optional extends true ? { data?: Data } : { data: Data }
20
+ >;
21
+
22
+ export declare namespace GraphNode {
23
+ export type Optional<T = any> = GraphNode<T, true>;
24
+ }
20
25
 
21
26
  export const BaseGraphEdge = S.Struct({
22
27
  id: S.String,
23
28
  type: S.optional(S.String),
29
+ data: S.optional(S.Any),
24
30
  source: S.String,
25
31
  target: S.String,
26
- data: S.optional(S.Any),
27
32
  });
28
33
 
34
+ /** Raw base type. */
29
35
  export type BaseGraphEdge = S.Schema.Type<typeof BaseGraphEdge>;
30
- export type GraphEdge<Data extends object | void = void> = BaseGraphEdge & { data: Data };
36
+
37
+ /** Typed edge data. */
38
+ export type GraphEdge<Data = any, Optional extends boolean = false> = Specialize<
39
+ BaseGraphEdge,
40
+ Optional extends true ? { data?: Data } : { data: Data }
41
+ >;
42
+
43
+ export declare namespace GraphEdge {
44
+ export type Optional<T = any> = GraphEdge<T, true>;
45
+ }
31
46
 
32
47
  /**
33
- * Generic graph abstraction.
48
+ * Allows any additional properties on graph nodes.
49
+ */
50
+ const ExtendableBaseGraphNode = S.extend(BaseGraphNode, S.Struct({}, { key: S.String, value: S.Any }));
51
+
52
+ /**
53
+ * Generic graph.
34
54
  */
35
55
  export const Graph = S.Struct({
36
- nodes: S.mutable(S.Array(BaseGraphNode)),
56
+ id: S.optional(S.String),
57
+ nodes: S.mutable(S.Array(ExtendableBaseGraphNode)),
37
58
  edges: S.mutable(S.Array(BaseGraphEdge)),
38
59
  });
39
60
 
40
61
  export type Graph = S.Schema.Type<typeof Graph>;
41
-
42
- export const emptyGraph: Graph = { nodes: [], edges: [] };
package/src/util.ts CHANGED
@@ -2,16 +2,68 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- // TODO(burdon): GraphBuilder.
6
-
7
- // TODO(burdon): Move to @dxos/live-object?
8
- export const removeElements = <T>(array: T[], predicate: (element: T, index: number) => boolean): T[] => {
9
- const deleted: T[] = [];
10
- for (let i = array.length - 1; i >= 0; i--) {
11
- if (predicate(array[i], i)) {
12
- deleted.push(...array.splice(i, 1));
5
+ import { type ReactiveEchoObject } from '@dxos/echo-db';
6
+ import { FormatEnum } from '@dxos/echo-schema';
7
+ import { invariant } from '@dxos/invariant';
8
+ import { getSchema, create } from '@dxos/live-object';
9
+ import { log } from '@dxos/log';
10
+ import { getSchemaProperties } from '@dxos/schema';
11
+
12
+ import { GraphModel } from './model';
13
+ import { Graph, type GraphNode } from './types';
14
+
15
+ const KEY_REGEX = /\w+/;
16
+
17
+ // NOTE: The `relation` is different from the `type`.
18
+ type EdgeMeta = { source: string; target: string; relation?: string };
19
+
20
+ export const createEdgeId = ({ source, target, relation }: EdgeMeta) => {
21
+ invariant(source.match(KEY_REGEX), `invalid source: ${source}`);
22
+ invariant(target.match(KEY_REGEX), `invalid target: ${target}`);
23
+ return [source, relation, target].join('_');
24
+ };
25
+
26
+ export const parseEdgeId = (id: string): EdgeMeta => {
27
+ const [source, relation, target] = id.split('_');
28
+ invariant(source.length && target.length);
29
+ return { source, relation: relation.length ? relation : undefined, target };
30
+ };
31
+
32
+ /**
33
+ * Creates a new reactive graph from a set of ECHO objects.
34
+ * References are mapped onto graph edges.
35
+ */
36
+ export const createGraph = (objects: ReactiveEchoObject<any>[]): GraphModel<GraphNode<ReactiveEchoObject<any>>> => {
37
+ const graph = new GraphModel<GraphNode<ReactiveEchoObject<any>>>(create(Graph, { nodes: [], edges: [] }));
38
+
39
+ // Map objects.
40
+ objects.forEach((object) => {
41
+ graph.addNode({ id: object.id, type: object.typename, data: object });
42
+ });
43
+
44
+ // Find references.
45
+ objects.forEach((object) => {
46
+ const schema = getSchema(object);
47
+ if (!schema) {
48
+ log.info('no schema for object', { id: object.id.slice(0, 8) });
49
+ return;
50
+ }
51
+
52
+ // Parse schema to follow referenced objects.
53
+ for (const prop of getSchemaProperties(schema.ast, object)) {
54
+ if (prop.format === FormatEnum.Ref) {
55
+ const source = object;
56
+ const target = object[prop.name]?.target;
57
+ if (target) {
58
+ graph.addEdge({
59
+ id: createEdgeId({ source: source.id, target: target.id, relation: String(prop.name) }),
60
+ source: source.id,
61
+ target: target.id,
62
+ });
63
+ }
64
+ }
13
65
  }
14
- }
66
+ });
15
67
 
16
- return deleted;
68
+ return graph;
17
69
  };
@@ -1,16 +0,0 @@
1
- import { type ReactiveEchoObject } from '@dxos/echo-db';
2
- import { GraphModel } from './graph';
3
- import { type GraphNode } from './types';
4
- type Edge = {
5
- source: string;
6
- target: string;
7
- relation: string;
8
- };
9
- export declare const createEdgeId: ({ source, target, relation }: Edge) => string;
10
- export declare const parseEdgeId: (id: string) => Edge;
11
- /**
12
- * Maps an ECHO object graph onto a layout graph.
13
- */
14
- export declare const createGraph: (objects: ReactiveEchoObject<any>[]) => GraphModel<GraphNode<ReactiveEchoObject<any>>>;
15
- export {};
16
- //# sourceMappingURL=buidler.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"buidler.d.ts","sourceRoot":"","sources":["../../../src/buidler.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAOxD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,SAAS,CAAC;AAGzC,KAAK,IAAI,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjE,eAAO,MAAM,YAAY,iCAAkC,IAAI,WAAsC,CAAC;AAEtG,eAAO,MAAM,WAAW,OAAQ,MAAM,KAAG,IAIxC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,YAAa,kBAAkB,CAAC,GAAG,CAAC,EAAE,KAAG,UAAU,CAAC,SAAS,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAiC7G,CAAC"}
@@ -1,30 +0,0 @@
1
- import { Graph, type GraphNode, type GraphEdge } from './types';
2
- /**
3
- * Typed reactive object graph.
4
- */
5
- export declare class ReadonlyGraphModel<Node extends GraphNode = any, Edge extends GraphEdge = any> {
6
- protected readonly _graph: Graph;
7
- constructor({ nodes, edges }?: Partial<Graph>);
8
- toJSON(): any;
9
- get graph(): Graph;
10
- get nodes(): Node[];
11
- get edges(): Edge[];
12
- getNode(id: string): Node | undefined;
13
- getNodes({ type }: Partial<Node>): Node[];
14
- getEdge(id: string): Edge | undefined;
15
- getEdges({ type, source, target }: Partial<Edge>): Edge[];
16
- }
17
- export declare class GraphModel<Node extends GraphNode = any, Edge extends GraphEdge = any> extends ReadonlyGraphModel<Node, Edge> {
18
- clear(): this;
19
- addGraph(graph: GraphModel<Node, Edge>): this;
20
- addGraphs(graphs: GraphModel<Node, Edge>[]): this;
21
- addNode(node: Node): this;
22
- addNodes(nodes: Node[]): this;
23
- addEdge(edge: Edge): this;
24
- addEdges(edges: Edge[]): this;
25
- removeNode(id: string): GraphModel<Node, Edge>;
26
- removeNodes(ids: string[]): GraphModel<Node, Edge>;
27
- removeEdge(id: string): GraphModel<Node, Edge>;
28
- removeEdges(ids: string[]): GraphModel<Node, Edge>;
29
- }
30
- //# sourceMappingURL=graph.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"graph.d.ts","sourceRoot":"","sources":["../../../src/graph.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,EAAE,KAAK,SAAS,EAAE,KAAK,SAAS,EAAE,MAAM,SAAS,CAAC;AAKhE;;GAEG;AACH,qBAAa,kBAAkB,CAAC,IAAI,SAAS,SAAS,GAAG,GAAG,EAAE,IAAI,SAAS,SAAS,GAAG,GAAG;IACxF,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;gBAErB,EAAE,KAAU,EAAE,KAAU,EAAE,GAAE,OAAO,CAAC,KAAK,CAAM;IAI3D,MAAM;IAON,IAAI,KAAK,IAAI,KAAK,CAEjB;IAED,IAAI,KAAK,IAAI,IAAI,EAAE,CAElB;IAED,IAAI,KAAK,IAAI,IAAI,EAAE,CAElB;IAED,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;IAIrC,QAAQ,CAAC,EAAE,IAAI,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,EAAE;IAIzC,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;IAIrC,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,EAAE;CAM1D;AAED,qBAAa,UAAU,CAAC,IAAI,SAAS,SAAS,GAAG,GAAG,EAAE,IAAI,SAAS,SAAS,GAAG,GAAG,CAAE,SAAQ,kBAAkB,CAC5G,IAAI,EACJ,IAAI,CACL;IACC,KAAK,IAAI,IAAI;IAMb,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,IAAI;IAM7C,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,GAAG,IAAI;IAQjD,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI;IAKzB,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,IAAI;IAK7B,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI;IAKzB,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,IAAI;IAO7B,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC;IAM9C,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC;IAKlD,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC;IAK9C,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC;CAInD"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=graph.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"graph.test.d.ts","sourceRoot":"","sources":["../../../src/graph.test.ts"],"names":[],"mappings":""}
package/src/buidler.ts DELETED
@@ -1,62 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- import { type ReactiveEchoObject } from '@dxos/echo-db';
6
- import { FormatEnum } from '@dxos/echo-schema';
7
- import { invariant } from '@dxos/invariant';
8
- import { getSchema } from '@dxos/live-object';
9
- import { log } from '@dxos/log';
10
- import { getSchemaProperties } from '@dxos/schema';
11
-
12
- import { GraphModel } from './graph';
13
- import { type GraphNode } from './types';
14
-
15
- // NOTE: The `relation` is different from the `type`.
16
- type Edge = { source: string; target: string; relation: string };
17
-
18
- export const createEdgeId = ({ source, target, relation }: Edge) => `${source}-${relation}-${target}`;
19
-
20
- export const parseEdgeId = (id: string): Edge => {
21
- const [source, relation, target] = id.split('-');
22
- invariant(source && target && relation);
23
- return { source, relation, target };
24
- };
25
-
26
- /**
27
- * Maps an ECHO object graph onto a layout graph.
28
- */
29
- export const createGraph = (objects: ReactiveEchoObject<any>[]): GraphModel<GraphNode<ReactiveEchoObject<any>>> => {
30
- const graph = new GraphModel<GraphNode<ReactiveEchoObject<any>>>();
31
-
32
- // Map objects.
33
- objects.forEach((object) => {
34
- graph.addNode({ id: object.id, type: object.typename, data: object });
35
- });
36
-
37
- // Find references.
38
- objects.forEach((object) => {
39
- const schema = getSchema(object);
40
- if (!schema) {
41
- log.info('no schema for object', { id: object.id.slice(0, 8) });
42
- return;
43
- }
44
-
45
- // Parse schema to follow referenced objects.
46
- for (const prop of getSchemaProperties(schema.ast, object)) {
47
- if (prop.format === FormatEnum.Ref) {
48
- const source = object;
49
- const target = object[prop.name]?.target;
50
- if (target) {
51
- graph.addEdge({
52
- id: createEdgeId({ source: source.id, target: target.id, relation: String(prop.name) }),
53
- source: source.id,
54
- target: target.id,
55
- });
56
- }
57
- }
58
- }
59
- });
60
-
61
- return graph;
62
- };
package/src/graph.test.ts DELETED
@@ -1,56 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import { describe, test } from 'vitest';
6
-
7
- import { createEdgeId } from './buidler';
8
- import { GraphModel } from './graph';
9
- import { type GraphNode } from './types';
10
-
11
- type TestData = { value: string };
12
-
13
- describe('Graph', () => {
14
- test('empty', ({ expect }) => {
15
- const { graph } = new GraphModel();
16
- expect(graph.nodes).to.have.length(0);
17
- expect(graph.edges).to.have.length(0);
18
- });
19
-
20
- test('add and remove subgraphs', ({ expect }) => {
21
- const graph = new GraphModel<GraphNode<TestData>>()
22
- .addNode({ id: 'node-1', data: { value: 'test' } })
23
- .addNode({ id: 'node-2', data: { value: 'test' } })
24
- .addNode({ id: 'node-3', data: { value: 'test' } })
25
- .addEdge({
26
- id: createEdgeId({ source: 'node-1', target: 'node-2', relation: 'test' }),
27
- source: 'node-1',
28
- target: 'node-2',
29
- })
30
- .addEdge({
31
- id: createEdgeId({ source: 'node-2', target: 'node-3', relation: 'test' }),
32
- source: 'node-2',
33
- target: 'node-3',
34
- });
35
- expect(graph.nodes).to.have.length(3);
36
- expect(graph.edges).to.have.length(2);
37
- const pre = graph.toJSON();
38
-
39
- const node: GraphNode<TestData> = graph.getNode('node-2')!;
40
- expect(node).to.exist;
41
-
42
- const removed = graph.removeNode('node-2');
43
- expect(removed.nodes).to.have.length(1);
44
- expect(removed.edges).to.have.length(2);
45
- expect(graph.nodes).to.have.length(2);
46
- expect(graph.edges).to.have.length(0);
47
-
48
- graph.addGraph(removed);
49
- const post = graph.toJSON();
50
- expect(pre).to.deep.eq(post);
51
-
52
- graph.clear();
53
- expect(graph.nodes).to.have.length(0);
54
- expect(graph.edges).to.have.length(0);
55
- });
56
- });
package/src/graph.ts DELETED
@@ -1,127 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import { create } from '@dxos/live-object';
6
-
7
- import { Graph, type GraphNode, type GraphEdge } from './types';
8
- import { removeElements } from './util';
9
-
10
- // TODO(burdon): Traversal/visitor.
11
-
12
- /**
13
- * Typed reactive object graph.
14
- */
15
- export class ReadonlyGraphModel<Node extends GraphNode = any, Edge extends GraphEdge = any> {
16
- protected readonly _graph: Graph;
17
-
18
- constructor({ nodes = [], edges = [] }: Partial<Graph> = {}) {
19
- this._graph = create(Graph, { nodes, edges });
20
- }
21
-
22
- toJSON() {
23
- // Sort to enable stable comparisons.
24
- this._graph.nodes.sort(({ id: a }, { id: b }) => a.localeCompare(b));
25
- this._graph.edges.sort(({ id: a }, { id: b }) => a.localeCompare(b));
26
- return JSON.parse(JSON.stringify(this._graph));
27
- }
28
-
29
- get graph(): Graph {
30
- return this._graph;
31
- }
32
-
33
- get nodes(): Node[] {
34
- return this._graph.nodes as Node[];
35
- }
36
-
37
- get edges(): Edge[] {
38
- return this._graph.edges as Edge[];
39
- }
40
-
41
- getNode(id: string): Node | undefined {
42
- return this.nodes.find((node) => node.id === id);
43
- }
44
-
45
- getNodes({ type }: Partial<Node>): Node[] {
46
- return this.nodes.filter((node) => !type || type === node.type);
47
- }
48
-
49
- getEdge(id: string): Edge | undefined {
50
- return this.edges.find((edge) => edge.id === id);
51
- }
52
-
53
- getEdges({ type, source, target }: Partial<Edge>): Edge[] {
54
- return this.edges.filter(
55
- (edge) =>
56
- (!type || type === edge.type) && (!source || source === edge.source) && (!target || target === edge.target),
57
- );
58
- }
59
- }
60
-
61
- export class GraphModel<Node extends GraphNode = any, Edge extends GraphEdge = any> extends ReadonlyGraphModel<
62
- Node,
63
- Edge
64
- > {
65
- clear(): this {
66
- this._graph.nodes.length = 0;
67
- this._graph.edges.length = 0;
68
- return this;
69
- }
70
-
71
- addGraph(graph: GraphModel<Node, Edge>): this {
72
- this.addNodes(graph.nodes);
73
- this.addEdges(graph.edges);
74
- return this;
75
- }
76
-
77
- addGraphs(graphs: GraphModel<Node, Edge>[]): this {
78
- graphs.forEach((graph) => {
79
- this.addNodes(graph.nodes);
80
- this.addEdges(graph.edges);
81
- });
82
- return this;
83
- }
84
-
85
- addNode(node: Node): this {
86
- this._graph.nodes.push(node);
87
- return this;
88
- }
89
-
90
- addNodes(nodes: Node[]): this {
91
- nodes.forEach((node) => this.addNode(node));
92
- return this;
93
- }
94
-
95
- addEdge(edge: Edge): this {
96
- this._graph.edges.push(edge);
97
- return this;
98
- }
99
-
100
- addEdges(edges: Edge[]): this {
101
- edges.forEach((edge) => this.addEdge(edge));
102
- return this;
103
- }
104
-
105
- // TODO(burdon): Return graph.
106
-
107
- removeNode(id: string): GraphModel<Node, Edge> {
108
- const nodes = removeElements(this._graph.nodes, (node) => node.id === id);
109
- const edges = removeElements(this._graph.edges, (edge) => edge.source === id || edge.target === id);
110
- return new GraphModel<Node, Edge>({ nodes, edges });
111
- }
112
-
113
- removeNodes(ids: string[]): GraphModel<Node, Edge> {
114
- const graphs = ids.map((id) => this.removeNode(id));
115
- return new GraphModel<Node, Edge>().addGraphs(graphs);
116
- }
117
-
118
- removeEdge(id: string): GraphModel<Node, Edge> {
119
- const edges = removeElements(this._graph.edges, (edge) => edge.id === id);
120
- return new GraphModel<Node, Edge>({ edges });
121
- }
122
-
123
- removeEdges(ids: string[]): GraphModel<Node, Edge> {
124
- const graphs = ids.map((id) => this.removeEdge(id));
125
- return new GraphModel<Node, Edge>().addGraphs(graphs);
126
- }
127
- }