@arke-institute/sdk 0.1.1 → 0.1.3

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 (41) hide show
  1. package/dist/content/index.cjs +591 -0
  2. package/dist/content/index.cjs.map +1 -0
  3. package/dist/content/index.d.cts +516 -0
  4. package/dist/content/index.d.ts +516 -0
  5. package/dist/content/index.js +558 -0
  6. package/dist/content/index.js.map +1 -0
  7. package/dist/edit/index.cjs +1503 -0
  8. package/dist/edit/index.cjs.map +1 -0
  9. package/dist/edit/index.d.cts +78 -0
  10. package/dist/edit/index.d.ts +78 -0
  11. package/dist/edit/index.js +1447 -0
  12. package/dist/edit/index.js.map +1 -0
  13. package/dist/{errors-BrNZWPE7.d.cts → errors-3L7IiHcr.d.cts} +3 -0
  14. package/dist/{errors-CCyp5KCg.d.ts → errors-BTe8GKRQ.d.ts} +3 -0
  15. package/dist/errors-CT7yzKkU.d.cts +874 -0
  16. package/dist/errors-CT7yzKkU.d.ts +874 -0
  17. package/dist/graph/index.cjs +427 -0
  18. package/dist/graph/index.cjs.map +1 -0
  19. package/dist/graph/index.d.cts +485 -0
  20. package/dist/graph/index.d.ts +485 -0
  21. package/dist/graph/index.js +396 -0
  22. package/dist/graph/index.js.map +1 -0
  23. package/dist/index.cjs +2726 -14
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +5 -1
  26. package/dist/index.d.ts +5 -1
  27. package/dist/index.js +2708 -14
  28. package/dist/index.js.map +1 -1
  29. package/dist/query/index.cjs +356 -0
  30. package/dist/query/index.cjs.map +1 -0
  31. package/dist/query/index.d.cts +636 -0
  32. package/dist/query/index.d.ts +636 -0
  33. package/dist/query/index.js +328 -0
  34. package/dist/query/index.js.map +1 -0
  35. package/dist/upload/index.cjs +3 -14
  36. package/dist/upload/index.cjs.map +1 -1
  37. package/dist/upload/index.d.cts +2 -2
  38. package/dist/upload/index.d.ts +2 -2
  39. package/dist/upload/index.js +3 -14
  40. package/dist/upload/index.js.map +1 -1
  41. package/package.json +26 -1
package/dist/index.js CHANGED
@@ -1466,7 +1466,6 @@ var ArkeUploader = class {
1466
1466
  };
1467
1467
 
1468
1468
  // src/upload/client.ts
1469
- init_errors();
1470
1469
  function getUserIdFromToken(token) {
1471
1470
  try {
1472
1471
  const parts = token.split(".");
@@ -1551,22 +1550,12 @@ var UploadClient = class {
1551
1550
  *
1552
1551
  * Requires owner or editor role on the collection containing the parent PI.
1553
1552
  * Use this to add a folder or files to an existing collection hierarchy.
1553
+ *
1554
+ * Note: Permission checks are enforced server-side by the ingest worker.
1555
+ * The server will return 403 if the user lacks edit access to the parent PI.
1554
1556
  */
1555
1557
  async addToCollection(options) {
1556
1558
  const { files, parentPi, customPrompts, processing, onProgress, dryRun } = options;
1557
- if (!dryRun) {
1558
- const permissions = await this.collectionsClient.getPiPermissions(parentPi);
1559
- if (!permissions.canEdit) {
1560
- if (!permissions.collection) {
1561
- throw new ValidationError(
1562
- `Cannot add files: PI "${parentPi}" is not part of any collection`
1563
- );
1564
- }
1565
- throw new ValidationError(
1566
- `Cannot add files to collection "${permissions.collection.title}": you need editor or owner role (current role: ${permissions.collection.role || "none"})`
1567
- );
1568
- }
1569
- }
1570
1559
  const uploader = new ArkeUploader({
1571
1560
  gatewayUrl: this.config.gatewayUrl,
1572
1561
  authToken: this.config.authToken,
@@ -1596,15 +1585,2720 @@ var UploadClient = class {
1596
1585
 
1597
1586
  // src/index.ts
1598
1587
  init_errors();
1588
+
1589
+ // src/query/errors.ts
1590
+ var QueryError = class extends Error {
1591
+ constructor(message, code2 = "UNKNOWN_ERROR", details) {
1592
+ super(message);
1593
+ this.code = code2;
1594
+ this.details = details;
1595
+ this.name = "QueryError";
1596
+ }
1597
+ };
1598
+
1599
+ // src/query/client.ts
1600
+ var QueryClient = class {
1601
+ constructor(config) {
1602
+ this.baseUrl = config.gatewayUrl.replace(/\/$/, "");
1603
+ this.fetchImpl = config.fetchImpl ?? fetch;
1604
+ }
1605
+ // ---------------------------------------------------------------------------
1606
+ // Request helpers
1607
+ // ---------------------------------------------------------------------------
1608
+ buildUrl(path2, query) {
1609
+ const url = new URL(`${this.baseUrl}${path2}`);
1610
+ if (query) {
1611
+ Object.entries(query).forEach(([key, value]) => {
1612
+ if (value !== void 0 && value !== null) {
1613
+ url.searchParams.set(key, String(value));
1614
+ }
1615
+ });
1616
+ }
1617
+ return url.toString();
1618
+ }
1619
+ async request(path2, options = {}) {
1620
+ const url = this.buildUrl(path2, options.query);
1621
+ const headers = new Headers({ "Content-Type": "application/json" });
1622
+ if (options.headers) {
1623
+ Object.entries(options.headers).forEach(([k, v]) => {
1624
+ if (v !== void 0) headers.set(k, v);
1625
+ });
1626
+ }
1627
+ const response = await this.fetchImpl(url, { ...options, headers });
1628
+ if (response.ok) {
1629
+ const contentType = response.headers.get("content-type") || "";
1630
+ if (contentType.includes("application/json")) {
1631
+ return await response.json();
1632
+ }
1633
+ return await response.text();
1634
+ }
1635
+ let body;
1636
+ const text = await response.text();
1637
+ try {
1638
+ body = JSON.parse(text);
1639
+ } catch {
1640
+ body = text;
1641
+ }
1642
+ const message = body?.error && typeof body.error === "string" ? body.error : body?.message && typeof body.message === "string" ? body.message : `Request failed with status ${response.status}`;
1643
+ throw new QueryError(message, "HTTP_ERROR", {
1644
+ status: response.status,
1645
+ body
1646
+ });
1647
+ }
1648
+ // ---------------------------------------------------------------------------
1649
+ // Query methods
1650
+ // ---------------------------------------------------------------------------
1651
+ /**
1652
+ * Execute a path query against the knowledge graph.
1653
+ *
1654
+ * @param pathQuery - The path query string (e.g., '"alice austen" -[*]{,4}-> type:person')
1655
+ * @param options - Query options (k, k_explore, lineage, enrich, etc.)
1656
+ * @returns Query results with entities, paths, and metadata
1657
+ *
1658
+ * @example
1659
+ * ```typescript
1660
+ * // Simple semantic search
1661
+ * const results = await query.path('"Washington" type:person');
1662
+ *
1663
+ * // Multi-hop traversal
1664
+ * const results = await query.path('"alice austen" -[*]{,4}-> type:person ~ "photographer"');
1665
+ *
1666
+ * // With lineage filtering (collection scope)
1667
+ * const results = await query.path('"letters" type:document', {
1668
+ * lineage: { sourcePi: 'arke:my_collection', direction: 'descendants' },
1669
+ * k: 10,
1670
+ * });
1671
+ * ```
1672
+ */
1673
+ async path(pathQuery, options = {}) {
1674
+ return this.request("/query/path", {
1675
+ method: "POST",
1676
+ body: JSON.stringify({
1677
+ path: pathQuery,
1678
+ ...options
1679
+ })
1680
+ });
1681
+ }
1682
+ /**
1683
+ * Execute a natural language query.
1684
+ *
1685
+ * The query is translated to a path query using an LLM, then executed.
1686
+ *
1687
+ * @param question - Natural language question
1688
+ * @param options - Query options including custom_instructions for the LLM
1689
+ * @returns Query results with translation info
1690
+ *
1691
+ * @example
1692
+ * ```typescript
1693
+ * const results = await query.natural('Find photographers connected to Alice Austen');
1694
+ * console.log('Generated query:', results.translation.path);
1695
+ * console.log('Explanation:', results.translation.explanation);
1696
+ * ```
1697
+ */
1698
+ async natural(question, options = {}) {
1699
+ const { custom_instructions, ...queryOptions } = options;
1700
+ return this.request("/query/natural", {
1701
+ method: "POST",
1702
+ body: JSON.stringify({
1703
+ query: question,
1704
+ custom_instructions,
1705
+ ...queryOptions
1706
+ })
1707
+ });
1708
+ }
1709
+ /**
1710
+ * Translate a natural language question to a path query without executing it.
1711
+ *
1712
+ * Useful for understanding how questions are translated or for manual execution later.
1713
+ *
1714
+ * @param question - Natural language question
1715
+ * @param customInstructions - Optional additional instructions for the LLM
1716
+ * @returns Translation result with path query and explanation
1717
+ *
1718
+ * @example
1719
+ * ```typescript
1720
+ * const result = await query.translate('Who wrote letters from Philadelphia?');
1721
+ * console.log('Path query:', result.path);
1722
+ * // '"letters" <-[authored, wrote]- type:person -[located]-> "Philadelphia"'
1723
+ * ```
1724
+ */
1725
+ async translate(question, customInstructions) {
1726
+ return this.request("/query/translate", {
1727
+ method: "POST",
1728
+ body: JSON.stringify({
1729
+ query: question,
1730
+ custom_instructions: customInstructions
1731
+ })
1732
+ });
1733
+ }
1734
+ /**
1735
+ * Parse and validate a path query without executing it.
1736
+ *
1737
+ * Returns the AST (Abstract Syntax Tree) if valid, or throws an error.
1738
+ *
1739
+ * @param pathQuery - The path query to parse
1740
+ * @returns Parsed AST
1741
+ * @throws QueryError if the query has syntax errors
1742
+ *
1743
+ * @example
1744
+ * ```typescript
1745
+ * try {
1746
+ * const result = await query.parse('"test" -[*]-> type:person');
1747
+ * console.log('Valid query, AST:', result.ast);
1748
+ * } catch (err) {
1749
+ * console.error('Invalid query:', err.message);
1750
+ * }
1751
+ * ```
1752
+ */
1753
+ async parse(pathQuery) {
1754
+ const url = this.buildUrl("/query/parse", { path: pathQuery });
1755
+ const response = await this.fetchImpl(url, {
1756
+ method: "GET",
1757
+ headers: { "Content-Type": "application/json" }
1758
+ });
1759
+ const body = await response.json();
1760
+ if ("error" in body && body.error === "Parse error") {
1761
+ throw new QueryError(
1762
+ body.message,
1763
+ "PARSE_ERROR",
1764
+ { position: body.position }
1765
+ );
1766
+ }
1767
+ if (!response.ok) {
1768
+ throw new QueryError(
1769
+ body.error || `Request failed with status ${response.status}`,
1770
+ "HTTP_ERROR",
1771
+ { status: response.status, body }
1772
+ );
1773
+ }
1774
+ return body;
1775
+ }
1776
+ /**
1777
+ * Get the path query syntax documentation.
1778
+ *
1779
+ * Returns comprehensive documentation including entry points, edge traversal,
1780
+ * filters, examples, and constraints.
1781
+ *
1782
+ * @returns Syntax documentation
1783
+ *
1784
+ * @example
1785
+ * ```typescript
1786
+ * const syntax = await query.syntax();
1787
+ *
1788
+ * // List all entry point types
1789
+ * syntax.entryPoints.types.forEach(ep => {
1790
+ * console.log(`${ep.syntax} - ${ep.description}`);
1791
+ * });
1792
+ *
1793
+ * // Show examples
1794
+ * syntax.examples.forEach(ex => {
1795
+ * console.log(`${ex.description}: ${ex.query}`);
1796
+ * });
1797
+ * ```
1798
+ */
1799
+ async syntax() {
1800
+ return this.request("/query/syntax", {
1801
+ method: "GET"
1802
+ });
1803
+ }
1804
+ /**
1805
+ * Check the health of the query service.
1806
+ *
1807
+ * @returns Health status
1808
+ */
1809
+ async health() {
1810
+ return this.request("/query/health", { method: "GET" });
1811
+ }
1812
+ /**
1813
+ * Direct semantic search against the vector index.
1814
+ *
1815
+ * This bypasses the path query syntax and directly queries Pinecone for
1816
+ * semantically similar entities. Useful for:
1817
+ * - Simple semantic searches without graph traversal
1818
+ * - Scoped searches filtered by source_pi (collection scope)
1819
+ * - Type-filtered semantic searches
1820
+ *
1821
+ * For graph traversal and path-based queries, use `path()` instead.
1822
+ *
1823
+ * @param text - Search query text
1824
+ * @param options - Search options (namespace, filters, top_k)
1825
+ * @returns Matching entities with similarity scores
1826
+ *
1827
+ * @example
1828
+ * ```typescript
1829
+ * // Simple semantic search
1830
+ * const results = await query.semanticSearch('photographers from New York');
1831
+ *
1832
+ * // Scoped to a specific PI (collection)
1833
+ * const scoped = await query.semanticSearch('portraits', {
1834
+ * filter: { source_pi: '01K75HQQXNTDG7BBP7PS9AWYAN' },
1835
+ * top_k: 20,
1836
+ * });
1837
+ *
1838
+ * // Filter by type
1839
+ * const people = await query.semanticSearch('artists', {
1840
+ * filter: { type: 'person' },
1841
+ * });
1842
+ *
1843
+ * // Search across merged entities from multiple source PIs
1844
+ * const merged = await query.semanticSearch('historical documents', {
1845
+ * filter: { merged_entities_source_pis: ['pi-1', 'pi-2'] },
1846
+ * });
1847
+ * ```
1848
+ */
1849
+ async semanticSearch(text, options = {}) {
1850
+ let pineconeFilter;
1851
+ if (options.filter) {
1852
+ pineconeFilter = {};
1853
+ if (options.filter.type) {
1854
+ const types = Array.isArray(options.filter.type) ? options.filter.type : [options.filter.type];
1855
+ pineconeFilter.type = types.length === 1 ? { $eq: types[0] } : { $in: types };
1856
+ }
1857
+ if (options.filter.source_pi) {
1858
+ const pis = Array.isArray(options.filter.source_pi) ? options.filter.source_pi : [options.filter.source_pi];
1859
+ pineconeFilter.source_pi = pis.length === 1 ? { $eq: pis[0] } : { $in: pis };
1860
+ }
1861
+ if (options.filter.merged_entities_source_pis) {
1862
+ const pis = Array.isArray(options.filter.merged_entities_source_pis) ? options.filter.merged_entities_source_pis : [options.filter.merged_entities_source_pis];
1863
+ pineconeFilter.merged_entities_source_pis = { $in: pis };
1864
+ }
1865
+ if (Object.keys(pineconeFilter).length === 0) {
1866
+ pineconeFilter = void 0;
1867
+ }
1868
+ }
1869
+ return this.request("/query/search/semantic", {
1870
+ method: "POST",
1871
+ body: JSON.stringify({
1872
+ text,
1873
+ namespace: options.namespace,
1874
+ filter: pineconeFilter,
1875
+ top_k: options.top_k
1876
+ })
1877
+ });
1878
+ }
1879
+ /**
1880
+ * Search for collections by semantic similarity.
1881
+ *
1882
+ * Searches the dedicated collections index for fast semantic matching.
1883
+ *
1884
+ * @param query - Search query text
1885
+ * @param options - Search options (limit, visibility filter)
1886
+ * @returns Matching collections with similarity scores
1887
+ *
1888
+ * @example
1889
+ * ```typescript
1890
+ * // Search for photography-related collections
1891
+ * const results = await query.searchCollections('photography');
1892
+ * console.log(results.collections[0].title);
1893
+ *
1894
+ * // Search only public collections
1895
+ * const publicResults = await query.searchCollections('history', {
1896
+ * visibility: 'public',
1897
+ * limit: 20,
1898
+ * });
1899
+ * ```
1900
+ */
1901
+ async searchCollections(query, options = {}) {
1902
+ return this.request("/query/search/collections", {
1903
+ method: "GET",
1904
+ query: {
1905
+ q: query,
1906
+ limit: options.limit?.toString(),
1907
+ visibility: options.visibility
1908
+ }
1909
+ });
1910
+ }
1911
+ };
1912
+
1913
+ // src/edit/types.ts
1914
+ var DEFAULT_RETRY_CONFIG = {
1915
+ maxRetries: 10,
1916
+ baseDelay: 100,
1917
+ maxDelay: 5e3,
1918
+ jitterFactor: 0.3
1919
+ };
1920
+
1921
+ // src/edit/errors.ts
1922
+ var EditError = class extends Error {
1923
+ constructor(message, code2 = "UNKNOWN_ERROR", details) {
1924
+ super(message);
1925
+ this.code = code2;
1926
+ this.details = details;
1927
+ this.name = "EditError";
1928
+ }
1929
+ };
1930
+ var EntityNotFoundError = class extends EditError {
1931
+ constructor(id) {
1932
+ super(`Entity not found: ${id}`, "ENTITY_NOT_FOUND", { id });
1933
+ this.name = "EntityNotFoundError";
1934
+ }
1935
+ };
1936
+ var CASConflictError = class extends EditError {
1937
+ constructor(id, expectedTip, actualTip) {
1938
+ super(
1939
+ `CAS conflict: entity ${id} was modified (expected ${expectedTip}, got ${actualTip})`,
1940
+ "CAS_CONFLICT",
1941
+ { id, expectedTip, actualTip }
1942
+ );
1943
+ this.name = "CASConflictError";
1944
+ }
1945
+ };
1946
+ var EntityExistsError = class extends EditError {
1947
+ constructor(id) {
1948
+ super(`Entity already exists: ${id}`, "ENTITY_EXISTS", { id });
1949
+ this.name = "EntityExistsError";
1950
+ }
1951
+ };
1952
+ var MergeError = class extends EditError {
1953
+ constructor(message, sourceId, targetId) {
1954
+ super(message, "MERGE_ERROR", { sourceId, targetId });
1955
+ this.name = "MergeError";
1956
+ }
1957
+ };
1958
+ var UnmergeError = class extends EditError {
1959
+ constructor(message, sourceId, targetId) {
1960
+ super(message, "UNMERGE_ERROR", { sourceId, targetId });
1961
+ this.name = "UnmergeError";
1962
+ }
1963
+ };
1964
+ var DeleteError = class extends EditError {
1965
+ constructor(message, id) {
1966
+ super(message, "DELETE_ERROR", { id });
1967
+ this.name = "DeleteError";
1968
+ }
1969
+ };
1970
+ var UndeleteError = class extends EditError {
1971
+ constructor(message, id) {
1972
+ super(message, "UNDELETE_ERROR", { id });
1973
+ this.name = "UndeleteError";
1974
+ }
1975
+ };
1976
+ var ReprocessError = class extends EditError {
1977
+ constructor(message, batchId) {
1978
+ super(message, "REPROCESS_ERROR", { batchId });
1979
+ this.name = "ReprocessError";
1980
+ }
1981
+ };
1982
+ var ValidationError2 = class extends EditError {
1983
+ constructor(message, field) {
1984
+ super(message, "VALIDATION_ERROR", { field });
1985
+ this.name = "ValidationError";
1986
+ }
1987
+ };
1988
+ var PermissionError = class extends EditError {
1989
+ constructor(message, id) {
1990
+ super(message, "PERMISSION_DENIED", { id });
1991
+ this.name = "PermissionError";
1992
+ }
1993
+ };
1994
+ var NetworkError2 = class extends EditError {
1995
+ constructor(message, statusCode) {
1996
+ super(message, "NETWORK_ERROR", { statusCode });
1997
+ this.name = "NetworkError";
1998
+ }
1999
+ };
2000
+ var ContentNotFoundError = class extends EditError {
2001
+ constructor(cid) {
2002
+ super(`Content not found: ${cid}`, "CONTENT_NOT_FOUND", { cid });
2003
+ this.name = "ContentNotFoundError";
2004
+ }
2005
+ };
2006
+ var IPFSError = class extends EditError {
2007
+ constructor(message) {
2008
+ super(message, "IPFS_ERROR");
2009
+ this.name = "IPFSError";
2010
+ }
2011
+ };
2012
+ var BackendError = class extends EditError {
2013
+ constructor(message) {
2014
+ super(message, "BACKEND_ERROR");
2015
+ this.name = "BackendError";
2016
+ }
2017
+ };
2018
+
2019
+ // src/edit/client.ts
2020
+ var RETRYABLE_STATUS_CODES = [409, 503];
2021
+ var RETRYABLE_ERRORS = ["ECONNRESET", "ETIMEDOUT", "fetch failed"];
2022
+ var EditClient = class {
2023
+ constructor(config) {
2024
+ this.gatewayUrl = config.gatewayUrl.replace(/\/$/, "");
2025
+ this.authToken = config.authToken;
2026
+ this.network = config.network || "main";
2027
+ this.userId = config.userId;
2028
+ this.retryConfig = { ...DEFAULT_RETRY_CONFIG, ...config.retryConfig };
2029
+ this.statusUrlTransform = config.statusUrlTransform;
2030
+ this.apiPrefix = config.apiPrefix ?? "/api";
2031
+ }
2032
+ // ===========================================================================
2033
+ // Configuration Methods
2034
+ // ===========================================================================
2035
+ /**
2036
+ * Update the auth token (useful for token refresh)
2037
+ */
2038
+ setAuthToken(token) {
2039
+ this.authToken = token;
2040
+ }
2041
+ /**
2042
+ * Set the network (main or test)
2043
+ */
2044
+ setNetwork(network) {
2045
+ this.network = network;
2046
+ }
2047
+ /**
2048
+ * Set the user ID for permission checks
2049
+ */
2050
+ setUserId(userId) {
2051
+ this.userId = userId;
2052
+ }
2053
+ // ===========================================================================
2054
+ // Internal Helpers
2055
+ // ===========================================================================
2056
+ /**
2057
+ * Build URL with API prefix
2058
+ */
2059
+ buildUrl(path2) {
2060
+ return `${this.gatewayUrl}${this.apiPrefix}${path2}`;
2061
+ }
2062
+ sleep(ms) {
2063
+ return new Promise((resolve) => setTimeout(resolve, ms));
2064
+ }
2065
+ getHeaders(contentType = "application/json") {
2066
+ const headers = {};
2067
+ if (contentType) {
2068
+ headers["Content-Type"] = contentType;
2069
+ }
2070
+ if (this.authToken) {
2071
+ headers["Authorization"] = `Bearer ${this.authToken}`;
2072
+ }
2073
+ headers["X-Arke-Network"] = this.network;
2074
+ if (this.userId) {
2075
+ headers["X-User-Id"] = this.userId;
2076
+ }
2077
+ return headers;
2078
+ }
2079
+ calculateDelay(attempt) {
2080
+ const { baseDelay, maxDelay, jitterFactor } = this.retryConfig;
2081
+ const exponentialDelay = baseDelay * Math.pow(2, attempt);
2082
+ const cappedDelay = Math.min(exponentialDelay, maxDelay);
2083
+ const jitter = cappedDelay * jitterFactor * (Math.random() * 2 - 1);
2084
+ return Math.max(0, cappedDelay + jitter);
2085
+ }
2086
+ isRetryableStatus(status) {
2087
+ return RETRYABLE_STATUS_CODES.includes(status);
2088
+ }
2089
+ isRetryableError(error) {
2090
+ const message = error.message.toLowerCase();
2091
+ return RETRYABLE_ERRORS.some((e) => message.includes(e.toLowerCase()));
2092
+ }
2093
+ /**
2094
+ * Execute a fetch with exponential backoff retry on transient errors
2095
+ */
2096
+ async fetchWithRetry(url, options, context) {
2097
+ let lastError = null;
2098
+ for (let attempt = 0; attempt <= this.retryConfig.maxRetries; attempt++) {
2099
+ try {
2100
+ const response = await fetch(url, options);
2101
+ if (this.isRetryableStatus(response.status) && attempt < this.retryConfig.maxRetries) {
2102
+ const delay = this.calculateDelay(attempt);
2103
+ lastError = new Error(`${context}: ${response.status} ${response.statusText}`);
2104
+ await this.sleep(delay);
2105
+ continue;
2106
+ }
2107
+ return response;
2108
+ } catch (error) {
2109
+ lastError = error;
2110
+ if (this.isRetryableError(lastError) && attempt < this.retryConfig.maxRetries) {
2111
+ const delay = this.calculateDelay(attempt);
2112
+ await this.sleep(delay);
2113
+ continue;
2114
+ }
2115
+ throw new NetworkError2(lastError.message);
2116
+ }
2117
+ }
2118
+ throw lastError || new NetworkError2("Request failed after retries");
2119
+ }
2120
+ /**
2121
+ * Handle common error responses and throw appropriate error types
2122
+ */
2123
+ async handleErrorResponse(response, context) {
2124
+ let errorData = {};
2125
+ try {
2126
+ errorData = await response.json();
2127
+ } catch {
2128
+ }
2129
+ const message = errorData.message || `${context}: ${response.statusText}`;
2130
+ const errorCode = errorData.error || "";
2131
+ switch (response.status) {
2132
+ case 400:
2133
+ throw new ValidationError2(message);
2134
+ case 403:
2135
+ throw new PermissionError(message);
2136
+ case 404:
2137
+ throw new EntityNotFoundError(message);
2138
+ case 409:
2139
+ if (errorCode === "CAS_FAILURE") {
2140
+ const details = errorData.details;
2141
+ throw new CASConflictError(
2142
+ context,
2143
+ details?.expect || "unknown",
2144
+ details?.actual || "unknown"
2145
+ );
2146
+ }
2147
+ if (errorCode === "CONFLICT") {
2148
+ throw new EntityExistsError(message);
2149
+ }
2150
+ throw new EditError(message, errorCode, errorData.details);
2151
+ case 503:
2152
+ if (errorCode === "IPFS_ERROR") {
2153
+ throw new IPFSError(message);
2154
+ }
2155
+ if (errorCode === "BACKEND_ERROR") {
2156
+ throw new BackendError(message);
2157
+ }
2158
+ throw new NetworkError2(message, response.status);
2159
+ default:
2160
+ throw new EditError(message, errorCode || "API_ERROR", { status: response.status });
2161
+ }
2162
+ }
2163
+ // ===========================================================================
2164
+ // Entity CRUD Operations
2165
+ // ===========================================================================
2166
+ /**
2167
+ * Create a new entity
2168
+ */
2169
+ async createEntity(request) {
2170
+ const url = this.buildUrl("/entities");
2171
+ const response = await this.fetchWithRetry(
2172
+ url,
2173
+ {
2174
+ method: "POST",
2175
+ headers: this.getHeaders(),
2176
+ body: JSON.stringify(request)
2177
+ },
2178
+ "Create entity"
2179
+ );
2180
+ if (!response.ok) {
2181
+ await this.handleErrorResponse(response, "Create entity");
2182
+ }
2183
+ return response.json();
2184
+ }
2185
+ /**
2186
+ * Get an entity by ID
2187
+ */
2188
+ async getEntity(id) {
2189
+ const url = this.buildUrl(`/entities/${encodeURIComponent(id)}`);
2190
+ const response = await this.fetchWithRetry(
2191
+ url,
2192
+ { headers: this.getHeaders() },
2193
+ `Get entity ${id}`
2194
+ );
2195
+ if (!response.ok) {
2196
+ await this.handleErrorResponse(response, `Get entity ${id}`);
2197
+ }
2198
+ return response.json();
2199
+ }
2200
+ /**
2201
+ * List entities with pagination
2202
+ */
2203
+ async listEntities(options = {}) {
2204
+ const params = new URLSearchParams();
2205
+ if (options.limit) params.set("limit", options.limit.toString());
2206
+ if (options.cursor) params.set("cursor", options.cursor);
2207
+ if (options.include_metadata) params.set("include_metadata", "true");
2208
+ const queryString = params.toString();
2209
+ const url = this.buildUrl(`/entities${queryString ? `?${queryString}` : ""}`);
2210
+ const response = await this.fetchWithRetry(url, { headers: this.getHeaders() }, "List entities");
2211
+ if (!response.ok) {
2212
+ await this.handleErrorResponse(response, "List entities");
2213
+ }
2214
+ return response.json();
2215
+ }
2216
+ /**
2217
+ * Update an entity (append new version)
2218
+ */
2219
+ async updateEntity(id, update) {
2220
+ const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/versions`);
2221
+ const response = await this.fetchWithRetry(
2222
+ url,
2223
+ {
2224
+ method: "POST",
2225
+ headers: this.getHeaders(),
2226
+ body: JSON.stringify(update)
2227
+ },
2228
+ `Update entity ${id}`
2229
+ );
2230
+ if (!response.ok) {
2231
+ await this.handleErrorResponse(response, `Update entity ${id}`);
2232
+ }
2233
+ return response.json();
2234
+ }
2235
+ // ===========================================================================
2236
+ // Version Operations
2237
+ // ===========================================================================
2238
+ /**
2239
+ * List version history for an entity
2240
+ */
2241
+ async listVersions(id, options = {}) {
2242
+ const params = new URLSearchParams();
2243
+ if (options.limit) params.set("limit", options.limit.toString());
2244
+ if (options.cursor) params.set("cursor", options.cursor);
2245
+ const queryString = params.toString();
2246
+ const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/versions${queryString ? `?${queryString}` : ""}`);
2247
+ const response = await this.fetchWithRetry(url, { headers: this.getHeaders() }, `List versions for ${id}`);
2248
+ if (!response.ok) {
2249
+ await this.handleErrorResponse(response, `List versions for ${id}`);
2250
+ }
2251
+ return response.json();
2252
+ }
2253
+ /**
2254
+ * Get a specific version of an entity
2255
+ */
2256
+ async getVersion(id, selector) {
2257
+ const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/versions/${encodeURIComponent(selector)}`);
2258
+ const response = await this.fetchWithRetry(
2259
+ url,
2260
+ { headers: this.getHeaders() },
2261
+ `Get version ${selector} for ${id}`
2262
+ );
2263
+ if (!response.ok) {
2264
+ await this.handleErrorResponse(response, `Get version ${selector} for ${id}`);
2265
+ }
2266
+ return response.json();
2267
+ }
2268
+ /**
2269
+ * Resolve an entity ID to its current tip CID (fast lookup)
2270
+ */
2271
+ async resolve(id) {
2272
+ const url = this.buildUrl(`/resolve/${encodeURIComponent(id)}`);
2273
+ const response = await this.fetchWithRetry(
2274
+ url,
2275
+ { headers: this.getHeaders() },
2276
+ `Resolve ${id}`
2277
+ );
2278
+ if (!response.ok) {
2279
+ await this.handleErrorResponse(response, `Resolve ${id}`);
2280
+ }
2281
+ return response.json();
2282
+ }
2283
+ // ===========================================================================
2284
+ // Hierarchy Operations
2285
+ // ===========================================================================
2286
+ /**
2287
+ * Update parent-child hierarchy relationships
2288
+ */
2289
+ async updateHierarchy(request) {
2290
+ const apiRequest = {
2291
+ parent_pi: request.parent_id,
2292
+ expect_tip: request.expect_tip,
2293
+ add_children: request.add_children,
2294
+ remove_children: request.remove_children,
2295
+ note: request.note
2296
+ };
2297
+ const url = this.buildUrl("/hierarchy");
2298
+ const response = await this.fetchWithRetry(
2299
+ url,
2300
+ {
2301
+ method: "POST",
2302
+ headers: this.getHeaders(),
2303
+ body: JSON.stringify(apiRequest)
2304
+ },
2305
+ `Update hierarchy for ${request.parent_id}`
2306
+ );
2307
+ if (!response.ok) {
2308
+ await this.handleErrorResponse(response, `Update hierarchy for ${request.parent_id}`);
2309
+ }
2310
+ return response.json();
2311
+ }
2312
+ // ===========================================================================
2313
+ // Merge Operations
2314
+ // ===========================================================================
2315
+ /**
2316
+ * Merge source entity into target entity
2317
+ */
2318
+ async mergeEntity(sourceId, request) {
2319
+ const url = this.buildUrl(`/entities/${encodeURIComponent(sourceId)}/merge`);
2320
+ const response = await this.fetchWithRetry(
2321
+ url,
2322
+ {
2323
+ method: "POST",
2324
+ headers: this.getHeaders(),
2325
+ body: JSON.stringify(request)
2326
+ },
2327
+ `Merge ${sourceId} into ${request.target_id}`
2328
+ );
2329
+ if (!response.ok) {
2330
+ try {
2331
+ const error = await response.json();
2332
+ throw new MergeError(
2333
+ error.message || `Merge failed: ${response.statusText}`,
2334
+ sourceId,
2335
+ request.target_id
2336
+ );
2337
+ } catch (e) {
2338
+ if (e instanceof MergeError) throw e;
2339
+ await this.handleErrorResponse(response, `Merge ${sourceId}`);
2340
+ }
2341
+ }
2342
+ return response.json();
2343
+ }
2344
+ /**
2345
+ * Unmerge (restore) a previously merged entity
2346
+ */
2347
+ async unmergeEntity(sourceId, request) {
2348
+ const url = this.buildUrl(`/entities/${encodeURIComponent(sourceId)}/unmerge`);
2349
+ const response = await this.fetchWithRetry(
2350
+ url,
2351
+ {
2352
+ method: "POST",
2353
+ headers: this.getHeaders(),
2354
+ body: JSON.stringify(request)
2355
+ },
2356
+ `Unmerge ${sourceId}`
2357
+ );
2358
+ if (!response.ok) {
2359
+ try {
2360
+ const error = await response.json();
2361
+ throw new UnmergeError(
2362
+ error.message || `Unmerge failed: ${response.statusText}`,
2363
+ sourceId,
2364
+ request.target_id
2365
+ );
2366
+ } catch (e) {
2367
+ if (e instanceof UnmergeError) throw e;
2368
+ await this.handleErrorResponse(response, `Unmerge ${sourceId}`);
2369
+ }
2370
+ }
2371
+ return response.json();
2372
+ }
2373
+ // ===========================================================================
2374
+ // Delete Operations
2375
+ // ===========================================================================
2376
+ /**
2377
+ * Soft delete an entity (creates tombstone, preserves history)
2378
+ */
2379
+ async deleteEntity(id, request) {
2380
+ const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/delete`);
2381
+ const response = await this.fetchWithRetry(
2382
+ url,
2383
+ {
2384
+ method: "POST",
2385
+ headers: this.getHeaders(),
2386
+ body: JSON.stringify(request)
2387
+ },
2388
+ `Delete ${id}`
2389
+ );
2390
+ if (!response.ok) {
2391
+ try {
2392
+ const error = await response.json();
2393
+ throw new DeleteError(error.message || `Delete failed: ${response.statusText}`, id);
2394
+ } catch (e) {
2395
+ if (e instanceof DeleteError) throw e;
2396
+ await this.handleErrorResponse(response, `Delete ${id}`);
2397
+ }
2398
+ }
2399
+ return response.json();
2400
+ }
2401
+ /**
2402
+ * Restore a deleted entity
2403
+ */
2404
+ async undeleteEntity(id, request) {
2405
+ const url = this.buildUrl(`/entities/${encodeURIComponent(id)}/undelete`);
2406
+ const response = await this.fetchWithRetry(
2407
+ url,
2408
+ {
2409
+ method: "POST",
2410
+ headers: this.getHeaders(),
2411
+ body: JSON.stringify(request)
2412
+ },
2413
+ `Undelete ${id}`
2414
+ );
2415
+ if (!response.ok) {
2416
+ try {
2417
+ const error = await response.json();
2418
+ throw new UndeleteError(error.message || `Undelete failed: ${response.statusText}`, id);
2419
+ } catch (e) {
2420
+ if (e instanceof UndeleteError) throw e;
2421
+ await this.handleErrorResponse(response, `Undelete ${id}`);
2422
+ }
2423
+ }
2424
+ return response.json();
2425
+ }
2426
+ // ===========================================================================
2427
+ // Content Operations
2428
+ // ===========================================================================
2429
+ /**
2430
+ * Upload files to IPFS
2431
+ */
2432
+ async upload(files) {
2433
+ let formData;
2434
+ if (files instanceof FormData) {
2435
+ formData = files;
2436
+ } else {
2437
+ formData = new FormData();
2438
+ const fileArray = Array.isArray(files) ? files : [files];
2439
+ for (const file of fileArray) {
2440
+ if (file instanceof File) {
2441
+ formData.append("file", file, file.name);
2442
+ } else {
2443
+ formData.append("file", file, "file");
2444
+ }
2445
+ }
2446
+ }
2447
+ const url = this.buildUrl("/upload");
2448
+ const response = await this.fetchWithRetry(
2449
+ url,
2450
+ {
2451
+ method: "POST",
2452
+ headers: this.getHeaders(null),
2453
+ // No Content-Type for multipart
2454
+ body: formData
2455
+ },
2456
+ "Upload files"
2457
+ );
2458
+ if (!response.ok) {
2459
+ await this.handleErrorResponse(response, "Upload files");
2460
+ }
2461
+ return response.json();
2462
+ }
2463
+ /**
2464
+ * Upload text content and return CID
2465
+ */
2466
+ async uploadContent(content, filename) {
2467
+ const blob = new Blob([content], { type: "text/plain" });
2468
+ const file = new File([blob], filename, { type: "text/plain" });
2469
+ const [result] = await this.upload(file);
2470
+ return result.cid;
2471
+ }
2472
+ /**
2473
+ * Download file content by CID
2474
+ */
2475
+ async getContent(cid) {
2476
+ const url = this.buildUrl(`/cat/${encodeURIComponent(cid)}`);
2477
+ const response = await this.fetchWithRetry(
2478
+ url,
2479
+ { headers: this.getHeaders() },
2480
+ `Get content ${cid}`
2481
+ );
2482
+ if (response.status === 404) {
2483
+ throw new ContentNotFoundError(cid);
2484
+ }
2485
+ if (!response.ok) {
2486
+ await this.handleErrorResponse(response, `Get content ${cid}`);
2487
+ }
2488
+ return response.text();
2489
+ }
2490
+ /**
2491
+ * Download a DAG node (JSON) by CID
2492
+ */
2493
+ async getDag(cid) {
2494
+ const url = this.buildUrl(`/dag/${encodeURIComponent(cid)}`);
2495
+ const response = await this.fetchWithRetry(
2496
+ url,
2497
+ { headers: this.getHeaders() },
2498
+ `Get DAG ${cid}`
2499
+ );
2500
+ if (response.status === 404) {
2501
+ throw new ContentNotFoundError(cid);
2502
+ }
2503
+ if (!response.ok) {
2504
+ await this.handleErrorResponse(response, `Get DAG ${cid}`);
2505
+ }
2506
+ return response.json();
2507
+ }
2508
+ // ===========================================================================
2509
+ // Arke Origin Operations
2510
+ // ===========================================================================
2511
+ /**
2512
+ * Get the Arke origin block (genesis entity)
2513
+ */
2514
+ async getArke() {
2515
+ const url = this.buildUrl("/arke");
2516
+ const response = await this.fetchWithRetry(
2517
+ url,
2518
+ { headers: this.getHeaders() },
2519
+ "Get Arke"
2520
+ );
2521
+ if (!response.ok) {
2522
+ await this.handleErrorResponse(response, "Get Arke");
2523
+ }
2524
+ return response.json();
2525
+ }
2526
+ /**
2527
+ * Initialize the Arke origin block (creates if doesn't exist)
2528
+ */
2529
+ async initArke() {
2530
+ const url = this.buildUrl("/arke/init");
2531
+ const response = await this.fetchWithRetry(
2532
+ url,
2533
+ {
2534
+ method: "POST",
2535
+ headers: this.getHeaders()
2536
+ },
2537
+ "Init Arke"
2538
+ );
2539
+ if (!response.ok) {
2540
+ await this.handleErrorResponse(response, "Init Arke");
2541
+ }
2542
+ return response.json();
2543
+ }
2544
+ // ===========================================================================
2545
+ // Reprocess API Operations (via /reprocess/*)
2546
+ // ===========================================================================
2547
+ /**
2548
+ * Trigger reprocessing for an entity
2549
+ */
2550
+ async reprocess(request) {
2551
+ const response = await this.fetchWithRetry(
2552
+ `${this.gatewayUrl}/reprocess/reprocess`,
2553
+ {
2554
+ method: "POST",
2555
+ headers: this.getHeaders(),
2556
+ body: JSON.stringify({
2557
+ pi: request.pi,
2558
+ phases: request.phases,
2559
+ cascade: request.cascade,
2560
+ options: request.options
2561
+ })
2562
+ },
2563
+ `Reprocess ${request.pi}`
2564
+ );
2565
+ if (response.status === 403) {
2566
+ const error = await response.json().catch(() => ({}));
2567
+ throw new PermissionError(
2568
+ error.message || `Permission denied to reprocess ${request.pi}`,
2569
+ request.pi
2570
+ );
2571
+ }
2572
+ if (!response.ok) {
2573
+ const error = await response.json().catch(() => ({}));
2574
+ throw new ReprocessError(error.message || `Reprocess failed: ${response.statusText}`);
2575
+ }
2576
+ return response.json();
2577
+ }
2578
+ /**
2579
+ * Get reprocessing status by batch ID
2580
+ */
2581
+ async getReprocessStatus(statusUrl, isFirstPoll = false) {
2582
+ const fetchUrl = this.statusUrlTransform ? this.statusUrlTransform(statusUrl) : statusUrl;
2583
+ const delay = isFirstPoll ? 3e3 : this.retryConfig.baseDelay;
2584
+ if (isFirstPoll) {
2585
+ await this.sleep(delay);
2586
+ }
2587
+ const response = await this.fetchWithRetry(
2588
+ fetchUrl,
2589
+ { headers: this.getHeaders() },
2590
+ "Get reprocess status"
2591
+ );
2592
+ if (!response.ok) {
2593
+ throw new EditError(
2594
+ `Failed to fetch reprocess status: ${response.statusText}`,
2595
+ "STATUS_ERROR",
2596
+ { status: response.status }
2597
+ );
2598
+ }
2599
+ return response.json();
2600
+ }
2601
+ // ===========================================================================
2602
+ // Utility Methods
2603
+ // ===========================================================================
2604
+ /**
2605
+ * Execute an operation with automatic CAS retry
2606
+ */
2607
+ async withCAS(id, operation, maxRetries = 3) {
2608
+ let lastError = null;
2609
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
2610
+ try {
2611
+ const entity = await this.getEntity(id);
2612
+ return await operation(entity);
2613
+ } catch (error) {
2614
+ if (error instanceof CASConflictError && attempt < maxRetries - 1) {
2615
+ lastError = error;
2616
+ const delay = this.calculateDelay(attempt);
2617
+ await this.sleep(delay);
2618
+ continue;
2619
+ }
2620
+ throw error;
2621
+ }
2622
+ }
2623
+ throw lastError || new EditError("withCAS failed after retries");
2624
+ }
2625
+ };
2626
+
2627
+ // src/edit/diff.ts
2628
+ import * as Diff from "diff";
2629
+ var DiffEngine = class {
2630
+ /**
2631
+ * Compute diff between two strings
2632
+ */
2633
+ static diff(original, modified) {
2634
+ const changes = Diff.diffLines(original, modified);
2635
+ const diffs = [];
2636
+ let lineNumber = 1;
2637
+ for (const change of changes) {
2638
+ if (change.added) {
2639
+ diffs.push({
2640
+ type: "addition",
2641
+ modified: change.value.trimEnd(),
2642
+ lineNumber
2643
+ });
2644
+ } else if (change.removed) {
2645
+ diffs.push({
2646
+ type: "deletion",
2647
+ original: change.value.trimEnd(),
2648
+ lineNumber
2649
+ });
2650
+ } else {
2651
+ const lines = change.value.split("\n").length - 1;
2652
+ lineNumber += lines;
2653
+ }
2654
+ if (change.added) {
2655
+ lineNumber += change.value.split("\n").length - 1;
2656
+ }
2657
+ }
2658
+ return diffs;
2659
+ }
2660
+ /**
2661
+ * Compute word-level diff for more granular changes
2662
+ */
2663
+ static diffWords(original, modified) {
2664
+ const changes = Diff.diffWords(original, modified);
2665
+ const diffs = [];
2666
+ for (const change of changes) {
2667
+ if (change.added) {
2668
+ diffs.push({
2669
+ type: "addition",
2670
+ modified: change.value
2671
+ });
2672
+ } else if (change.removed) {
2673
+ diffs.push({
2674
+ type: "deletion",
2675
+ original: change.value
2676
+ });
2677
+ }
2678
+ }
2679
+ return diffs;
2680
+ }
2681
+ /**
2682
+ * Create a ComponentDiff from original and modified content
2683
+ */
2684
+ static createComponentDiff(componentName, original, modified) {
2685
+ const diffs = this.diff(original, modified);
2686
+ const hasChanges = diffs.length > 0;
2687
+ let summary;
2688
+ if (!hasChanges) {
2689
+ summary = "No changes";
2690
+ } else {
2691
+ const additions = diffs.filter((d) => d.type === "addition").length;
2692
+ const deletions = diffs.filter((d) => d.type === "deletion").length;
2693
+ const parts = [];
2694
+ if (additions > 0) parts.push(`${additions} addition${additions > 1 ? "s" : ""}`);
2695
+ if (deletions > 0) parts.push(`${deletions} deletion${deletions > 1 ? "s" : ""}`);
2696
+ summary = parts.join(", ");
2697
+ }
2698
+ return {
2699
+ componentName,
2700
+ diffs,
2701
+ summary,
2702
+ hasChanges
2703
+ };
2704
+ }
2705
+ /**
2706
+ * Format diffs for AI prompt consumption
2707
+ */
2708
+ static formatForPrompt(diffs) {
2709
+ if (diffs.length === 0) {
2710
+ return "No changes detected.";
2711
+ }
2712
+ const lines = [];
2713
+ for (const diff of diffs) {
2714
+ const linePrefix = diff.lineNumber ? `Line ${diff.lineNumber}: ` : "";
2715
+ if (diff.type === "addition") {
2716
+ lines.push(`${linePrefix}+ ${diff.modified}`);
2717
+ } else if (diff.type === "deletion") {
2718
+ lines.push(`${linePrefix}- ${diff.original}`);
2719
+ } else if (diff.type === "change") {
2720
+ lines.push(`${linePrefix}"${diff.original}" \u2192 "${diff.modified}"`);
2721
+ }
2722
+ }
2723
+ return lines.join("\n");
2724
+ }
2725
+ /**
2726
+ * Format component diffs for AI prompt
2727
+ */
2728
+ static formatComponentDiffsForPrompt(componentDiffs) {
2729
+ const sections = [];
2730
+ for (const cd of componentDiffs) {
2731
+ if (!cd.hasChanges) continue;
2732
+ sections.push(`## Changes to ${cd.componentName}:`);
2733
+ sections.push(this.formatForPrompt(cd.diffs));
2734
+ sections.push("");
2735
+ }
2736
+ return sections.join("\n");
2737
+ }
2738
+ /**
2739
+ * Create a unified diff view
2740
+ */
2741
+ static unifiedDiff(original, modified, options) {
2742
+ const filename = options?.filename || "content";
2743
+ const patch = Diff.createPatch(filename, original, modified, "", "", {
2744
+ context: options?.context ?? 3
2745
+ });
2746
+ return patch;
2747
+ }
2748
+ /**
2749
+ * Extract corrections from diffs (specific text replacements)
2750
+ */
2751
+ static extractCorrections(original, modified, sourceFile) {
2752
+ const wordDiffs = Diff.diffWords(original, modified);
2753
+ const corrections = [];
2754
+ let i = 0;
2755
+ while (i < wordDiffs.length) {
2756
+ const current = wordDiffs[i];
2757
+ if (current.removed && i + 1 < wordDiffs.length && wordDiffs[i + 1].added) {
2758
+ const removed = current.value.trim();
2759
+ const added = wordDiffs[i + 1].value.trim();
2760
+ if (removed && added && removed !== added) {
2761
+ corrections.push({
2762
+ original: removed,
2763
+ corrected: added,
2764
+ sourceFile
2765
+ });
2766
+ }
2767
+ i += 2;
2768
+ } else {
2769
+ i++;
2770
+ }
2771
+ }
2772
+ return corrections;
2773
+ }
2774
+ /**
2775
+ * Check if two strings are meaningfully different
2776
+ * (ignoring whitespace differences)
2777
+ */
2778
+ static hasSignificantChanges(original, modified) {
2779
+ const normalizedOriginal = original.replace(/\s+/g, " ").trim();
2780
+ const normalizedModified = modified.replace(/\s+/g, " ").trim();
2781
+ return normalizedOriginal !== normalizedModified;
2782
+ }
2783
+ };
2784
+
2785
+ // src/edit/prompts.ts
2786
+ var PromptBuilder = class {
2787
+ /**
2788
+ * Build prompt for AI-first mode (user provides instructions)
2789
+ */
2790
+ static buildAIPrompt(userPrompt, component, entityContext, currentContent) {
2791
+ const sections = [];
2792
+ sections.push(`## Instructions for ${component}`);
2793
+ sections.push(userPrompt);
2794
+ sections.push("");
2795
+ sections.push("## Entity Context");
2796
+ sections.push(`- PI: ${entityContext.pi}`);
2797
+ sections.push(`- Current version: ${entityContext.ver}`);
2798
+ if (entityContext.parentPi) {
2799
+ sections.push(`- Parent: ${entityContext.parentPi}`);
2800
+ }
2801
+ if (entityContext.childrenCount > 0) {
2802
+ sections.push(`- Children: ${entityContext.childrenCount}`);
2803
+ }
2804
+ sections.push("");
2805
+ if (currentContent) {
2806
+ sections.push(`## Current ${component} content for reference:`);
2807
+ sections.push("```");
2808
+ sections.push(currentContent.slice(0, 2e3));
2809
+ if (currentContent.length > 2e3) {
2810
+ sections.push("... [truncated]");
2811
+ }
2812
+ sections.push("```");
2813
+ }
2814
+ return sections.join("\n");
2815
+ }
2816
+ /**
2817
+ * Build prompt incorporating manual edits and diffs
2818
+ */
2819
+ static buildEditReviewPrompt(componentDiffs, corrections, component, userInstructions) {
2820
+ const sections = [];
2821
+ sections.push("## Manual Edits Made");
2822
+ sections.push("");
2823
+ sections.push("The following manual edits were made to this entity:");
2824
+ sections.push("");
2825
+ const diffContent = DiffEngine.formatComponentDiffsForPrompt(componentDiffs);
2826
+ if (diffContent) {
2827
+ sections.push(diffContent);
2828
+ }
2829
+ if (corrections.length > 0) {
2830
+ sections.push("## Corrections Identified");
2831
+ sections.push("");
2832
+ for (const correction of corrections) {
2833
+ const source = correction.sourceFile ? ` (in ${correction.sourceFile})` : "";
2834
+ sections.push(`- "${correction.original}" \u2192 "${correction.corrected}"${source}`);
2835
+ }
2836
+ sections.push("");
2837
+ }
2838
+ sections.push("## Instructions");
2839
+ if (userInstructions) {
2840
+ sections.push(userInstructions);
2841
+ } else {
2842
+ sections.push(
2843
+ `Update the ${component} to accurately reflect these changes. Ensure any corrections are incorporated and the content is consistent.`
2844
+ );
2845
+ }
2846
+ sections.push("");
2847
+ sections.push("## Guidance");
2848
+ switch (component) {
2849
+ case "pinax":
2850
+ sections.push(
2851
+ "Update metadata fields to reflect any corrections. Pay special attention to dates, names, and other factual information that may have been corrected."
2852
+ );
2853
+ break;
2854
+ case "description":
2855
+ sections.push(
2856
+ "Regenerate the description incorporating the changes. Maintain the overall tone and structure while ensuring accuracy based on the corrections."
2857
+ );
2858
+ break;
2859
+ case "cheimarros":
2860
+ sections.push(
2861
+ "Update the knowledge graph to reflect any new or corrected entities, relationships, and facts identified in the changes."
2862
+ );
2863
+ break;
2864
+ }
2865
+ return sections.join("\n");
2866
+ }
2867
+ /**
2868
+ * Build cascade-aware prompt additions
2869
+ */
2870
+ static buildCascadePrompt(basePrompt, cascadeContext) {
2871
+ const sections = [basePrompt];
2872
+ sections.push("");
2873
+ sections.push("## Cascade Context");
2874
+ sections.push("");
2875
+ sections.push(
2876
+ "This edit is part of a cascading update. After updating this entity, parent entities will also be updated to reflect these changes."
2877
+ );
2878
+ sections.push("");
2879
+ if (cascadeContext.path.length > 1) {
2880
+ sections.push(`Cascade path: ${cascadeContext.path.join(" \u2192 ")}`);
2881
+ sections.push(`Depth: ${cascadeContext.depth}`);
2882
+ }
2883
+ if (cascadeContext.stopAtPi) {
2884
+ sections.push(`Cascade will stop at: ${cascadeContext.stopAtPi}`);
2885
+ }
2886
+ sections.push("");
2887
+ sections.push(
2888
+ "Ensure the content accurately represents the source material so parent aggregations will be correct."
2889
+ );
2890
+ return sections.join("\n");
2891
+ }
2892
+ /**
2893
+ * Build a general prompt combining multiple instructions
2894
+ */
2895
+ static buildCombinedPrompt(generalPrompt, componentPrompt, component) {
2896
+ const sections = [];
2897
+ if (generalPrompt) {
2898
+ sections.push("## General Instructions");
2899
+ sections.push(generalPrompt);
2900
+ sections.push("");
2901
+ }
2902
+ if (componentPrompt) {
2903
+ sections.push(`## Specific Instructions for ${component}`);
2904
+ sections.push(componentPrompt);
2905
+ sections.push("");
2906
+ }
2907
+ if (sections.length === 0) {
2908
+ return `Regenerate the ${component} based on the current entity content.`;
2909
+ }
2910
+ return sections.join("\n");
2911
+ }
2912
+ /**
2913
+ * Build prompt for correction-based updates
2914
+ */
2915
+ static buildCorrectionPrompt(corrections) {
2916
+ if (corrections.length === 0) {
2917
+ return "";
2918
+ }
2919
+ const sections = [];
2920
+ sections.push("## Corrections Applied");
2921
+ sections.push("");
2922
+ sections.push("The following corrections were made to the source content:");
2923
+ sections.push("");
2924
+ for (const correction of corrections) {
2925
+ const source = correction.sourceFile ? ` in ${correction.sourceFile}` : "";
2926
+ sections.push(`- "${correction.original}" was corrected to "${correction.corrected}"${source}`);
2927
+ if (correction.context) {
2928
+ sections.push(` Context: ${correction.context}`);
2929
+ }
2930
+ }
2931
+ sections.push("");
2932
+ sections.push(
2933
+ "Update the metadata and description to reflect these corrections. Previous content may have contained errors based on the incorrect text."
2934
+ );
2935
+ return sections.join("\n");
2936
+ }
2937
+ /**
2938
+ * Get component-specific regeneration guidance
2939
+ */
2940
+ static getComponentGuidance(component) {
2941
+ switch (component) {
2942
+ case "pinax":
2943
+ return "Extract and structure metadata including: institution, creator, title, date range, subjects, type, and other relevant fields. Ensure accuracy based on the source content.";
2944
+ case "description":
2945
+ return "Generate a clear, informative description that summarizes the entity content. Focus on what the material contains, its historical significance, and context. Write for a general audience unless otherwise specified.";
2946
+ case "cheimarros":
2947
+ return "Extract entities (people, places, organizations, events) and their relationships. Build a knowledge graph that captures the key facts and connections in the content.";
2948
+ default:
2949
+ return "";
2950
+ }
2951
+ }
2952
+ };
2953
+
2954
+ // src/edit/session.ts
2955
+ var DEFAULT_SCOPE = {
2956
+ components: [],
2957
+ cascade: false
2958
+ };
2959
+ var DEFAULT_POLL_OPTIONS = {
2960
+ intervalMs: 2e3,
2961
+ timeoutMs: 3e5
2962
+ // 5 minutes
2963
+ };
2964
+ var EditSession = class {
2965
+ constructor(client, pi, config) {
2966
+ this.entity = null;
2967
+ this.loadedComponents = {};
2968
+ // AI mode state
2969
+ this.prompts = {};
2970
+ // Manual mode state
2971
+ this.editedContent = {};
2972
+ this.corrections = [];
2973
+ // Scope
2974
+ this.scope = { ...DEFAULT_SCOPE };
2975
+ // Execution state
2976
+ this.submitting = false;
2977
+ this.result = null;
2978
+ this.statusUrl = null;
2979
+ this.client = client;
2980
+ this.pi = pi;
2981
+ this.mode = config?.mode ?? "ai-prompt";
2982
+ this.aiReviewEnabled = config?.aiReviewEnabled ?? true;
2983
+ }
2984
+ // ===========================================================================
2985
+ // Loading
2986
+ // ===========================================================================
2987
+ /**
2988
+ * Load the entity and its key components
2989
+ */
2990
+ async load() {
2991
+ this.entity = await this.client.getEntity(this.pi);
2992
+ const priorityComponents = ["description.md", "pinax.json", "cheimarros.json"];
2993
+ await Promise.all(
2994
+ priorityComponents.map(async (name) => {
2995
+ const cid = this.entity.components[name];
2996
+ if (cid) {
2997
+ try {
2998
+ this.loadedComponents[name] = await this.client.getContent(cid);
2999
+ } catch {
3000
+ }
3001
+ }
3002
+ })
3003
+ );
3004
+ }
3005
+ /**
3006
+ * Load a specific component on demand
3007
+ */
3008
+ async loadComponent(name) {
3009
+ if (this.loadedComponents[name]) {
3010
+ return this.loadedComponents[name];
3011
+ }
3012
+ if (!this.entity) {
3013
+ throw new ValidationError2("Session not loaded");
3014
+ }
3015
+ const cid = this.entity.components[name];
3016
+ if (!cid) {
3017
+ return void 0;
3018
+ }
3019
+ const content = await this.client.getContent(cid);
3020
+ this.loadedComponents[name] = content;
3021
+ return content;
3022
+ }
3023
+ /**
3024
+ * Get the loaded entity
3025
+ */
3026
+ getEntity() {
3027
+ if (!this.entity) {
3028
+ throw new ValidationError2("Session not loaded. Call load() first.");
3029
+ }
3030
+ return this.entity;
3031
+ }
3032
+ /**
3033
+ * Get loaded component content
3034
+ */
3035
+ getComponents() {
3036
+ return { ...this.loadedComponents };
3037
+ }
3038
+ // ===========================================================================
3039
+ // AI Prompt Mode
3040
+ // ===========================================================================
3041
+ /**
3042
+ * Set a prompt for AI regeneration
3043
+ */
3044
+ setPrompt(target, prompt) {
3045
+ if (this.mode === "manual-only") {
3046
+ throw new ValidationError2("Cannot set prompts in manual-only mode");
3047
+ }
3048
+ this.prompts[target] = prompt;
3049
+ }
3050
+ /**
3051
+ * Get all prompts
3052
+ */
3053
+ getPrompts() {
3054
+ return { ...this.prompts };
3055
+ }
3056
+ /**
3057
+ * Clear a prompt
3058
+ */
3059
+ clearPrompt(target) {
3060
+ delete this.prompts[target];
3061
+ }
3062
+ // ===========================================================================
3063
+ // Manual Edit Mode
3064
+ // ===========================================================================
3065
+ /**
3066
+ * Set edited content for a component
3067
+ */
3068
+ setContent(componentName, content) {
3069
+ if (this.mode === "ai-prompt") {
3070
+ throw new ValidationError2("Cannot set content in ai-prompt mode");
3071
+ }
3072
+ this.editedContent[componentName] = content;
3073
+ }
3074
+ /**
3075
+ * Get all edited content
3076
+ */
3077
+ getEditedContent() {
3078
+ return { ...this.editedContent };
3079
+ }
3080
+ /**
3081
+ * Clear edited content for a component
3082
+ */
3083
+ clearContent(componentName) {
3084
+ delete this.editedContent[componentName];
3085
+ }
3086
+ /**
3087
+ * Add a correction (for OCR fixes, etc.)
3088
+ */
3089
+ addCorrection(original, corrected, sourceFile) {
3090
+ this.corrections.push({ original, corrected, sourceFile });
3091
+ }
3092
+ /**
3093
+ * Get all corrections
3094
+ */
3095
+ getCorrections() {
3096
+ return [...this.corrections];
3097
+ }
3098
+ /**
3099
+ * Clear corrections
3100
+ */
3101
+ clearCorrections() {
3102
+ this.corrections = [];
3103
+ }
3104
+ // ===========================================================================
3105
+ // Scope Configuration
3106
+ // ===========================================================================
3107
+ /**
3108
+ * Set the edit scope
3109
+ */
3110
+ setScope(scope) {
3111
+ this.scope = { ...this.scope, ...scope };
3112
+ }
3113
+ /**
3114
+ * Get the current scope
3115
+ */
3116
+ getScope() {
3117
+ return { ...this.scope };
3118
+ }
3119
+ // ===========================================================================
3120
+ // Preview & Summary
3121
+ // ===========================================================================
3122
+ /**
3123
+ * Get diffs for manual changes
3124
+ */
3125
+ getDiff() {
3126
+ const diffs = [];
3127
+ for (const [name, edited] of Object.entries(this.editedContent)) {
3128
+ const original = this.loadedComponents[name] || "";
3129
+ if (DiffEngine.hasSignificantChanges(original, edited)) {
3130
+ diffs.push(DiffEngine.createComponentDiff(name, original, edited));
3131
+ }
3132
+ }
3133
+ return diffs;
3134
+ }
3135
+ /**
3136
+ * Preview what prompts will be sent to AI
3137
+ */
3138
+ previewPrompt() {
3139
+ const result = {};
3140
+ if (!this.entity) return result;
3141
+ const entityContext = {
3142
+ pi: this.entity.id,
3143
+ ver: this.entity.ver,
3144
+ parentPi: this.entity.parent_pi,
3145
+ childrenCount: this.entity.children_pi?.length ?? 0,
3146
+ currentContent: this.loadedComponents
3147
+ };
3148
+ for (const component of this.scope.components) {
3149
+ let prompt;
3150
+ if (this.mode === "ai-prompt") {
3151
+ const componentPrompt = this.prompts[component];
3152
+ const generalPrompt = this.prompts["general"];
3153
+ const combined = PromptBuilder.buildCombinedPrompt(generalPrompt, componentPrompt, component);
3154
+ prompt = PromptBuilder.buildAIPrompt(
3155
+ combined,
3156
+ component,
3157
+ entityContext,
3158
+ this.loadedComponents[`${component}.json`] || this.loadedComponents[`${component}.md`]
3159
+ );
3160
+ } else {
3161
+ const diffs = this.getDiff();
3162
+ const userInstructions = this.prompts["general"] || this.prompts[component];
3163
+ prompt = PromptBuilder.buildEditReviewPrompt(diffs, this.corrections, component, userInstructions);
3164
+ }
3165
+ if (this.scope.cascade) {
3166
+ prompt = PromptBuilder.buildCascadePrompt(prompt, {
3167
+ path: [this.entity.id, this.entity.parent_pi || "root"].filter(Boolean),
3168
+ depth: 0,
3169
+ stopAtPi: this.scope.stopAtPi
3170
+ });
3171
+ }
3172
+ result[component] = prompt;
3173
+ }
3174
+ return result;
3175
+ }
3176
+ /**
3177
+ * Get a summary of pending changes
3178
+ */
3179
+ getChangeSummary() {
3180
+ const diffs = this.getDiff();
3181
+ const hasManualEdits = diffs.some((d) => d.hasChanges);
3182
+ return {
3183
+ mode: this.mode,
3184
+ hasManualEdits,
3185
+ editedComponents: Object.keys(this.editedContent),
3186
+ corrections: [...this.corrections],
3187
+ prompts: { ...this.prompts },
3188
+ scope: { ...this.scope },
3189
+ willRegenerate: [...this.scope.components],
3190
+ willCascade: this.scope.cascade,
3191
+ willSave: hasManualEdits,
3192
+ willReprocess: this.scope.components.length > 0
3193
+ };
3194
+ }
3195
+ // ===========================================================================
3196
+ // Execution
3197
+ // ===========================================================================
3198
+ /**
3199
+ * Submit changes (saves first if manual edits, then reprocesses)
3200
+ */
3201
+ async submit(note) {
3202
+ if (this.submitting) {
3203
+ throw new ValidationError2("Submit already in progress");
3204
+ }
3205
+ if (!this.entity) {
3206
+ throw new ValidationError2("Session not loaded. Call load() first.");
3207
+ }
3208
+ this.submitting = true;
3209
+ this.result = {};
3210
+ try {
3211
+ const diffs = this.getDiff();
3212
+ const hasManualEdits = diffs.some((d) => d.hasChanges);
3213
+ if (hasManualEdits) {
3214
+ const componentUpdates = {};
3215
+ for (const [name, content] of Object.entries(this.editedContent)) {
3216
+ const original = this.loadedComponents[name] || "";
3217
+ if (DiffEngine.hasSignificantChanges(original, content)) {
3218
+ const cid = await this.client.uploadContent(content, name);
3219
+ componentUpdates[name] = cid;
3220
+ }
3221
+ }
3222
+ const version = await this.client.updateEntity(this.pi, {
3223
+ expect_tip: this.entity.manifest_cid,
3224
+ components: componentUpdates,
3225
+ note
3226
+ });
3227
+ this.result.saved = {
3228
+ pi: version.id,
3229
+ newVersion: version.ver,
3230
+ newTip: version.tip
3231
+ };
3232
+ this.entity.manifest_cid = version.tip;
3233
+ this.entity.ver = version.ver;
3234
+ }
3235
+ if (this.scope.components.length > 0) {
3236
+ const customPrompts = this.buildCustomPrompts();
3237
+ const reprocessResult = await this.client.reprocess({
3238
+ pi: this.pi,
3239
+ phases: this.scope.components,
3240
+ cascade: this.scope.cascade,
3241
+ options: {
3242
+ stop_at_pi: this.scope.stopAtPi,
3243
+ custom_prompts: customPrompts,
3244
+ custom_note: note
3245
+ }
3246
+ });
3247
+ this.result.reprocess = reprocessResult;
3248
+ this.statusUrl = reprocessResult.status_url;
3249
+ }
3250
+ return this.result;
3251
+ } finally {
3252
+ this.submitting = false;
3253
+ }
3254
+ }
3255
+ /**
3256
+ * Wait for reprocessing to complete
3257
+ */
3258
+ async waitForCompletion(options) {
3259
+ const opts = { ...DEFAULT_POLL_OPTIONS, ...options };
3260
+ if (!this.statusUrl) {
3261
+ return {
3262
+ phase: "complete",
3263
+ saveComplete: true
3264
+ };
3265
+ }
3266
+ const startTime = Date.now();
3267
+ let isFirstPoll = true;
3268
+ while (true) {
3269
+ const status = await this.client.getReprocessStatus(this.statusUrl, isFirstPoll);
3270
+ isFirstPoll = false;
3271
+ const editStatus = {
3272
+ phase: status.status === "DONE" ? "complete" : status.status === "ERROR" ? "error" : "reprocessing",
3273
+ saveComplete: true,
3274
+ reprocessStatus: status,
3275
+ error: status.error
3276
+ };
3277
+ if (opts.onProgress) {
3278
+ opts.onProgress(editStatus);
3279
+ }
3280
+ if (status.status === "DONE" || status.status === "ERROR") {
3281
+ return editStatus;
3282
+ }
3283
+ if (Date.now() - startTime > opts.timeoutMs) {
3284
+ return {
3285
+ phase: "error",
3286
+ saveComplete: true,
3287
+ reprocessStatus: status,
3288
+ error: "Timeout waiting for reprocessing to complete"
3289
+ };
3290
+ }
3291
+ await new Promise((resolve) => setTimeout(resolve, opts.intervalMs));
3292
+ }
3293
+ }
3294
+ /**
3295
+ * Get current status without waiting
3296
+ */
3297
+ async getStatus() {
3298
+ if (!this.statusUrl) {
3299
+ return {
3300
+ phase: this.result?.saved ? "complete" : "idle",
3301
+ saveComplete: !!this.result?.saved
3302
+ };
3303
+ }
3304
+ const status = await this.client.getReprocessStatus(this.statusUrl);
3305
+ return {
3306
+ phase: status.status === "DONE" ? "complete" : status.status === "ERROR" ? "error" : "reprocessing",
3307
+ saveComplete: true,
3308
+ reprocessStatus: status,
3309
+ error: status.error
3310
+ };
3311
+ }
3312
+ // ===========================================================================
3313
+ // Private Helpers
3314
+ // ===========================================================================
3315
+ buildCustomPrompts() {
3316
+ const custom = {};
3317
+ if (this.mode === "ai-prompt") {
3318
+ if (this.prompts["general"]) custom.general = this.prompts["general"];
3319
+ if (this.prompts["pinax"]) custom.pinax = this.prompts["pinax"];
3320
+ if (this.prompts["description"]) custom.description = this.prompts["description"];
3321
+ if (this.prompts["cheimarros"]) custom.cheimarros = this.prompts["cheimarros"];
3322
+ } else {
3323
+ const diffs = this.getDiff();
3324
+ const diffContext = DiffEngine.formatComponentDiffsForPrompt(diffs);
3325
+ const correctionContext = PromptBuilder.buildCorrectionPrompt(this.corrections);
3326
+ const basePrompt = [diffContext, correctionContext, this.prompts["general"]].filter(Boolean).join("\n\n");
3327
+ if (basePrompt) {
3328
+ custom.general = basePrompt;
3329
+ }
3330
+ if (this.prompts["pinax"]) custom.pinax = this.prompts["pinax"];
3331
+ if (this.prompts["description"]) custom.description = this.prompts["description"];
3332
+ if (this.prompts["cheimarros"]) custom.cheimarros = this.prompts["cheimarros"];
3333
+ }
3334
+ return custom;
3335
+ }
3336
+ };
3337
+
3338
+ // src/content/errors.ts
3339
+ var ContentError = class extends Error {
3340
+ constructor(message, code2 = "CONTENT_ERROR", details) {
3341
+ super(message);
3342
+ this.code = code2;
3343
+ this.details = details;
3344
+ this.name = "ContentError";
3345
+ }
3346
+ };
3347
+ var EntityNotFoundError2 = class extends ContentError {
3348
+ constructor(id) {
3349
+ super(`Entity not found: ${id}`, "ENTITY_NOT_FOUND", { id });
3350
+ this.name = "EntityNotFoundError";
3351
+ }
3352
+ };
3353
+ var ContentNotFoundError2 = class extends ContentError {
3354
+ constructor(cid) {
3355
+ super(`Content not found: ${cid}`, "CONTENT_NOT_FOUND", { cid });
3356
+ this.name = "ContentNotFoundError";
3357
+ }
3358
+ };
3359
+ var ComponentNotFoundError = class extends ContentError {
3360
+ constructor(id, componentName) {
3361
+ super(
3362
+ `Component '${componentName}' not found on entity ${id}`,
3363
+ "COMPONENT_NOT_FOUND",
3364
+ { id, componentName }
3365
+ );
3366
+ this.name = "ComponentNotFoundError";
3367
+ }
3368
+ };
3369
+ var VersionNotFoundError = class extends ContentError {
3370
+ constructor(id, selector) {
3371
+ super(
3372
+ `Version not found: ${selector} for entity ${id}`,
3373
+ "VERSION_NOT_FOUND",
3374
+ { id, selector }
3375
+ );
3376
+ this.name = "VersionNotFoundError";
3377
+ }
3378
+ };
3379
+ var NetworkError3 = class extends ContentError {
3380
+ constructor(message, statusCode) {
3381
+ super(message, "NETWORK_ERROR", { statusCode });
3382
+ this.statusCode = statusCode;
3383
+ this.name = "NetworkError";
3384
+ }
3385
+ };
3386
+
3387
+ // src/content/client.ts
3388
+ var ContentClient = class {
3389
+ constructor(config) {
3390
+ this.baseUrl = config.gatewayUrl.replace(/\/$/, "");
3391
+ this.fetchImpl = config.fetchImpl ?? fetch;
3392
+ }
3393
+ // ---------------------------------------------------------------------------
3394
+ // Request helpers
3395
+ // ---------------------------------------------------------------------------
3396
+ buildUrl(path2, query) {
3397
+ const url = new URL(`${this.baseUrl}${path2}`);
3398
+ if (query) {
3399
+ Object.entries(query).forEach(([key, value]) => {
3400
+ if (value !== void 0 && value !== null) {
3401
+ url.searchParams.set(key, String(value));
3402
+ }
3403
+ });
3404
+ }
3405
+ return url.toString();
3406
+ }
3407
+ async request(path2, options = {}) {
3408
+ const url = this.buildUrl(path2, options.query);
3409
+ const headers = new Headers({ "Content-Type": "application/json" });
3410
+ if (options.headers) {
3411
+ Object.entries(options.headers).forEach(([k, v]) => {
3412
+ if (v !== void 0) headers.set(k, v);
3413
+ });
3414
+ }
3415
+ let response;
3416
+ try {
3417
+ response = await this.fetchImpl(url, { ...options, headers });
3418
+ } catch (err) {
3419
+ throw new NetworkError3(
3420
+ err instanceof Error ? err.message : "Network request failed"
3421
+ );
3422
+ }
3423
+ if (response.ok) {
3424
+ const contentType = response.headers.get("content-type") || "";
3425
+ if (contentType.includes("application/json")) {
3426
+ return await response.json();
3427
+ }
3428
+ return await response.text();
3429
+ }
3430
+ let body;
3431
+ const text = await response.text();
3432
+ try {
3433
+ body = JSON.parse(text);
3434
+ } catch {
3435
+ body = text;
3436
+ }
3437
+ if (response.status === 404) {
3438
+ const errorCode = body?.error;
3439
+ if (errorCode === "NOT_FOUND" || errorCode === "ENTITY_NOT_FOUND") {
3440
+ throw new ContentError(
3441
+ body?.message || "Not found",
3442
+ "NOT_FOUND",
3443
+ body
3444
+ );
3445
+ }
3446
+ }
3447
+ const message = body?.error && typeof body.error === "string" ? body.error : body?.message && typeof body.message === "string" ? body.message : `Request failed with status ${response.status}`;
3448
+ throw new ContentError(message, "HTTP_ERROR", {
3449
+ status: response.status,
3450
+ body
3451
+ });
3452
+ }
3453
+ // ---------------------------------------------------------------------------
3454
+ // Entity Operations
3455
+ // ---------------------------------------------------------------------------
3456
+ /**
3457
+ * Get an entity by its Persistent Identifier (PI).
3458
+ *
3459
+ * @param pi - Persistent Identifier (ULID or test PI with II prefix)
3460
+ * @returns Full entity manifest
3461
+ * @throws EntityNotFoundError if the entity doesn't exist
3462
+ *
3463
+ * @example
3464
+ * ```typescript
3465
+ * const entity = await content.get('01K75HQQXNTDG7BBP7PS9AWYAN');
3466
+ * console.log('Version:', entity.ver);
3467
+ * console.log('Components:', Object.keys(entity.components));
3468
+ * ```
3469
+ */
3470
+ async get(pi) {
3471
+ try {
3472
+ return await this.request(`/api/entities/${encodeURIComponent(pi)}`);
3473
+ } catch (err) {
3474
+ if (err instanceof ContentError && err.code === "NOT_FOUND") {
3475
+ throw new EntityNotFoundError2(pi);
3476
+ }
3477
+ throw err;
3478
+ }
3479
+ }
3480
+ /**
3481
+ * List entities with pagination.
3482
+ *
3483
+ * @param options - Pagination and metadata options
3484
+ * @returns Paginated list of entity summaries
3485
+ *
3486
+ * @example
3487
+ * ```typescript
3488
+ * // Get first page
3489
+ * const page1 = await content.list({ limit: 20, include_metadata: true });
3490
+ *
3491
+ * // Get next page
3492
+ * if (page1.next_cursor) {
3493
+ * const page2 = await content.list({ cursor: page1.next_cursor });
3494
+ * }
3495
+ * ```
3496
+ */
3497
+ async list(options = {}) {
3498
+ return this.request("/api/entities", {
3499
+ query: {
3500
+ limit: options.limit,
3501
+ cursor: options.cursor,
3502
+ include_metadata: options.include_metadata
3503
+ }
3504
+ });
3505
+ }
3506
+ /**
3507
+ * Get version history for an entity.
3508
+ *
3509
+ * @param pi - Persistent Identifier
3510
+ * @param options - Pagination options
3511
+ * @returns Version history (newest first)
3512
+ *
3513
+ * @example
3514
+ * ```typescript
3515
+ * const history = await content.versions('01K75HQQXNTDG7BBP7PS9AWYAN');
3516
+ * console.log('Total versions:', history.items.length);
3517
+ * history.items.forEach(v => {
3518
+ * console.log(`v${v.ver}: ${v.ts} - ${v.note || 'no note'}`);
3519
+ * });
3520
+ * ```
3521
+ */
3522
+ async versions(pi, options = {}) {
3523
+ try {
3524
+ return await this.request(
3525
+ `/api/entities/${encodeURIComponent(pi)}/versions`,
3526
+ {
3527
+ query: {
3528
+ limit: options.limit,
3529
+ cursor: options.cursor
3530
+ }
3531
+ }
3532
+ );
3533
+ } catch (err) {
3534
+ if (err instanceof ContentError && err.code === "NOT_FOUND") {
3535
+ throw new EntityNotFoundError2(pi);
3536
+ }
3537
+ throw err;
3538
+ }
3539
+ }
3540
+ /**
3541
+ * Get a specific version of an entity.
3542
+ *
3543
+ * @param pi - Persistent Identifier
3544
+ * @param selector - Version selector: 'ver:N' for version number or 'cid:...' for CID
3545
+ * @returns Entity manifest for the specified version
3546
+ *
3547
+ * @example
3548
+ * ```typescript
3549
+ * // Get version 2
3550
+ * const v2 = await content.getVersion('01K75HQQXNTDG7BBP7PS9AWYAN', 'ver:2');
3551
+ *
3552
+ * // Get by CID
3553
+ * const vByCid = await content.getVersion('01K75HQQXNTDG7BBP7PS9AWYAN', 'cid:bafybeih...');
3554
+ * ```
3555
+ */
3556
+ async getVersion(pi, selector) {
3557
+ try {
3558
+ return await this.request(
3559
+ `/api/entities/${encodeURIComponent(pi)}/versions/${encodeURIComponent(selector)}`
3560
+ );
3561
+ } catch (err) {
3562
+ if (err instanceof ContentError && err.code === "NOT_FOUND") {
3563
+ throw new EntityNotFoundError2(pi);
3564
+ }
3565
+ throw err;
3566
+ }
3567
+ }
3568
+ /**
3569
+ * Resolve a PI to its tip CID (fast lookup without fetching manifest).
3570
+ *
3571
+ * @param pi - Persistent Identifier
3572
+ * @returns PI and tip CID
3573
+ *
3574
+ * @example
3575
+ * ```typescript
3576
+ * const { tip } = await content.resolve('01K75HQQXNTDG7BBP7PS9AWYAN');
3577
+ * console.log('Latest manifest CID:', tip);
3578
+ * ```
3579
+ */
3580
+ async resolve(pi) {
3581
+ try {
3582
+ return await this.request(`/api/resolve/${encodeURIComponent(pi)}`);
3583
+ } catch (err) {
3584
+ if (err instanceof ContentError && err.code === "NOT_FOUND") {
3585
+ throw new EntityNotFoundError2(pi);
3586
+ }
3587
+ throw err;
3588
+ }
3589
+ }
3590
+ /**
3591
+ * Get the list of child PIs for an entity (fast, returns only PIs).
3592
+ *
3593
+ * @param pi - Persistent Identifier of parent entity
3594
+ * @returns Array of child PIs
3595
+ *
3596
+ * @example
3597
+ * ```typescript
3598
+ * const childPis = await content.children('01K75HQQXNTDG7BBP7PS9AWYAN');
3599
+ * console.log('Children:', childPis);
3600
+ * ```
3601
+ */
3602
+ async children(pi) {
3603
+ const entity = await this.get(pi);
3604
+ return entity.children_pi || [];
3605
+ }
3606
+ /**
3607
+ * Get all child entities for a parent (fetches full entity for each child).
3608
+ *
3609
+ * @param pi - Persistent Identifier of parent entity
3610
+ * @returns Array of child entities
3611
+ *
3612
+ * @example
3613
+ * ```typescript
3614
+ * const childEntities = await content.childrenEntities('01K75HQQXNTDG7BBP7PS9AWYAN');
3615
+ * childEntities.forEach(child => {
3616
+ * console.log(`${child.pi}: v${child.ver}`);
3617
+ * });
3618
+ * ```
3619
+ */
3620
+ async childrenEntities(pi) {
3621
+ const childPis = await this.children(pi);
3622
+ if (childPis.length === 0) {
3623
+ return [];
3624
+ }
3625
+ const results = await Promise.allSettled(
3626
+ childPis.map((childPi) => this.get(childPi))
3627
+ );
3628
+ return results.filter((r) => r.status === "fulfilled").map((r) => r.value);
3629
+ }
3630
+ /**
3631
+ * Get the Arke origin block (root of the archive tree).
3632
+ *
3633
+ * @returns Arke origin entity
3634
+ *
3635
+ * @example
3636
+ * ```typescript
3637
+ * const origin = await content.arke();
3638
+ * console.log('Arke origin:', origin.pi);
3639
+ * ```
3640
+ */
3641
+ async arke() {
3642
+ return this.request("/api/arke");
3643
+ }
3644
+ // ---------------------------------------------------------------------------
3645
+ // Content Download
3646
+ // ---------------------------------------------------------------------------
3647
+ /**
3648
+ * Download content by CID.
3649
+ *
3650
+ * Returns Blob in browser environments, Buffer in Node.js.
3651
+ *
3652
+ * @param cid - Content Identifier
3653
+ * @returns Content as Blob (browser) or Buffer (Node)
3654
+ * @throws ContentNotFoundError if the content doesn't exist
3655
+ *
3656
+ * @example
3657
+ * ```typescript
3658
+ * const content = await client.download('bafybeih...');
3659
+ *
3660
+ * // In browser
3661
+ * const url = URL.createObjectURL(content as Blob);
3662
+ *
3663
+ * // In Node.js
3664
+ * fs.writeFileSync('output.bin', content as Buffer);
3665
+ * ```
3666
+ */
3667
+ async download(cid) {
3668
+ const url = this.buildUrl(`/api/cat/${encodeURIComponent(cid)}`);
3669
+ let response;
3670
+ try {
3671
+ response = await this.fetchImpl(url);
3672
+ } catch (err) {
3673
+ throw new NetworkError3(
3674
+ err instanceof Error ? err.message : "Network request failed"
3675
+ );
3676
+ }
3677
+ if (!response.ok) {
3678
+ if (response.status === 404) {
3679
+ throw new ContentNotFoundError2(cid);
3680
+ }
3681
+ throw new ContentError(
3682
+ `Failed to download content: ${response.status}`,
3683
+ "DOWNLOAD_ERROR",
3684
+ { status: response.status }
3685
+ );
3686
+ }
3687
+ if (typeof window !== "undefined") {
3688
+ return response.blob();
3689
+ } else {
3690
+ const arrayBuffer = await response.arrayBuffer();
3691
+ return Buffer.from(arrayBuffer);
3692
+ }
3693
+ }
3694
+ /**
3695
+ * Get a direct URL for content by CID.
3696
+ *
3697
+ * This is useful for embedding in img tags or for direct downloads.
3698
+ *
3699
+ * @param cid - Content Identifier
3700
+ * @returns URL string
3701
+ *
3702
+ * @example
3703
+ * ```typescript
3704
+ * const url = content.getUrl('bafybeih...');
3705
+ * // Use in img tag: <img src={url} />
3706
+ * ```
3707
+ */
3708
+ getUrl(cid) {
3709
+ return `${this.baseUrl}/api/cat/${encodeURIComponent(cid)}`;
3710
+ }
3711
+ /**
3712
+ * Stream content by CID.
3713
+ *
3714
+ * @param cid - Content Identifier
3715
+ * @returns ReadableStream of the content
3716
+ * @throws ContentNotFoundError if the content doesn't exist
3717
+ *
3718
+ * @example
3719
+ * ```typescript
3720
+ * const stream = await content.stream('bafybeih...');
3721
+ * const reader = stream.getReader();
3722
+ * while (true) {
3723
+ * const { done, value } = await reader.read();
3724
+ * if (done) break;
3725
+ * // Process chunk
3726
+ * }
3727
+ * ```
3728
+ */
3729
+ async stream(cid) {
3730
+ const url = this.buildUrl(`/api/cat/${encodeURIComponent(cid)}`);
3731
+ let response;
3732
+ try {
3733
+ response = await this.fetchImpl(url);
3734
+ } catch (err) {
3735
+ throw new NetworkError3(
3736
+ err instanceof Error ? err.message : "Network request failed"
3737
+ );
3738
+ }
3739
+ if (!response.ok) {
3740
+ if (response.status === 404) {
3741
+ throw new ContentNotFoundError2(cid);
3742
+ }
3743
+ throw new ContentError(
3744
+ `Failed to stream content: ${response.status}`,
3745
+ "STREAM_ERROR",
3746
+ { status: response.status }
3747
+ );
3748
+ }
3749
+ if (!response.body) {
3750
+ throw new ContentError("Response body is not available", "STREAM_ERROR");
3751
+ }
3752
+ return response.body;
3753
+ }
3754
+ /**
3755
+ * Download a DAG node (JSON) by CID.
3756
+ *
3757
+ * Use this to fetch JSON components like properties and relationships.
3758
+ *
3759
+ * @param cid - Content Identifier of the DAG node
3760
+ * @returns Parsed JSON object
3761
+ * @throws ContentNotFoundError if the content doesn't exist
3762
+ *
3763
+ * @example
3764
+ * ```typescript
3765
+ * const relationships = await content.getDag<RelationshipsComponent>(
3766
+ * entity.components.relationships
3767
+ * );
3768
+ * console.log('Relationships:', relationships.relationships);
3769
+ * ```
3770
+ */
3771
+ async getDag(cid) {
3772
+ const url = this.buildUrl(`/api/dag/${encodeURIComponent(cid)}`);
3773
+ let response;
3774
+ try {
3775
+ response = await this.fetchImpl(url);
3776
+ } catch (err) {
3777
+ throw new NetworkError3(
3778
+ err instanceof Error ? err.message : "Network request failed"
3779
+ );
3780
+ }
3781
+ if (!response.ok) {
3782
+ if (response.status === 404) {
3783
+ throw new ContentNotFoundError2(cid);
3784
+ }
3785
+ throw new ContentError(
3786
+ `Failed to fetch DAG node: ${response.status}`,
3787
+ "DAG_ERROR",
3788
+ { status: response.status }
3789
+ );
3790
+ }
3791
+ return await response.json();
3792
+ }
3793
+ // ---------------------------------------------------------------------------
3794
+ // Component Helpers
3795
+ // ---------------------------------------------------------------------------
3796
+ /**
3797
+ * Download a component from an entity.
3798
+ *
3799
+ * @param entity - Entity containing the component
3800
+ * @param componentName - Name of the component (e.g., 'pinax', 'description', 'source')
3801
+ * @returns Component content as Blob (browser) or Buffer (Node)
3802
+ * @throws ComponentNotFoundError if the component doesn't exist
3803
+ *
3804
+ * @example
3805
+ * ```typescript
3806
+ * const entity = await content.get('01K75HQQXNTDG7BBP7PS9AWYAN');
3807
+ * const pinax = await content.getComponent(entity, 'pinax');
3808
+ * ```
3809
+ */
3810
+ async getComponent(entity, componentName) {
3811
+ const cid = entity.components[componentName];
3812
+ if (!cid) {
3813
+ throw new ComponentNotFoundError(entity.id, componentName);
3814
+ }
3815
+ return this.download(cid);
3816
+ }
3817
+ /**
3818
+ * Get the URL for a component from an entity.
3819
+ *
3820
+ * @param entity - Entity containing the component
3821
+ * @param componentName - Name of the component
3822
+ * @returns URL string
3823
+ * @throws ComponentNotFoundError if the component doesn't exist
3824
+ *
3825
+ * @example
3826
+ * ```typescript
3827
+ * const entity = await content.get('01K75HQQXNTDG7BBP7PS9AWYAN');
3828
+ * const imageUrl = content.getComponentUrl(entity, 'source');
3829
+ * // Use in img tag: <img src={imageUrl} />
3830
+ * ```
3831
+ */
3832
+ getComponentUrl(entity, componentName) {
3833
+ const cid = entity.components[componentName];
3834
+ if (!cid) {
3835
+ throw new ComponentNotFoundError(entity.id, componentName);
3836
+ }
3837
+ return this.getUrl(cid);
3838
+ }
3839
+ /**
3840
+ * Get the properties component for an entity.
3841
+ *
3842
+ * @param entity - Entity containing the properties component
3843
+ * @returns Properties object, or null if no properties component exists
3844
+ *
3845
+ * @example
3846
+ * ```typescript
3847
+ * const entity = await content.get('01K75HQQXNTDG7BBP7PS9AWYAN');
3848
+ * const props = await content.getProperties(entity);
3849
+ * if (props) {
3850
+ * console.log('Title:', props.title);
3851
+ * }
3852
+ * ```
3853
+ */
3854
+ async getProperties(entity) {
3855
+ const cid = entity.components.properties;
3856
+ if (!cid) {
3857
+ return null;
3858
+ }
3859
+ return this.getDag(cid);
3860
+ }
3861
+ /**
3862
+ * Get the relationships component for an entity.
3863
+ *
3864
+ * @param entity - Entity containing the relationships component
3865
+ * @returns Relationships component, or null if no relationships exist
3866
+ *
3867
+ * @example
3868
+ * ```typescript
3869
+ * const entity = await content.get('01K75HQQXNTDG7BBP7PS9AWYAN');
3870
+ * const rels = await content.getRelationships(entity);
3871
+ * if (rels) {
3872
+ * rels.relationships.forEach(r => {
3873
+ * console.log(`${r.predicate} -> ${r.target_label}`);
3874
+ * });
3875
+ * }
3876
+ * ```
3877
+ */
3878
+ async getRelationships(entity) {
3879
+ const cid = entity.components.relationships;
3880
+ if (!cid) {
3881
+ return null;
3882
+ }
3883
+ return this.getDag(cid);
3884
+ }
3885
+ };
3886
+
3887
+ // src/graph/errors.ts
3888
+ var GraphError = class extends Error {
3889
+ constructor(message, code2 = "GRAPH_ERROR", details) {
3890
+ super(message);
3891
+ this.code = code2;
3892
+ this.details = details;
3893
+ this.name = "GraphError";
3894
+ }
3895
+ };
3896
+ var GraphEntityNotFoundError = class extends GraphError {
3897
+ constructor(canonicalId) {
3898
+ super(`Graph entity not found: ${canonicalId}`, "ENTITY_NOT_FOUND", { canonicalId });
3899
+ this.name = "GraphEntityNotFoundError";
3900
+ }
3901
+ };
3902
+ var NoPathFoundError = class extends GraphError {
3903
+ constructor(sourceIds, targetIds) {
3904
+ super(
3905
+ `No path found between sources and targets`,
3906
+ "NO_PATH_FOUND",
3907
+ { sourceIds, targetIds }
3908
+ );
3909
+ this.name = "NoPathFoundError";
3910
+ }
3911
+ };
3912
+ var NetworkError4 = class extends GraphError {
3913
+ constructor(message, statusCode) {
3914
+ super(message, "NETWORK_ERROR", { statusCode });
3915
+ this.statusCode = statusCode;
3916
+ this.name = "NetworkError";
3917
+ }
3918
+ };
3919
+
3920
+ // src/graph/client.ts
3921
+ var GraphClient = class {
3922
+ constructor(config) {
3923
+ this.baseUrl = config.gatewayUrl.replace(/\/$/, "");
3924
+ this.fetchImpl = config.fetchImpl ?? fetch;
3925
+ }
3926
+ // ---------------------------------------------------------------------------
3927
+ // Request helpers
3928
+ // ---------------------------------------------------------------------------
3929
+ buildUrl(path2, query) {
3930
+ const url = new URL(`${this.baseUrl}${path2}`);
3931
+ if (query) {
3932
+ Object.entries(query).forEach(([key, value]) => {
3933
+ if (value !== void 0 && value !== null) {
3934
+ url.searchParams.set(key, String(value));
3935
+ }
3936
+ });
3937
+ }
3938
+ return url.toString();
3939
+ }
3940
+ async request(path2, options = {}) {
3941
+ const url = this.buildUrl(path2, options.query);
3942
+ const headers = new Headers({ "Content-Type": "application/json" });
3943
+ if (options.headers) {
3944
+ Object.entries(options.headers).forEach(([k, v]) => {
3945
+ if (v !== void 0) headers.set(k, v);
3946
+ });
3947
+ }
3948
+ let response;
3949
+ try {
3950
+ response = await this.fetchImpl(url, { ...options, headers });
3951
+ } catch (err) {
3952
+ throw new NetworkError4(
3953
+ err instanceof Error ? err.message : "Network request failed"
3954
+ );
3955
+ }
3956
+ if (response.ok) {
3957
+ const contentType = response.headers.get("content-type") || "";
3958
+ if (contentType.includes("application/json")) {
3959
+ return await response.json();
3960
+ }
3961
+ return await response.text();
3962
+ }
3963
+ let body;
3964
+ const text = await response.text();
3965
+ try {
3966
+ body = JSON.parse(text);
3967
+ } catch {
3968
+ body = text;
3969
+ }
3970
+ if (response.status === 404) {
3971
+ throw new GraphError(
3972
+ body?.message || "Not found",
3973
+ "NOT_FOUND",
3974
+ body
3975
+ );
3976
+ }
3977
+ const message = body?.error && typeof body.error === "string" ? body.error : body?.message && typeof body.message === "string" ? body.message : `Request failed with status ${response.status}`;
3978
+ throw new GraphError(message, "HTTP_ERROR", {
3979
+ status: response.status,
3980
+ body
3981
+ });
3982
+ }
3983
+ // ---------------------------------------------------------------------------
3984
+ // Code-based Lookups (indexed in GraphDB)
3985
+ // ---------------------------------------------------------------------------
3986
+ /**
3987
+ * Query entities by code with optional type filter.
3988
+ *
3989
+ * @param code - Entity code to search for
3990
+ * @param type - Optional entity type filter
3991
+ * @returns Matching entities
3992
+ *
3993
+ * @example
3994
+ * ```typescript
3995
+ * // Find by code
3996
+ * const entities = await graph.queryByCode('person_john');
3997
+ *
3998
+ * // With type filter
3999
+ * const people = await graph.queryByCode('john', 'person');
4000
+ * ```
4001
+ */
4002
+ async queryByCode(code2, type) {
4003
+ const response = await this.request(
4004
+ "/graphdb/entity/query",
4005
+ {
4006
+ method: "POST",
4007
+ body: JSON.stringify({ code: code2, type })
4008
+ }
4009
+ );
4010
+ if (!response.found || !response.entity) {
4011
+ return [];
4012
+ }
4013
+ return [response.entity];
4014
+ }
4015
+ /**
4016
+ * Look up entities by code across all PIs.
4017
+ *
4018
+ * @param code - Entity code to search for
4019
+ * @param type - Optional entity type filter
4020
+ * @returns Matching entities
4021
+ *
4022
+ * @example
4023
+ * ```typescript
4024
+ * const entities = await graph.lookupByCode('alice_austen', 'person');
4025
+ * ```
4026
+ */
4027
+ async lookupByCode(code2, type) {
4028
+ const response = await this.request(
4029
+ "/graphdb/entities/lookup-by-code",
4030
+ {
4031
+ method: "POST",
4032
+ body: JSON.stringify({ code: code2, type })
4033
+ }
4034
+ );
4035
+ return response.entities || [];
4036
+ }
4037
+ // ---------------------------------------------------------------------------
4038
+ // PI-based Operations
4039
+ // ---------------------------------------------------------------------------
4040
+ /**
4041
+ * List entities extracted from a specific PI or multiple PIs.
4042
+ *
4043
+ * This returns knowledge graph entities (persons, places, events, etc.)
4044
+ * that were extracted from the given PI(s), not the PI entity itself.
4045
+ *
4046
+ * @param pi - Single PI or array of PIs
4047
+ * @param options - Filter options
4048
+ * @returns Extracted entities from the PI(s)
4049
+ *
4050
+ * @example
4051
+ * ```typescript
4052
+ * // From single PI
4053
+ * const entities = await graph.listEntitiesFromPi('01K75HQQXNTDG7BBP7PS9AWYAN');
4054
+ *
4055
+ * // With type filter
4056
+ * const people = await graph.listEntitiesFromPi('01K75HQQXNTDG7BBP7PS9AWYAN', { type: 'person' });
4057
+ *
4058
+ * // From multiple PIs
4059
+ * const all = await graph.listEntitiesFromPi(['pi-1', 'pi-2']);
4060
+ * ```
4061
+ */
4062
+ async listEntitiesFromPi(pi, options = {}) {
4063
+ const pis = Array.isArray(pi) ? pi : [pi];
4064
+ const response = await this.request(
4065
+ "/graphdb/entities/list",
4066
+ {
4067
+ method: "POST",
4068
+ body: JSON.stringify({
4069
+ pis,
4070
+ type: options.type
4071
+ })
4072
+ }
4073
+ );
4074
+ return response.entities || [];
4075
+ }
4076
+ /**
4077
+ * Get entities with their relationships from a PI.
4078
+ *
4079
+ * This is an optimized query that returns entities along with all their
4080
+ * relationship data in a single request.
4081
+ *
4082
+ * @param pi - Persistent Identifier
4083
+ * @param type - Optional entity type filter
4084
+ * @returns Entities with relationships
4085
+ *
4086
+ * @example
4087
+ * ```typescript
4088
+ * const entities = await graph.getEntitiesWithRelationships('01K75HQQXNTDG7BBP7PS9AWYAN');
4089
+ * entities.forEach(e => {
4090
+ * console.log(`${e.label} has ${e.relationships.length} relationships`);
4091
+ * });
4092
+ * ```
4093
+ */
4094
+ async getEntitiesWithRelationships(pi, type) {
4095
+ const response = await this.request(
4096
+ "/graphdb/pi/entities-with-relationships",
4097
+ {
4098
+ method: "POST",
4099
+ body: JSON.stringify({ pi, type })
4100
+ }
4101
+ );
4102
+ return response.entities || [];
4103
+ }
4104
+ /**
4105
+ * Get the lineage (ancestors and/or descendants) of a PI.
4106
+ *
4107
+ * This traverses the PI hierarchy (parent_pi/children_pi relationships)
4108
+ * which is indexed in GraphDB for fast lookups.
4109
+ *
4110
+ * @param pi - Source PI
4111
+ * @param direction - 'ancestors', 'descendants', or 'both'
4112
+ * @param maxHops - Maximum depth to traverse (default: 10)
4113
+ * @returns Lineage data with PIs at each hop level
4114
+ *
4115
+ * @example
4116
+ * ```typescript
4117
+ * // Get ancestors (parent chain)
4118
+ * const lineage = await graph.getLineage('01K75HQQXNTDG7BBP7PS9AWYAN', 'ancestors');
4119
+ *
4120
+ * // Get both directions
4121
+ * const full = await graph.getLineage('01K75HQQXNTDG7BBP7PS9AWYAN', 'both');
4122
+ * ```
4123
+ */
4124
+ async getLineage(pi, direction = "both", maxHops = 10) {
4125
+ return this.request("/graphdb/pi/lineage", {
4126
+ method: "POST",
4127
+ body: JSON.stringify({ sourcePi: pi, direction, maxHops })
4128
+ });
4129
+ }
4130
+ // ---------------------------------------------------------------------------
4131
+ // Relationship Operations
4132
+ // ---------------------------------------------------------------------------
4133
+ /**
4134
+ * Get relationships for an entity from the GraphDB index.
4135
+ *
4136
+ * **Important distinction from ContentClient.getRelationships():**
4137
+ * - **ContentClient.getRelationships()**: Returns OUTBOUND relationships only
4138
+ * (from the entity's relationships.json in IPFS - source of truth)
4139
+ * - **GraphClient.getRelationships()**: Returns BOTH inbound AND outbound
4140
+ * relationships (from the indexed GraphDB mirror)
4141
+ *
4142
+ * Use this method when you need to find "what references this entity" (inbound)
4143
+ * or want a complete bidirectional view.
4144
+ *
4145
+ * @param id - Entity identifier (works for both PIs and KG entities)
4146
+ * @param direction - Filter by direction: 'outgoing', 'incoming', or 'both' (default)
4147
+ * @returns Array of relationships with direction indicator
4148
+ *
4149
+ * @example
4150
+ * ```typescript
4151
+ * // Get all relationships (both directions)
4152
+ * const all = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN');
4153
+ *
4154
+ * // Get only inbound relationships ("who references this entity?")
4155
+ * const incoming = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN', 'incoming');
4156
+ *
4157
+ * // Get only outbound relationships (similar to IPFS, but from index)
4158
+ * const outgoing = await graph.getRelationships('01K75HQQXNTDG7BBP7PS9AWYAN', 'outgoing');
4159
+ *
4160
+ * // Process by direction
4161
+ * const rels = await graph.getRelationships('entity-id');
4162
+ * rels.forEach(r => {
4163
+ * if (r.direction === 'incoming') {
4164
+ * console.log(`${r.target_label} references this entity via ${r.predicate}`);
4165
+ * } else {
4166
+ * console.log(`This entity ${r.predicate} -> ${r.target_label}`);
4167
+ * }
4168
+ * });
4169
+ * ```
4170
+ */
4171
+ async getRelationships(id, direction = "both") {
4172
+ const response = await this.request(`/graphdb/relationships/${encodeURIComponent(id)}`);
4173
+ if (!response.found || !response.relationships) {
4174
+ return [];
4175
+ }
4176
+ let relationships = response.relationships;
4177
+ if (direction !== "both") {
4178
+ relationships = relationships.filter((rel) => rel.direction === direction);
4179
+ }
4180
+ return relationships.map((rel) => ({
4181
+ direction: rel.direction,
4182
+ predicate: rel.predicate,
4183
+ target_id: rel.target_id,
4184
+ target_code: rel.target_code || "",
4185
+ target_label: rel.target_label,
4186
+ target_type: rel.target_type,
4187
+ properties: rel.properties,
4188
+ source_pi: rel.source_pi,
4189
+ created_at: rel.created_at
4190
+ }));
4191
+ }
4192
+ // ---------------------------------------------------------------------------
4193
+ // Path Finding
4194
+ // ---------------------------------------------------------------------------
4195
+ /**
4196
+ * Find shortest paths between sets of entities.
4197
+ *
4198
+ * @param sourceIds - Starting entity IDs
4199
+ * @param targetIds - Target entity IDs
4200
+ * @param options - Path finding options
4201
+ * @returns Found paths
4202
+ *
4203
+ * @example
4204
+ * ```typescript
4205
+ * const paths = await graph.findPaths(
4206
+ * ['entity-alice'],
4207
+ * ['entity-bob'],
4208
+ * { max_depth: 4, direction: 'both' }
4209
+ * );
4210
+ *
4211
+ * paths.forEach(path => {
4212
+ * console.log(`Path of length ${path.length}:`);
4213
+ * path.edges.forEach(e => {
4214
+ * console.log(` ${e.subject_label} -[${e.predicate}]-> ${e.object_label}`);
4215
+ * });
4216
+ * });
4217
+ * ```
4218
+ */
4219
+ async findPaths(sourceIds, targetIds, options = {}) {
4220
+ const response = await this.request("/graphdb/paths/between", {
4221
+ method: "POST",
4222
+ body: JSON.stringify({
4223
+ source_ids: sourceIds,
4224
+ target_ids: targetIds,
4225
+ max_depth: options.max_depth,
4226
+ direction: options.direction,
4227
+ limit: options.limit
4228
+ })
4229
+ });
4230
+ return response.paths || [];
4231
+ }
4232
+ /**
4233
+ * Find entities of a specific type reachable from starting entities.
4234
+ *
4235
+ * @param startIds - Starting entity IDs
4236
+ * @param targetType - Type of entities to find
4237
+ * @param options - Search options
4238
+ * @returns Reachable entities of the specified type
4239
+ *
4240
+ * @example
4241
+ * ```typescript
4242
+ * // Find all people reachable from an event
4243
+ * const people = await graph.findReachable(
4244
+ * ['event-id'],
4245
+ * 'person',
4246
+ * { max_depth: 3 }
4247
+ * );
4248
+ * ```
4249
+ */
4250
+ async findReachable(startIds, targetType, options = {}) {
4251
+ const response = await this.request(
4252
+ "/graphdb/paths/reachable",
4253
+ {
4254
+ method: "POST",
4255
+ body: JSON.stringify({
4256
+ start_ids: startIds,
4257
+ target_type: targetType,
4258
+ max_depth: options.max_depth,
4259
+ direction: options.direction,
4260
+ limit: options.limit
4261
+ })
4262
+ }
4263
+ );
4264
+ return response.entities || [];
4265
+ }
4266
+ /**
4267
+ * Check the health of the graph service.
4268
+ *
4269
+ * @returns Health status
4270
+ */
4271
+ async health() {
4272
+ return this.request("/graphdb/health", { method: "GET" });
4273
+ }
4274
+ };
1599
4275
  export {
1600
4276
  ArkeUploader,
1601
4277
  CollectionsClient,
1602
4278
  CollectionsError,
4279
+ ComponentNotFoundError,
4280
+ ContentClient,
4281
+ ContentError,
4282
+ NetworkError3 as ContentNetworkError,
4283
+ ContentNotFoundError2 as ContentNotFoundError,
4284
+ EditClient,
4285
+ EditError,
4286
+ EditSession,
4287
+ EntityNotFoundError2 as EntityNotFoundError,
4288
+ GraphClient,
4289
+ GraphEntityNotFoundError,
4290
+ GraphError,
4291
+ NetworkError4 as GraphNetworkError,
1603
4292
  NetworkError,
4293
+ NoPathFoundError,
4294
+ PermissionError,
4295
+ QueryClient,
4296
+ QueryError,
1604
4297
  ScanError,
1605
4298
  UploadClient,
1606
4299
  UploadError,
1607
4300
  ValidationError,
4301
+ VersionNotFoundError,
1608
4302
  WorkerAPIError
1609
4303
  };
1610
4304
  //# sourceMappingURL=index.js.map