@arke-institute/sdk 0.1.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +126 -184
  2. package/dist/generated/index.cjs +19 -0
  3. package/dist/generated/index.cjs.map +1 -0
  4. package/dist/generated/index.d.cts +6192 -0
  5. package/dist/generated/index.d.ts +6192 -0
  6. package/dist/generated/index.js +1 -0
  7. package/dist/generated/index.js.map +1 -0
  8. package/dist/index-BrXke2kI.d.ts +302 -0
  9. package/dist/index-FHcLPBSV.d.cts +302 -0
  10. package/dist/index.cjs +188 -4254
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +62 -7
  13. package/dist/index.d.ts +62 -7
  14. package/dist/index.js +168 -4226
  15. package/dist/index.js.map +1 -1
  16. package/dist/operations/index.cjs +113 -0
  17. package/dist/operations/index.cjs.map +1 -0
  18. package/dist/operations/index.d.cts +3 -0
  19. package/dist/operations/index.d.ts +3 -0
  20. package/dist/operations/index.js +84 -0
  21. package/dist/operations/index.js.map +1 -0
  22. package/package.json +44 -53
  23. package/dist/client-dAk3E64p.d.cts +0 -183
  24. package/dist/client-dAk3E64p.d.ts +0 -183
  25. package/dist/collections/index.cjs +0 -233
  26. package/dist/collections/index.cjs.map +0 -1
  27. package/dist/collections/index.d.cts +0 -9
  28. package/dist/collections/index.d.ts +0 -9
  29. package/dist/collections/index.js +0 -205
  30. package/dist/collections/index.js.map +0 -1
  31. package/dist/content/index.cjs +0 -591
  32. package/dist/content/index.cjs.map +0 -1
  33. package/dist/content/index.d.cts +0 -516
  34. package/dist/content/index.d.ts +0 -516
  35. package/dist/content/index.js +0 -558
  36. package/dist/content/index.js.map +0 -1
  37. package/dist/edit/index.cjs +0 -1503
  38. package/dist/edit/index.cjs.map +0 -1
  39. package/dist/edit/index.d.cts +0 -78
  40. package/dist/edit/index.d.ts +0 -78
  41. package/dist/edit/index.js +0 -1447
  42. package/dist/edit/index.js.map +0 -1
  43. package/dist/errors-3L7IiHcr.d.cts +0 -480
  44. package/dist/errors-BTe8GKRQ.d.ts +0 -480
  45. package/dist/errors-CT7yzKkU.d.cts +0 -874
  46. package/dist/errors-CT7yzKkU.d.ts +0 -874
  47. package/dist/graph/index.cjs +0 -427
  48. package/dist/graph/index.cjs.map +0 -1
  49. package/dist/graph/index.d.cts +0 -485
  50. package/dist/graph/index.d.ts +0 -485
  51. package/dist/graph/index.js +0 -396
  52. package/dist/graph/index.js.map +0 -1
  53. package/dist/query/index.cjs +0 -356
  54. package/dist/query/index.cjs.map +0 -1
  55. package/dist/query/index.d.cts +0 -636
  56. package/dist/query/index.d.ts +0 -636
  57. package/dist/query/index.js +0 -328
  58. package/dist/query/index.js.map +0 -1
  59. package/dist/upload/index.cjs +0 -1634
  60. package/dist/upload/index.cjs.map +0 -1
  61. package/dist/upload/index.d.cts +0 -150
  62. package/dist/upload/index.d.ts +0 -150
  63. package/dist/upload/index.js +0 -1597
  64. package/dist/upload/index.js.map +0 -1
@@ -1,396 +0,0 @@
1
- // src/graph/errors.ts
2
- var GraphError = class extends Error {
3
- constructor(message, code = "GRAPH_ERROR", details) {
4
- super(message);
5
- this.code = code;
6
- this.details = details;
7
- this.name = "GraphError";
8
- }
9
- };
10
- var GraphEntityNotFoundError = class extends GraphError {
11
- constructor(canonicalId) {
12
- super(`Graph entity not found: ${canonicalId}`, "ENTITY_NOT_FOUND", { canonicalId });
13
- this.name = "GraphEntityNotFoundError";
14
- }
15
- };
16
- var NoPathFoundError = class extends GraphError {
17
- constructor(sourceIds, targetIds) {
18
- super(
19
- `No path found between sources and targets`,
20
- "NO_PATH_FOUND",
21
- { sourceIds, targetIds }
22
- );
23
- this.name = "NoPathFoundError";
24
- }
25
- };
26
- var NetworkError = class extends GraphError {
27
- constructor(message, statusCode) {
28
- super(message, "NETWORK_ERROR", { statusCode });
29
- this.statusCode = statusCode;
30
- this.name = "NetworkError";
31
- }
32
- };
33
-
34
- // src/graph/client.ts
35
- var GraphClient = class {
36
- constructor(config) {
37
- this.baseUrl = config.gatewayUrl.replace(/\/$/, "");
38
- this.fetchImpl = config.fetchImpl ?? fetch;
39
- }
40
- // ---------------------------------------------------------------------------
41
- // Request helpers
42
- // ---------------------------------------------------------------------------
43
- buildUrl(path, query) {
44
- const url = new URL(`${this.baseUrl}${path}`);
45
- if (query) {
46
- Object.entries(query).forEach(([key, value]) => {
47
- if (value !== void 0 && value !== null) {
48
- url.searchParams.set(key, String(value));
49
- }
50
- });
51
- }
52
- return url.toString();
53
- }
54
- async request(path, options = {}) {
55
- const url = this.buildUrl(path, options.query);
56
- const headers = new Headers({ "Content-Type": "application/json" });
57
- if (options.headers) {
58
- Object.entries(options.headers).forEach(([k, v]) => {
59
- if (v !== void 0) headers.set(k, v);
60
- });
61
- }
62
- let response;
63
- try {
64
- response = await this.fetchImpl(url, { ...options, headers });
65
- } catch (err) {
66
- throw new NetworkError(
67
- err instanceof Error ? err.message : "Network request failed"
68
- );
69
- }
70
- if (response.ok) {
71
- const contentType = response.headers.get("content-type") || "";
72
- if (contentType.includes("application/json")) {
73
- return await response.json();
74
- }
75
- return await response.text();
76
- }
77
- let body;
78
- const text = await response.text();
79
- try {
80
- body = JSON.parse(text);
81
- } catch {
82
- body = text;
83
- }
84
- if (response.status === 404) {
85
- throw new GraphError(
86
- body?.message || "Not found",
87
- "NOT_FOUND",
88
- body
89
- );
90
- }
91
- const message = body?.error && typeof body.error === "string" ? body.error : body?.message && typeof body.message === "string" ? body.message : `Request failed with status ${response.status}`;
92
- throw new GraphError(message, "HTTP_ERROR", {
93
- status: response.status,
94
- body
95
- });
96
- }
97
- // ---------------------------------------------------------------------------
98
- // Code-based Lookups (indexed in GraphDB)
99
- // ---------------------------------------------------------------------------
100
- /**
101
- * Query entities by code with optional type filter.
102
- *
103
- * @param code - Entity code to search for
104
- * @param type - Optional entity type filter
105
- * @returns Matching entities
106
- *
107
- * @example
108
- * ```typescript
109
- * // Find by code
110
- * const entities = await graph.queryByCode('person_john');
111
- *
112
- * // With type filter
113
- * const people = await graph.queryByCode('john', 'person');
114
- * ```
115
- */
116
- async queryByCode(code, type) {
117
- const response = await this.request(
118
- "/graphdb/entity/query",
119
- {
120
- method: "POST",
121
- body: JSON.stringify({ code, type })
122
- }
123
- );
124
- if (!response.found || !response.entity) {
125
- return [];
126
- }
127
- return [response.entity];
128
- }
129
- /**
130
- * Look up entities by code across all PIs.
131
- *
132
- * @param code - Entity code to search for
133
- * @param type - Optional entity type filter
134
- * @returns Matching entities
135
- *
136
- * @example
137
- * ```typescript
138
- * const entities = await graph.lookupByCode('alice_austen', 'person');
139
- * ```
140
- */
141
- async lookupByCode(code, type) {
142
- const response = await this.request(
143
- "/graphdb/entities/lookup-by-code",
144
- {
145
- method: "POST",
146
- body: JSON.stringify({ code, type })
147
- }
148
- );
149
- return response.entities || [];
150
- }
151
- // ---------------------------------------------------------------------------
152
- // PI-based Operations
153
- // ---------------------------------------------------------------------------
154
- /**
155
- * List entities extracted from a specific PI or multiple PIs.
156
- *
157
- * This returns knowledge graph entities (persons, places, events, etc.)
158
- * that were extracted from the given PI(s), not the PI entity itself.
159
- *
160
- * @param pi - Single PI or array of PIs
161
- * @param options - Filter options
162
- * @returns Extracted entities from the PI(s)
163
- *
164
- * @example
165
- * ```typescript
166
- * // From single PI
167
- * const entities = await graph.listEntitiesFromPi('01K75HQQXNTDG7BBP7PS9AWYAN');
168
- *
169
- * // With type filter
170
- * const people = await graph.listEntitiesFromPi('01K75HQQXNTDG7BBP7PS9AWYAN', { type: 'person' });
171
- *
172
- * // From multiple PIs
173
- * const all = await graph.listEntitiesFromPi(['pi-1', 'pi-2']);
174
- * ```
175
- */
176
- async listEntitiesFromPi(pi, options = {}) {
177
- const pis = Array.isArray(pi) ? pi : [pi];
178
- const response = await this.request(
179
- "/graphdb/entities/list",
180
- {
181
- method: "POST",
182
- body: JSON.stringify({
183
- pis,
184
- type: options.type
185
- })
186
- }
187
- );
188
- return response.entities || [];
189
- }
190
- /**
191
- * Get entities with their relationships from a PI.
192
- *
193
- * This is an optimized query that returns entities along with all their
194
- * relationship data in a single request.
195
- *
196
- * @param pi - Persistent Identifier
197
- * @param type - Optional entity type filter
198
- * @returns Entities with relationships
199
- *
200
- * @example
201
- * ```typescript
202
- * const entities = await graph.getEntitiesWithRelationships('01K75HQQXNTDG7BBP7PS9AWYAN');
203
- * entities.forEach(e => {
204
- * console.log(`${e.label} has ${e.relationships.length} relationships`);
205
- * });
206
- * ```
207
- */
208
- async getEntitiesWithRelationships(pi, type) {
209
- const response = await this.request(
210
- "/graphdb/pi/entities-with-relationships",
211
- {
212
- method: "POST",
213
- body: JSON.stringify({ pi, type })
214
- }
215
- );
216
- return response.entities || [];
217
- }
218
- /**
219
- * Get the lineage (ancestors and/or descendants) of a PI.
220
- *
221
- * This traverses the PI hierarchy (parent_pi/children_pi relationships)
222
- * which is indexed in GraphDB for fast lookups.
223
- *
224
- * @param pi - Source PI
225
- * @param direction - 'ancestors', 'descendants', or 'both'
226
- * @param maxHops - Maximum depth to traverse (default: 10)
227
- * @returns Lineage data with PIs at each hop level
228
- *
229
- * @example
230
- * ```typescript
231
- * // Get ancestors (parent chain)
232
- * const lineage = await graph.getLineage('01K75HQQXNTDG7BBP7PS9AWYAN', 'ancestors');
233
- *
234
- * // Get both directions
235
- * const full = await graph.getLineage('01K75HQQXNTDG7BBP7PS9AWYAN', 'both');
236
- * ```
237
- */
238
- async getLineage(pi, direction = "both", maxHops = 10) {
239
- return this.request("/graphdb/pi/lineage", {
240
- method: "POST",
241
- body: JSON.stringify({ sourcePi: pi, direction, maxHops })
242
- });
243
- }
244
- // ---------------------------------------------------------------------------
245
- // Relationship Operations
246
- // ---------------------------------------------------------------------------
247
- /**
248
- * Get relationships for an entity from the GraphDB index.
249
- *
250
- * **Important distinction from ContentClient.getRelationships():**
251
- * - **ContentClient.getRelationships()**: Returns OUTBOUND relationships only
252
- * (from the entity's relationships.json in IPFS - source of truth)
253
- * - **GraphClient.getRelationships()**: Returns BOTH inbound AND outbound
254
- * relationships (from the indexed GraphDB mirror)
255
- *
256
- * Use this method when you need to find "what references this entity" (inbound)
257
- * or want a complete bidirectional view.
258
- *
259
- * @param id - Entity identifier (works for both PIs and KG entities)
260
- * @param direction - Filter by direction: 'outgoing', 'incoming', or 'both' (default)
261
- * @returns Array of relationships with direction indicator
262
- *
263
- * @example
264
- * ```typescript
265
- * // Get all relationships (both directions)
266
- * const all = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN');
267
- *
268
- * // Get only inbound relationships ("who references this entity?")
269
- * const incoming = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN', 'incoming');
270
- *
271
- * // Get only outbound relationships (similar to IPFS, but from index)
272
- * const outgoing = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN', 'outgoing');
273
- *
274
- * // Process by direction
275
- * const rels = await graph.getRelationships('entity-id');
276
- * rels.forEach(r => {
277
- * if (r.direction === 'incoming') {
278
- * console.log(`${r.target_label} references this entity via ${r.predicate}`);
279
- * } else {
280
- * console.log(`This entity ${r.predicate} -> ${r.target_label}`);
281
- * }
282
- * });
283
- * ```
284
- */
285
- async getRelationships(id, direction = "both") {
286
- const response = await this.request(`/graphdb/relationships/${encodeURIComponent(id)}`);
287
- if (!response.found || !response.relationships) {
288
- return [];
289
- }
290
- let relationships = response.relationships;
291
- if (direction !== "both") {
292
- relationships = relationships.filter((rel) => rel.direction === direction);
293
- }
294
- return relationships.map((rel) => ({
295
- direction: rel.direction,
296
- predicate: rel.predicate,
297
- target_id: rel.target_id,
298
- target_code: rel.target_code || "",
299
- target_label: rel.target_label,
300
- target_type: rel.target_type,
301
- properties: rel.properties,
302
- source_pi: rel.source_pi,
303
- created_at: rel.created_at
304
- }));
305
- }
306
- // ---------------------------------------------------------------------------
307
- // Path Finding
308
- // ---------------------------------------------------------------------------
309
- /**
310
- * Find shortest paths between sets of entities.
311
- *
312
- * @param sourceIds - Starting entity IDs
313
- * @param targetIds - Target entity IDs
314
- * @param options - Path finding options
315
- * @returns Found paths
316
- *
317
- * @example
318
- * ```typescript
319
- * const paths = await graph.findPaths(
320
- * ['entity-alice'],
321
- * ['entity-bob'],
322
- * { max_depth: 4, direction: 'both' }
323
- * );
324
- *
325
- * paths.forEach(path => {
326
- * console.log(`Path of length ${path.length}:`);
327
- * path.edges.forEach(e => {
328
- * console.log(` ${e.subject_label} -[${e.predicate}]-> ${e.object_label}`);
329
- * });
330
- * });
331
- * ```
332
- */
333
- async findPaths(sourceIds, targetIds, options = {}) {
334
- const response = await this.request("/graphdb/paths/between", {
335
- method: "POST",
336
- body: JSON.stringify({
337
- source_ids: sourceIds,
338
- target_ids: targetIds,
339
- max_depth: options.max_depth,
340
- direction: options.direction,
341
- limit: options.limit
342
- })
343
- });
344
- return response.paths || [];
345
- }
346
- /**
347
- * Find entities of a specific type reachable from starting entities.
348
- *
349
- * @param startIds - Starting entity IDs
350
- * @param targetType - Type of entities to find
351
- * @param options - Search options
352
- * @returns Reachable entities of the specified type
353
- *
354
- * @example
355
- * ```typescript
356
- * // Find all people reachable from an event
357
- * const people = await graph.findReachable(
358
- * ['event-id'],
359
- * 'person',
360
- * { max_depth: 3 }
361
- * );
362
- * ```
363
- */
364
- async findReachable(startIds, targetType, options = {}) {
365
- const response = await this.request(
366
- "/graphdb/paths/reachable",
367
- {
368
- method: "POST",
369
- body: JSON.stringify({
370
- start_ids: startIds,
371
- target_type: targetType,
372
- max_depth: options.max_depth,
373
- direction: options.direction,
374
- limit: options.limit
375
- })
376
- }
377
- );
378
- return response.entities || [];
379
- }
380
- /**
381
- * Check the health of the graph service.
382
- *
383
- * @returns Health status
384
- */
385
- async health() {
386
- return this.request("/graphdb/health", { method: "GET" });
387
- }
388
- };
389
- export {
390
- GraphClient,
391
- GraphEntityNotFoundError,
392
- GraphError,
393
- NetworkError,
394
- NoPathFoundError
395
- };
396
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/graph/errors.ts","../../src/graph/client.ts"],"sourcesContent":["/**\n * Graph package error classes for the Arke SDK\n */\n\n/**\n * Base error class for graph operations\n */\nexport class GraphError extends Error {\n constructor(\n message: string,\n public code: string = 'GRAPH_ERROR',\n public details?: unknown\n ) {\n super(message);\n this.name = 'GraphError';\n }\n}\n\n/**\n * Thrown when an entity is not found by canonical ID\n */\nexport class GraphEntityNotFoundError extends GraphError {\n constructor(canonicalId: string) {\n super(`Graph entity not found: ${canonicalId}`, 'ENTITY_NOT_FOUND', { canonicalId });\n this.name = 'GraphEntityNotFoundError';\n }\n}\n\n/**\n * Thrown when no paths are found between entities\n */\nexport class NoPathFoundError extends GraphError {\n constructor(sourceIds: string[], targetIds: string[]) {\n super(\n `No path found between sources and targets`,\n 'NO_PATH_FOUND',\n { sourceIds, targetIds }\n );\n this.name = 'NoPathFoundError';\n }\n}\n\n/**\n * Thrown when a network error occurs\n */\nexport class NetworkError extends GraphError {\n constructor(message: string, public statusCode?: number) {\n super(message, 'NETWORK_ERROR', { statusCode });\n this.name = 'NetworkError';\n }\n}\n","import {\n GraphError,\n NetworkError,\n} from './errors.js';\nimport type {\n GraphEntity,\n EntityWithRelationships,\n Relationship,\n RelationshipDirection,\n Path,\n PathOptions,\n ReachableOptions,\n ListFromPiOptions,\n EntityQueryResponse,\n EntitiesWithRelationshipsResponse,\n PathsResponse,\n LineageResponse,\n} from './types.js';\n\n/**\n * Configuration for GraphClient\n */\nexport interface GraphClientConfig {\n /**\n * Gateway base URL (e.g., https://gateway.arke.institute).\n * The client will call /graphdb/* endpoints for GraphDB Gateway.\n */\n gatewayUrl: string;\n /**\n * Optional custom fetch implementation (useful for testing).\n */\n fetchImpl?: typeof fetch;\n}\n\ntype JsonBody = Record<string, unknown>;\n\n/**\n * Client for querying entity relationships and graph traversal from the Arke knowledge graph.\n *\n * The GraphDB is an indexed mirror of entity data stored in IPFS. Use this client for:\n * - **Bidirectional relationship queries** (IPFS only stores outbound relationships)\n * - **Path finding** between entities\n * - **Lineage queries** (PI ancestors/descendants)\n * - **Code-based lookups** (indexed for fast search)\n * - **Listing extracted entities** from a PI\n *\n * For entity CRUD operations, use ContentClient (source of truth in IPFS).\n * For write operations, use EditClient.\n *\n * All endpoints are public and do not require authentication.\n *\n * @example\n * ```typescript\n * const graph = new GraphClient({\n * gatewayUrl: 'https://gateway.arke.institute',\n * });\n *\n * // Get BOTH inbound and outbound relationships (GraphDB indexed)\n * const allRels = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN');\n *\n * // Get only inbound relationships (\"who references this entity?\")\n * const incoming = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN', 'incoming');\n *\n * // Find paths between entities\n * const paths = await graph.findPaths(['entity-1'], ['entity-2'], { max_depth: 4 });\n *\n * // Get PI lineage\n * const lineage = await graph.getLineage('01K75HQQXNTDG7BBP7PS9AWYAN', 'ancestors');\n * ```\n */\nexport class GraphClient {\n private baseUrl: string;\n private fetchImpl: typeof fetch;\n\n constructor(config: GraphClientConfig) {\n this.baseUrl = config.gatewayUrl.replace(/\\/$/, '');\n this.fetchImpl = config.fetchImpl ?? fetch;\n }\n\n // ---------------------------------------------------------------------------\n // Request helpers\n // ---------------------------------------------------------------------------\n\n private buildUrl(path: string, query?: Record<string, string | number | boolean | undefined>) {\n const url = new URL(`${this.baseUrl}${path}`);\n if (query) {\n Object.entries(query).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n url.searchParams.set(key, String(value));\n }\n });\n }\n return url.toString();\n }\n\n private async request<T>(\n path: string,\n options: RequestInit & {\n query?: Record<string, string | number | boolean | undefined>;\n } = {}\n ): Promise<T> {\n const url = this.buildUrl(path, options.query);\n const headers = new Headers({ 'Content-Type': 'application/json' });\n if (options.headers) {\n Object.entries(options.headers).forEach(([k, v]) => {\n if (v !== undefined) headers.set(k, v as string);\n });\n }\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, { ...options, headers });\n } catch (err) {\n throw new NetworkError(\n err instanceof Error ? err.message : 'Network request failed'\n );\n }\n\n if (response.ok) {\n const contentType = response.headers.get('content-type') || '';\n if (contentType.includes('application/json')) {\n return (await response.json()) as T;\n }\n return (await response.text()) as unknown as T;\n }\n\n let body: unknown;\n const text = await response.text();\n try {\n body = JSON.parse(text);\n } catch {\n body = text;\n }\n\n // Handle 404 specifically\n if (response.status === 404) {\n throw new GraphError(\n (body as JsonBody)?.message as string || 'Not found',\n 'NOT_FOUND',\n body\n );\n }\n\n const message =\n (body as JsonBody)?.error && typeof (body as JsonBody).error === 'string'\n ? ((body as JsonBody).error as string)\n : (body as JsonBody)?.message && typeof (body as JsonBody).message === 'string'\n ? ((body as JsonBody).message as string)\n : `Request failed with status ${response.status}`;\n\n throw new GraphError(message, 'HTTP_ERROR', {\n status: response.status,\n body,\n });\n }\n\n // ---------------------------------------------------------------------------\n // Code-based Lookups (indexed in GraphDB)\n // ---------------------------------------------------------------------------\n\n /**\n * Query entities by code with optional type filter.\n *\n * @param code - Entity code to search for\n * @param type - Optional entity type filter\n * @returns Matching entities\n *\n * @example\n * ```typescript\n * // Find by code\n * const entities = await graph.queryByCode('person_john');\n *\n * // With type filter\n * const people = await graph.queryByCode('john', 'person');\n * ```\n */\n async queryByCode(code: string, type?: string): Promise<GraphEntity[]> {\n const response = await this.request<EntityQueryResponse>(\n '/graphdb/entity/query',\n {\n method: 'POST',\n body: JSON.stringify({ code, type }),\n }\n );\n\n if (!response.found || !response.entity) {\n return [];\n }\n\n return [response.entity];\n }\n\n /**\n * Look up entities by code across all PIs.\n *\n * @param code - Entity code to search for\n * @param type - Optional entity type filter\n * @returns Matching entities\n *\n * @example\n * ```typescript\n * const entities = await graph.lookupByCode('alice_austen', 'person');\n * ```\n */\n async lookupByCode(code: string, type?: string): Promise<GraphEntity[]> {\n const response = await this.request<{ entities: GraphEntity[] }>(\n '/graphdb/entities/lookup-by-code',\n {\n method: 'POST',\n body: JSON.stringify({ code, type }),\n }\n );\n return response.entities || [];\n }\n\n // ---------------------------------------------------------------------------\n // PI-based Operations\n // ---------------------------------------------------------------------------\n\n /**\n * List entities extracted from a specific PI or multiple PIs.\n *\n * This returns knowledge graph entities (persons, places, events, etc.)\n * that were extracted from the given PI(s), not the PI entity itself.\n *\n * @param pi - Single PI or array of PIs\n * @param options - Filter options\n * @returns Extracted entities from the PI(s)\n *\n * @example\n * ```typescript\n * // From single PI\n * const entities = await graph.listEntitiesFromPi('01K75HQQXNTDG7BBP7PS9AWYAN');\n *\n * // With type filter\n * const people = await graph.listEntitiesFromPi('01K75HQQXNTDG7BBP7PS9AWYAN', { type: 'person' });\n *\n * // From multiple PIs\n * const all = await graph.listEntitiesFromPi(['pi-1', 'pi-2']);\n * ```\n */\n async listEntitiesFromPi(\n pi: string | string[],\n options: ListFromPiOptions = {}\n ): Promise<GraphEntity[]> {\n const pis = Array.isArray(pi) ? pi : [pi];\n const response = await this.request<{ entities: GraphEntity[] }>(\n '/graphdb/entities/list',\n {\n method: 'POST',\n body: JSON.stringify({\n pis,\n type: options.type,\n }),\n }\n );\n return response.entities || [];\n }\n\n /**\n * Get entities with their relationships from a PI.\n *\n * This is an optimized query that returns entities along with all their\n * relationship data in a single request.\n *\n * @param pi - Persistent Identifier\n * @param type - Optional entity type filter\n * @returns Entities with relationships\n *\n * @example\n * ```typescript\n * const entities = await graph.getEntitiesWithRelationships('01K75HQQXNTDG7BBP7PS9AWYAN');\n * entities.forEach(e => {\n * console.log(`${e.label} has ${e.relationships.length} relationships`);\n * });\n * ```\n */\n async getEntitiesWithRelationships(\n pi: string,\n type?: string\n ): Promise<EntityWithRelationships[]> {\n const response = await this.request<EntitiesWithRelationshipsResponse>(\n '/graphdb/pi/entities-with-relationships',\n {\n method: 'POST',\n body: JSON.stringify({ pi, type }),\n }\n );\n return response.entities || [];\n }\n\n /**\n * Get the lineage (ancestors and/or descendants) of a PI.\n *\n * This traverses the PI hierarchy (parent_pi/children_pi relationships)\n * which is indexed in GraphDB for fast lookups.\n *\n * @param pi - Source PI\n * @param direction - 'ancestors', 'descendants', or 'both'\n * @param maxHops - Maximum depth to traverse (default: 10)\n * @returns Lineage data with PIs at each hop level\n *\n * @example\n * ```typescript\n * // Get ancestors (parent chain)\n * const lineage = await graph.getLineage('01K75HQQXNTDG7BBP7PS9AWYAN', 'ancestors');\n *\n * // Get both directions\n * const full = await graph.getLineage('01K75HQQXNTDG7BBP7PS9AWYAN', 'both');\n * ```\n */\n async getLineage(\n pi: string,\n direction: 'ancestors' | 'descendants' | 'both' = 'both',\n maxHops: number = 10\n ): Promise<LineageResponse> {\n return this.request<LineageResponse>('/graphdb/pi/lineage', {\n method: 'POST',\n body: JSON.stringify({ sourcePi: pi, direction, maxHops }),\n });\n }\n\n // ---------------------------------------------------------------------------\n // Relationship Operations\n // ---------------------------------------------------------------------------\n\n /**\n * Get relationships for an entity from the GraphDB index.\n *\n * **Important distinction from ContentClient.getRelationships():**\n * - **ContentClient.getRelationships()**: Returns OUTBOUND relationships only\n * (from the entity's relationships.json in IPFS - source of truth)\n * - **GraphClient.getRelationships()**: Returns BOTH inbound AND outbound\n * relationships (from the indexed GraphDB mirror)\n *\n * Use this method when you need to find \"what references this entity\" (inbound)\n * or want a complete bidirectional view.\n *\n * @param id - Entity identifier (works for both PIs and KG entities)\n * @param direction - Filter by direction: 'outgoing', 'incoming', or 'both' (default)\n * @returns Array of relationships with direction indicator\n *\n * @example\n * ```typescript\n * // Get all relationships (both directions)\n * const all = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN');\n *\n * // Get only inbound relationships (\"who references this entity?\")\n * const incoming = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN', 'incoming');\n *\n * // Get only outbound relationships (similar to IPFS, but from index)\n * const outgoing = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN', 'outgoing');\n *\n * // Process by direction\n * const rels = await graph.getRelationships('entity-id');\n * rels.forEach(r => {\n * if (r.direction === 'incoming') {\n * console.log(`${r.target_label} references this entity via ${r.predicate}`);\n * } else {\n * console.log(`This entity ${r.predicate} -> ${r.target_label}`);\n * }\n * });\n * ```\n */\n async getRelationships(\n id: string,\n direction: RelationshipDirection = 'both'\n ): Promise<Relationship[]> {\n const response = await this.request<{\n found: boolean;\n canonical_id?: string;\n relationships?: Array<{\n direction: 'outgoing' | 'incoming';\n predicate: string;\n target_id: string;\n target_code?: string;\n target_label: string;\n target_type: string;\n properties?: Record<string, unknown>;\n source_pi?: string;\n created_at?: string;\n }>;\n }>(`/graphdb/relationships/${encodeURIComponent(id)}`);\n\n if (!response.found || !response.relationships) {\n return [];\n }\n\n let relationships = response.relationships;\n\n // Filter by direction if specified\n if (direction !== 'both') {\n relationships = relationships.filter(rel => rel.direction === direction);\n }\n\n return relationships.map(rel => ({\n direction: rel.direction,\n predicate: rel.predicate,\n target_id: rel.target_id,\n target_code: rel.target_code || '',\n target_label: rel.target_label,\n target_type: rel.target_type,\n properties: rel.properties,\n source_pi: rel.source_pi,\n created_at: rel.created_at,\n }));\n }\n\n // ---------------------------------------------------------------------------\n // Path Finding\n // ---------------------------------------------------------------------------\n\n /**\n * Find shortest paths between sets of entities.\n *\n * @param sourceIds - Starting entity IDs\n * @param targetIds - Target entity IDs\n * @param options - Path finding options\n * @returns Found paths\n *\n * @example\n * ```typescript\n * const paths = await graph.findPaths(\n * ['entity-alice'],\n * ['entity-bob'],\n * { max_depth: 4, direction: 'both' }\n * );\n *\n * paths.forEach(path => {\n * console.log(`Path of length ${path.length}:`);\n * path.edges.forEach(e => {\n * console.log(` ${e.subject_label} -[${e.predicate}]-> ${e.object_label}`);\n * });\n * });\n * ```\n */\n async findPaths(\n sourceIds: string[],\n targetIds: string[],\n options: PathOptions = {}\n ): Promise<Path[]> {\n const response = await this.request<PathsResponse>('/graphdb/paths/between', {\n method: 'POST',\n body: JSON.stringify({\n source_ids: sourceIds,\n target_ids: targetIds,\n max_depth: options.max_depth,\n direction: options.direction,\n limit: options.limit,\n }),\n });\n return response.paths || [];\n }\n\n /**\n * Find entities of a specific type reachable from starting entities.\n *\n * @param startIds - Starting entity IDs\n * @param targetType - Type of entities to find\n * @param options - Search options\n * @returns Reachable entities of the specified type\n *\n * @example\n * ```typescript\n * // Find all people reachable from an event\n * const people = await graph.findReachable(\n * ['event-id'],\n * 'person',\n * { max_depth: 3 }\n * );\n * ```\n */\n async findReachable(\n startIds: string[],\n targetType: string,\n options: ReachableOptions = {}\n ): Promise<GraphEntity[]> {\n const response = await this.request<{ entities: GraphEntity[] }>(\n '/graphdb/paths/reachable',\n {\n method: 'POST',\n body: JSON.stringify({\n start_ids: startIds,\n target_type: targetType,\n max_depth: options.max_depth,\n direction: options.direction,\n limit: options.limit,\n }),\n }\n );\n return response.entities || [];\n }\n\n /**\n * Check the health of the graph service.\n *\n * @returns Health status\n */\n async health(): Promise<{ status: string; service: string; version: string }> {\n return this.request('/graphdb/health', { method: 'GET' });\n }\n}\n"],"mappings":";AAOO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YACE,SACO,OAAe,eACf,SACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,2BAAN,cAAuC,WAAW;AAAA,EACvD,YAAY,aAAqB;AAC/B,UAAM,2BAA2B,WAAW,IAAI,oBAAoB,EAAE,YAAY,CAAC;AACnF,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,mBAAN,cAA+B,WAAW;AAAA,EAC/C,YAAY,WAAqB,WAAqB;AACpD;AAAA,MACE;AAAA,MACA;AAAA,MACA,EAAE,WAAW,UAAU;AAAA,IACzB;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,eAAN,cAA2B,WAAW;AAAA,EAC3C,YAAY,SAAwB,YAAqB;AACvD,UAAM,SAAS,iBAAiB,EAAE,WAAW,CAAC;AADZ;AAElC,SAAK,OAAO;AAAA,EACd;AACF;;;ACoBO,IAAM,cAAN,MAAkB;AAAA,EAIvB,YAAY,QAA2B;AACrC,SAAK,UAAU,OAAO,WAAW,QAAQ,OAAO,E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