@dxos/graph 0.7.5-labs.e27f9b9 → 0.7.5-main.2567c87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=graph.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.test.d.ts","sourceRoot":"","sources":["../../../src/graph.test.ts"],"names":[],"mappings":""}
@@ -1,4 +1,4 @@
1
- export * from './model';
1
+ export * from './buidler';
2
+ export * from './graph';
2
3
  export * from './types';
3
- export * from './util';
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC"}
@@ -1,59 +1,41 @@
1
1
  import { S } from '@dxos/echo-schema';
2
- import { type Specialize } from '@dxos/util';
3
2
  export declare const BaseGraphNode: S.Struct<{
4
3
  id: typeof S.String;
5
4
  type: S.optional<typeof S.String>;
6
5
  data: S.optional<typeof S.Any>;
7
6
  }>;
8
- /** Raw base type. */
9
7
  export type BaseGraphNode = S.Schema.Type<typeof BaseGraphNode>;
10
- /** Typed node data. */
11
- export type GraphNode<Data = any, Optional extends boolean = false> = Specialize<BaseGraphNode, Optional extends true ? {
12
- data?: Data;
13
- } : {
8
+ export type GraphNode<Data extends object | void = void> = BaseGraphNode & {
14
9
  data: Data;
15
- }>;
16
- export declare namespace GraphNode {
17
- type Optional<T = any> = GraphNode<T, true>;
18
- }
10
+ };
19
11
  export declare const BaseGraphEdge: S.Struct<{
20
12
  id: typeof S.String;
21
13
  type: S.optional<typeof S.String>;
22
- data: S.optional<typeof S.Any>;
23
14
  source: typeof S.String;
24
15
  target: typeof S.String;
16
+ data: S.optional<typeof S.Any>;
25
17
  }>;
26
- /** Raw base type. */
27
18
  export type BaseGraphEdge = S.Schema.Type<typeof BaseGraphEdge>;
28
- /** Typed edge data. */
29
- export type GraphEdge<Data = any, Optional extends boolean = false> = Specialize<BaseGraphEdge, Optional extends true ? {
30
- data?: Data;
31
- } : {
19
+ export type GraphEdge<Data extends object | void = void> = BaseGraphEdge & {
32
20
  data: Data;
33
- }>;
34
- export declare namespace GraphEdge {
35
- type Optional<T = any> = GraphEdge<T, true>;
36
- }
21
+ };
37
22
  /**
38
- * Generic graph.
23
+ * Generic graph abstraction.
39
24
  */
40
25
  export declare const Graph: S.Struct<{
41
- id: S.optional<typeof S.String>;
42
- nodes: S.mutable<S.Array$<S.extend<S.Struct<{
26
+ nodes: S.mutable<S.Array$<S.Struct<{
43
27
  id: typeof S.String;
44
28
  type: S.optional<typeof S.String>;
45
29
  data: S.optional<typeof S.Any>;
46
- }>, S.TypeLiteral<{}, readonly [{
47
- readonly key: typeof S.String;
48
- readonly value: typeof S.Any;
49
- }]>>>>;
30
+ }>>>;
50
31
  edges: S.mutable<S.Array$<S.Struct<{
51
32
  id: typeof S.String;
52
33
  type: S.optional<typeof S.String>;
53
- data: S.optional<typeof S.Any>;
54
34
  source: typeof S.String;
55
35
  target: typeof S.String;
36
+ data: S.optional<typeof S.Any>;
56
37
  }>>>;
57
38
  }>;
58
39
  export type Graph = S.Schema.Type<typeof Graph>;
40
+ export declare const emptyGraph: Graph;
59
41
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/types.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,eAAO,MAAM,aAAa;;;;EAIxB,CAAC;AAEH,qBAAqB;AACrB,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,aAAa,CAAC,CAAC;AAChE,uBAAuB;AACvB,MAAM,MAAM,SAAS,CAAC,IAAI,GAAG,GAAG,EAAE,QAAQ,SAAS,OAAO,GAAG,KAAK,IAAI,UAAU,CAC9E,aAAa,EACb,QAAQ,SAAS,IAAI,GAAG;IAAE,IAAI,CAAC,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,IAAI,CAAA;CAAE,CACzD,CAAC;AAEF,MAAM,CAAC,OAAO,WAAW,SAAS,CAAC;IACjC,KAAY,QAAQ,CAAC,CAAC,GAAG,GAAG,IAAI,SAAS,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;CACpD;AAED,eAAO,MAAM,aAAa;;;;;;EAMxB,CAAC;AAEH,qBAAqB;AACrB,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,aAAa,CAAC,CAAC;AAEhE,uBAAuB;AACvB,MAAM,MAAM,SAAS,CAAC,IAAI,GAAG,GAAG,EAAE,QAAQ,SAAS,OAAO,GAAG,KAAK,IAAI,UAAU,CAC9E,aAAa,EACb,QAAQ,SAAS,IAAI,GAAG;IAAE,IAAI,CAAC,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,IAAI,CAAA;CAAE,CACzD,CAAC;AAEF,MAAM,CAAC,OAAO,WAAW,SAAS,CAAC;IACjC,KAAY,QAAQ,CAAC,CAAC,GAAG,GAAG,IAAI,SAAS,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;CACpD;AAOD;;GAEG;AACH,eAAO,MAAM,KAAK;;;;;;;;;;;;;;;;;EAIhB,CAAC;AAEH,MAAM,MAAM,KAAK,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,KAAK,CAAC,CAAC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/types.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AAOtC,eAAO,MAAM,aAAa;;;;EAIxB,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,aAAa,CAAC,CAAC;AAChE,MAAM,MAAM,SAAS,CAAC,IAAI,SAAS,MAAM,GAAG,IAAI,GAAG,IAAI,IAAI,aAAa,GAAG;IAAE,IAAI,EAAE,IAAI,CAAA;CAAE,CAAC;AAE1F,eAAO,MAAM,aAAa;;;;;;EAMxB,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,aAAa,CAAC,CAAC;AAChE,MAAM,MAAM,SAAS,CAAC,IAAI,SAAS,MAAM,GAAG,IAAI,GAAG,IAAI,IAAI,aAAa,GAAG;IAAE,IAAI,EAAE,IAAI,CAAA;CAAE,CAAC;AAE1F;;GAEG;AACH,eAAO,MAAM,KAAK;;;;;;;;;;;;;EAGhB,CAAC;AAEH,MAAM,MAAM,KAAK,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,KAAK,CAAC,CAAC;AAEhD,eAAO,MAAM,UAAU,EAAE,KAAgC,CAAC"}
@@ -1,17 +1,2 @@
1
- import { type ReactiveEchoObject } from '@dxos/echo-db';
2
- import { GraphModel } from './model';
3
- import { type GraphNode } from './types';
4
- type EdgeMeta = {
5
- source: string;
6
- target: string;
7
- relation?: string;
8
- };
9
- export declare const createEdgeId: ({ source, target, relation }: EdgeMeta) => string;
10
- export declare const parseEdgeId: (id: string) => EdgeMeta;
11
- /**
12
- * Creates a new reactive graph from a set of ECHO objects.
13
- * References are mapped onto graph edges.
14
- */
15
- export declare const createGraph: (objects: ReactiveEchoObject<any>[]) => GraphModel<GraphNode<ReactiveEchoObject<any>>>;
16
- export {};
1
+ export declare const removeElements: <T>(array: T[], predicate: (element: T, index: number) => boolean) => T[];
17
2
  //# sourceMappingURL=util.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../../src/util.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAOxD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAS,KAAK,SAAS,EAAE,MAAM,SAAS,CAAC;AAKhD,KAAK,QAAQ,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtE,eAAO,MAAM,YAAY,iCAAkC,QAAQ,WAIlE,CAAC;AAEF,eAAO,MAAM,WAAW,OAAQ,MAAM,KAAG,QAIxC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,WAAW,YAAa,kBAAkB,CAAC,GAAG,CAAC,EAAE,KAAG,UAAU,CAAC,SAAS,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAiC7G,CAAC"}
1
+ {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../../src/util.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,cAAc,GAAI,CAAC,SAAS,CAAC,EAAE,aAAa,CAAC,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,KAAG,CAAC,EASlG,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/graph",
3
- "version": "0.7.5-labs.e27f9b9",
3
+ "version": "0.7.5-main.2567c87",
4
4
  "description": "Low-level graph API",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -32,25 +32,27 @@
32
32
  "dependencies": {
33
33
  "@effect/schema": "^0.75.5",
34
34
  "@preact/signals-core": "^1.6.0",
35
+ "graphology": "^0.25.4",
36
+ "graphology-shortest-path": "^2.1.0",
37
+ "graphology-types": "^0.24.8",
35
38
  "lodash.defaultsdeep": "^4.6.1",
36
- "@dxos/async": "0.7.5-labs.e27f9b9",
37
- "@dxos/echo-db": "0.7.5-labs.e27f9b9",
38
- "@dxos/echo-schema": "0.7.5-labs.e27f9b9",
39
- "@dxos/debug": "0.7.5-labs.e27f9b9",
40
- "@dxos/invariant": "0.7.5-labs.e27f9b9",
41
- "@dxos/live-object": "0.7.5-labs.e27f9b9",
42
- "@dxos/log": "0.7.5-labs.e27f9b9",
43
- "@dxos/node-std": "0.7.5-labs.e27f9b9",
44
- "@dxos/schema": "0.7.5-labs.e27f9b9",
45
- "@dxos/util": "0.7.5-labs.e27f9b9"
39
+ "@dxos/async": "0.7.5-main.2567c87",
40
+ "@dxos/debug": "0.7.5-main.2567c87",
41
+ "@dxos/echo-schema": "0.7.5-main.2567c87",
42
+ "@dxos/invariant": "0.7.5-main.2567c87",
43
+ "@dxos/live-object": "0.7.5-main.2567c87",
44
+ "@dxos/echo-db": "0.7.5-main.2567c87",
45
+ "@dxos/log": "0.7.5-main.2567c87",
46
+ "@dxos/schema": "0.7.5-main.2567c87",
47
+ "@dxos/util": "0.7.5-main.2567c87"
46
48
  },
47
49
  "devDependencies": {
48
50
  "@antv/graphlib": "^2.0.4",
49
51
  "@antv/layout": "^1.2.13",
50
52
  "@types/lodash.defaultsdeep": "^4.6.6",
51
- "@dxos/echo-db": "0.7.5-labs.e27f9b9",
52
- "@dxos/echo-schema": "0.7.5-labs.e27f9b9",
53
- "@dxos/random": "0.7.5-labs.e27f9b9"
53
+ "@dxos/echo-db": "0.7.5-main.2567c87",
54
+ "@dxos/echo-schema": "0.7.5-main.2567c87",
55
+ "@dxos/random": "0.7.5-main.2567c87"
54
56
  },
55
57
  "publishConfig": {
56
58
  "access": "public"
package/src/buidler.ts ADDED
@@ -0,0 +1,62 @@
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
+ };
@@ -0,0 +1,56 @@
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 ADDED
@@ -0,0 +1,127 @@
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
+ }
package/src/index.ts CHANGED
@@ -2,6 +2,6 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- export * from './model';
5
+ export * from './buidler';
6
+ export * from './graph';
6
7
  export * from './types';
7
- export * from './util';
package/src/types.ts CHANGED
@@ -3,7 +3,11 @@
3
3
  //
4
4
 
5
5
  import { S } from '@dxos/echo-schema';
6
- import { type Specialize } from '@dxos/util';
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
7
11
 
8
12
  export const BaseGraphNode = S.Struct({
9
13
  id: S.String,
@@ -11,51 +15,28 @@ export const BaseGraphNode = S.Struct({
11
15
  data: S.optional(S.Any),
12
16
  });
13
17
 
14
- /** Raw base type. */
15
18
  export type BaseGraphNode = S.Schema.Type<typeof BaseGraphNode>;
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
- }
19
+ export type GraphNode<Data extends object | void = void> = BaseGraphNode & { data: Data };
25
20
 
26
21
  export const BaseGraphEdge = S.Struct({
27
22
  id: S.String,
28
23
  type: S.optional(S.String),
29
- data: S.optional(S.Any),
30
24
  source: S.String,
31
25
  target: S.String,
26
+ data: S.optional(S.Any),
32
27
  });
33
28
 
34
- /** Raw base type. */
35
29
  export type BaseGraphEdge = S.Schema.Type<typeof BaseGraphEdge>;
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
- }
30
+ export type GraphEdge<Data extends object | void = void> = BaseGraphEdge & { data: Data };
46
31
 
47
32
  /**
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.
33
+ * Generic graph abstraction.
54
34
  */
55
35
  export const Graph = S.Struct({
56
- id: S.optional(S.String),
57
- nodes: S.mutable(S.Array(ExtendableBaseGraphNode)),
36
+ nodes: S.mutable(S.Array(BaseGraphNode)),
58
37
  edges: S.mutable(S.Array(BaseGraphEdge)),
59
38
  });
60
39
 
61
40
  export type Graph = S.Schema.Type<typeof Graph>;
41
+
42
+ export const emptyGraph: Graph = { nodes: [], edges: [] };
package/src/util.ts CHANGED
@@ -1,69 +1,17 @@
1
1
  //
2
- // Copyright 2023 DXOS.org
2
+ // Copyright 2024 DXOS.org
3
3
  //
4
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, create } from '@dxos/live-object';
9
- import { log } from '@dxos/log';
10
- import { getSchemaProperties } from '@dxos/schema';
5
+ // TODO(burdon): GraphBuilder.
11
6
 
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
- }
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));
65
13
  }
66
- });
14
+ }
67
15
 
68
- return graph;
16
+ return deleted;
69
17
  };