@bevorai/sdk 0.2.2-rc1 → 0.2.2-rc3

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 (80) hide show
  1. package/README.md +7 -6
  2. package/dist/client.d.ts +0 -2
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +0 -3
  5. package/dist/client.js.map +1 -1
  6. package/dist/errors.d.ts +9 -1
  7. package/dist/errors.d.ts.map +1 -1
  8. package/dist/errors.js +9 -0
  9. package/dist/errors.js.map +1 -1
  10. package/dist/graph/call-node.d.ts +16 -15
  11. package/dist/graph/call-node.d.ts.map +1 -1
  12. package/dist/graph/call-node.js +113 -175
  13. package/dist/graph/call-node.js.map +1 -1
  14. package/dist/graph/cursor.d.ts +2 -0
  15. package/dist/graph/cursor.d.ts.map +1 -1
  16. package/dist/graph/cursor.js +22 -18
  17. package/dist/graph/cursor.js.map +1 -1
  18. package/dist/graph/graph.d.ts +30 -49
  19. package/dist/graph/graph.d.ts.map +1 -1
  20. package/dist/graph/graph.js +366 -192
  21. package/dist/graph/graph.js.map +1 -1
  22. package/dist/helpers/sarif.d.ts +16 -2
  23. package/dist/helpers/sarif.d.ts.map +1 -1
  24. package/dist/helpers/sarif.js +217 -59
  25. package/dist/helpers/sarif.js.map +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/resources/analyses.d.ts +31 -33
  29. package/dist/resources/analyses.d.ts.map +1 -1
  30. package/dist/resources/analyses.js +54 -42
  31. package/dist/resources/analyses.js.map +1 -1
  32. package/dist/resources/codes.d.ts +4 -20
  33. package/dist/resources/codes.d.ts.map +1 -1
  34. package/dist/resources/codes.js +5 -26
  35. package/dist/resources/codes.js.map +1 -1
  36. package/dist/resources/graph.d.ts +82 -0
  37. package/dist/resources/graph.d.ts.map +1 -0
  38. package/dist/resources/graph.js +133 -0
  39. package/dist/resources/graph.js.map +1 -0
  40. package/dist/resources/index.d.ts +1 -3
  41. package/dist/resources/index.d.ts.map +1 -1
  42. package/dist/resources/index.js +1 -3
  43. package/dist/resources/index.js.map +1 -1
  44. package/dist/resources/projects.d.ts +4 -4
  45. package/dist/resources/projects.d.ts.map +1 -1
  46. package/dist/resources/projects.js +5 -5
  47. package/dist/resources/projects.js.map +1 -1
  48. package/dist/resources/users.d.ts +4 -1
  49. package/dist/resources/users.d.ts.map +1 -1
  50. package/dist/resources/users.js +8 -5
  51. package/dist/resources/users.js.map +1 -1
  52. package/dist/types/generics.d.ts +7 -0
  53. package/dist/types/generics.d.ts.map +1 -1
  54. package/dist/types/graph-data.d.ts +44 -19
  55. package/dist/types/graph-data.d.ts.map +1 -1
  56. package/dist/types/literals.d.ts +2 -0
  57. package/dist/types/literals.d.ts.map +1 -1
  58. package/dist/types/node-locations.d.ts +16 -0
  59. package/dist/types/node-locations.d.ts.map +1 -0
  60. package/dist/types/node-locations.js +3 -0
  61. package/dist/types/node-locations.js.map +1 -0
  62. package/dist/types/requests.d.ts +53 -47
  63. package/dist/types/requests.d.ts.map +1 -1
  64. package/dist/types/responses.d.ts +34 -20
  65. package/dist/types/responses.d.ts.map +1 -1
  66. package/dist/version.d.ts +1 -1
  67. package/dist/version.js +1 -1
  68. package/package.json +1 -1
  69. package/dist/resources/files.d.ts +0 -36
  70. package/dist/resources/files.d.ts.map +0 -1
  71. package/dist/resources/files.js +0 -55
  72. package/dist/resources/files.js.map +0 -1
  73. package/dist/resources/nodes.d.ts +0 -43
  74. package/dist/resources/nodes.d.ts.map +0 -1
  75. package/dist/resources/nodes.js +0 -75
  76. package/dist/resources/nodes.js.map +0 -1
  77. package/dist/resources/transitions.d.ts +0 -29
  78. package/dist/resources/transitions.d.ts.map +0 -1
  79. package/dist/resources/transitions.js +0 -37
  80. package/dist/resources/transitions.js.map +0 -1
@@ -1,18 +1,33 @@
1
+ import { NodeResolutionError } from "../errors.js";
1
2
  import { CallNode } from "./call-node.js";
2
- import { GraphCursor } from "./cursor.js";
3
+ import { edgeKey, GraphCursor } from "./cursor.js";
4
+ const ALL_PARTS = ["nodes", "edges", "files"];
3
5
  const HEX_LITERAL_RE = /hex"([0-9a-fA-F]+)"/g;
4
6
  const LARGE_STRING_LITERAL_RE = /"(?:[^"\\]|\\[\s\S]){512,}"/g;
7
+ const PARAMS_RE = /\(.*\)\s*$/;
8
+ const DELIMITER_RE = /::|\./;
9
+ const NEWLINE = 0x0a;
10
+ const CARRIAGE_RETURN = 0x0d;
11
+ const ASCII_WHITESPACE = new Set([0x20, 0x09, 0x0a, 0x0b, 0x0c, 0x0d]);
5
12
  const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
6
13
  const utf8Encoder = new TextEncoder();
7
14
  const sanitizeChunk = (src) => src
8
15
  .replace(HEX_LITERAL_RE, (match, hex) => Math.floor(hex.length / 2) > 256 ? 'hex"<BYTECODE OMITTED>"' : match)
9
16
  .replace(LARGE_STRING_LITERAL_RE, '"[LARGE_STRING_OMITTED]"');
10
- const mustGet = (map, key, label) => {
11
- const value = map.get(key);
12
- if (value === undefined)
13
- throw new Error(`unknown ${label}: ${String(key)}`);
14
- return value;
17
+ const splitLines = (content) => {
18
+ const lines = [];
19
+ let start = 0;
20
+ for (let i = 0; i < content.length; i++) {
21
+ if (content[i] === NEWLINE) {
22
+ lines.push(content.subarray(start, i));
23
+ start = i + 1;
24
+ }
25
+ }
26
+ lines.push(content.subarray(start));
27
+ return lines;
15
28
  };
29
+ /** Byte length of the first `count` code points of `text`. */
30
+ const codePointsToBytes = (text, count) => utf8Encoder.encode([...text].slice(0, count).join("")).length;
16
31
  /**
17
32
  * Language-agnostic graph view for one code version, backed by HTTP only.
18
33
  *
@@ -21,19 +36,19 @@ const mustGet = (map, key, label) => {
21
36
  export class Graph {
22
37
  codeId;
23
38
  #client;
24
- #isBuilt = false;
25
- edges = [];
26
- fileMap = new Map();
27
- /** file id -> ids of the nodes in that file */
28
- sourceMap = new Map();
29
- nodeMap = new Map();
30
- /** short id -> id */
31
- idMap = new Map();
32
- /** id -> short id */
33
- reverseIdMap = new Map();
39
+ #isBuilt = {
40
+ nodes: false,
41
+ edges: false,
42
+ files: false,
43
+ };
44
+ #fileMap = new Map();
45
+ #nodeMap = new Map();
46
+ #edgeMap = new Map();
47
+ #shortIdToId = new Map();
48
+ #filePaths = new Map();
49
+ #languages = new Set();
34
50
  #adjacency = new Map();
35
51
  #reverseAdjacency = new Map();
36
- #edgeById = new Map();
37
52
  #fileText = new Map();
38
53
  constructor(client, codeId) {
39
54
  this.#client = client;
@@ -45,57 +60,73 @@ export class Graph {
45
60
  return graph;
46
61
  }
47
62
  get isBuilt() {
48
- return this.#isBuilt;
63
+ return ALL_PARTS.every((part) => this.#isBuilt[part]);
49
64
  }
50
- /** Fetches the snapshot (nodes, edges and files). No-op once built. */
65
+ /** Fetches whichever of the nodes, edges and files aren't loaded yet. */
51
66
  async build() {
52
- if (this.#isBuilt)
53
- return;
67
+ const graph = this.#client.codes.graph.with(this.codeId);
54
68
  const [nodes, edges, files] = await Promise.all([
55
- this.#client.codes.nodes.list(this.codeId),
56
- this.#client.codes.edges(this.codeId),
57
- this.#client.codes.files.list(this.codeId),
69
+ this.#needs("nodes") ? graph.listNodes() : null,
70
+ this.#needs("edges") ? graph.listEdges() : null,
71
+ this.#needs("files") ? graph.listFiles() : null,
58
72
  ]);
59
73
  this.#ingestSnapshot({
60
- nodes: nodes.results,
61
- edges: edges.results,
62
- files: files.results,
74
+ nodes: nodes?.results ?? [],
75
+ edges: edges?.results ?? [],
76
+ files: files?.results ?? [],
63
77
  });
64
78
  }
65
- /** Fetches a file's text once and caches it. */
66
- async getFileContent(fileId) {
67
- const cached = this.#fileText.get(fileId);
79
+ async getNode(ref, orNone = false) {
80
+ this.#ensureBuilt(["nodes"]);
81
+ try {
82
+ if (typeof ref === "string")
83
+ return this._resolveNodeLocId(ref);
84
+ if (ref.strategy === "physical")
85
+ return await this.#resolveNodeLocPhysical(ref);
86
+ throw new Error("invalid ref");
87
+ }
88
+ catch (error) {
89
+ if (orNone && error instanceof NodeResolutionError)
90
+ return null;
91
+ throw error;
92
+ }
93
+ }
94
+ /** Fetches a file's text, by file id or path, once and caches it. */
95
+ async getFileContent(ref) {
96
+ const file = this.getFile(ref);
97
+ const cached = this.#fileText.get(file.id);
68
98
  if (cached !== undefined)
69
99
  return cached;
70
- const text = await this.#client.codes.files.content(this.codeId, fileId);
71
- this.#fileText.set(fileId, text);
100
+ const text = await this.#client.codes.graph.getFileSource(this.codeId, file.id);
101
+ this.#fileText.set(file.id, text);
72
102
  return text;
73
103
  }
74
104
  /**
75
105
  * The node's source, with oversized hex/string literals elided.
76
- * With `withDocstring`, prefixes the docstring, following `@inheritdoc` to the referenced natspec.
106
+ *
107
+ * With `with_docstring`, prefixes the node's docstring. With `resolve_docstring` as well, an
108
+ * `@inheritdoc` docstring is replaced by the natspec it references.
77
109
  */
78
- async reconstructChunk(nodeId, { withDocstring = false } = {}) {
79
- this.#ensureBuilt();
80
- const node = this.getNode(nodeId);
110
+ async reconstructChunk(ref, params) {
111
+ this.#ensureBuilt(["nodes", "files"]);
112
+ const node = await this.getNode(ref);
81
113
  const source = utf8Encoder.encode(await this.getFileContent(node.file_id));
82
114
  let docstring = null;
83
- if (withDocstring && node.docstring) {
84
- if (!node.docstring.includes("@inheritdoc")) {
115
+ if (params?.with_docstring && node.docstring) {
116
+ if (!node.docstring.includes("@inheritdoc") ||
117
+ !params.resolve_docstring) {
85
118
  docstring = node.docstring;
86
119
  }
87
120
  else {
88
- const [natspec] = this.getEdgesForNode(nodeId, {
121
+ for (const edge of this.listEdges({
122
+ node_id: node.id,
89
123
  direction: "out",
90
- edgeType: "has_ref_comment",
91
- });
92
- if (natspec) {
93
- if (!natspec.dst_id)
94
- throw new Error(`has_ref_comment edge ${natspec.id} has no destination`);
95
- docstring = this.getNode(natspec.dst_id).docstring ?? null;
96
- }
97
- else {
98
- docstring = node.docstring;
124
+ edge_type: "has_ref_comment",
125
+ })) {
126
+ if (edge.dst_id) {
127
+ docstring = (await this.getNode(edge.dst_id)).docstring ?? null;
128
+ break;
129
+ }
99
130
  }
100
131
  }
101
132
  }
@@ -105,31 +136,35 @@ export class Graph {
105
136
  const chunk = sanitizeChunk(utf8Decoder.decode(source.subarray(node.src_start_pos, node.src_end_pos)));
106
137
  return docstring ? `${docstring}\n${chunk}` : chunk;
107
138
  }
108
- #ensureBuilt() {
109
- if (!this.#isBuilt)
110
- throw new Error("must run build() first");
139
+ #ensureBuilt(parts = ALL_PARTS) {
140
+ const missing = parts.filter((part) => !this.#isBuilt[part]);
141
+ if (missing.length)
142
+ throw new Error(`must build ${missing.join(", ")}`);
143
+ }
144
+ #needs(part) {
145
+ return !this.#isBuilt[part];
111
146
  }
112
147
  #ingestSnapshot({ nodes, edges, files }) {
113
- this.edges = edges;
114
- this.fileMap = new Map(files.map((file) => [file.id, file]));
115
- this.nodeMap = new Map();
116
- this.idMap = new Map();
117
- this.reverseIdMap = new Map();
118
- this.sourceMap = new Map();
148
+ for (const file of files) {
149
+ this.#fileMap.set(file.id, file);
150
+ this.#filePaths.set(file.path, file.id);
151
+ this.#languages.add(file.language);
152
+ }
119
153
  for (const node of nodes) {
120
- this.reverseIdMap.set(node.id, node.short_id);
121
- this.idMap.set(node.short_id, node.id);
122
- this.nodeMap.set(node.id, node);
123
- const inFile = this.sourceMap.get(node.file_id);
124
- if (inFile)
125
- inFile.push(node.id);
126
- else
127
- this.sourceMap.set(node.file_id, [node.id]);
154
+ this.#shortIdToId.set(node.short_id, node.id);
155
+ this.#nodeMap.set(node.id, node);
156
+ this.#languages.add(node.language);
128
157
  }
129
- this.#buildAdjacency();
130
- this.#isBuilt = true;
131
- }
132
- #buildAdjacency() {
158
+ if (edges.length)
159
+ this.#buildAdjacency(edges);
160
+ if (files.length)
161
+ this.#isBuilt.files = true;
162
+ if (nodes.length)
163
+ this.#isBuilt.nodes = true;
164
+ if (edges.length)
165
+ this.#isBuilt.edges = true;
166
+ }
167
+ #buildAdjacency(edges) {
133
168
  const adjacency = new Map();
134
169
  const reverse = new Map();
135
170
  const push = (map, key, edge) => {
@@ -139,112 +174,286 @@ export class Graph {
139
174
  else
140
175
  map.set(key, [edge]);
141
176
  };
142
- for (const edge of this.edges) {
177
+ for (const edge of edges) {
178
+ this.#edgeMap.set(edgeKey(edge), edge);
143
179
  push(adjacency, edge.src_id, edge);
144
180
  if (edge.dst_id)
145
181
  push(reverse, edge.dst_id, edge);
146
182
  }
147
183
  for (const list of adjacency.values())
148
- list.sort((a, b) => a.src_start_pos - b.src_start_pos);
184
+ list.sort((a, b) => a.index - b.index);
149
185
  this.#adjacency = adjacency;
150
186
  this.#reverseAdjacency = reverse;
151
- this.#edgeById = new Map(this.edges.map((edge) => [edge.id, edge]));
152
- }
153
- getShortFromId(nodeId) {
154
- return mustGet(this.reverseIdMap, nodeId, "node id");
155
- }
156
- getIdFromShort(shortId) {
157
- return mustGet(this.idMap, shortId, "short id");
158
- }
159
- getAllNodes() {
160
- this.#ensureBuilt();
161
- return [...this.nodeMap.values()];
162
- }
163
- /** Nodes with no incoming edges. */
164
- getRootNodes() {
165
- return this.getAllNodes().filter((node) => !this.#reverseAdjacency.has(node.id));
166
187
  }
167
- getAllFiles() {
168
- this.#ensureBuilt();
169
- return [...this.fileMap.values()];
170
- }
171
- exists(nodeId) {
172
- return this.nodeMap.has(nodeId);
173
- }
174
- existsShortId(shortId) {
175
- return this.idMap.has(shortId);
176
- }
177
- getNode(nodeId) {
178
- this.#ensureBuilt();
179
- return mustGet(this.nodeMap, nodeId, "node");
180
- }
181
- getFile(fileId) {
182
- this.#ensureBuilt();
183
- return mustGet(this.fileMap, fileId, "file");
188
+ listNodes(params) {
189
+ const required = ["nodes"];
190
+ if (params?.no_deps !== undefined)
191
+ required.push("files");
192
+ if (params?.is_root !== undefined || params?.fqn !== undefined)
193
+ required.push("edges");
194
+ this.#ensureBuilt(required);
195
+ const nodes = [...this.#nodeMap.values()];
196
+ if (!params)
197
+ return nodes;
198
+ const fqn = params.fqn === undefined
199
+ ? []
200
+ : params.fqn
201
+ .trim()
202
+ .replace(PARAMS_RE, "")
203
+ .split(DELIMITER_RE)
204
+ .filter((part) => part);
205
+ if (params.fqn !== undefined && !fqn.length)
206
+ return [];
207
+ return nodes.filter((node) => {
208
+ if (fqn.length) {
209
+ if (node.name !== fqn[fqn.length - 1])
210
+ return false;
211
+ const qualified = this.qualifiedParts(node);
212
+ if (qualified.length < fqn.length ||
213
+ qualified.slice(-fqn.length).some((part, i) => part !== fqn[i]))
214
+ return false;
215
+ }
216
+ if (params.node_type !== undefined && node.node_type !== params.node_type)
217
+ return false;
218
+ if (params.name !== undefined &&
219
+ node.name.toLowerCase() !== params.name.toLowerCase())
220
+ return false;
221
+ if (params.file_id !== undefined && node.file_id !== params.file_id)
222
+ return false;
223
+ if (params.file_path !== undefined &&
224
+ node.file_path !== params.file_path) {
225
+ return false;
226
+ }
227
+ if (params.is_entrypoint !== undefined &&
228
+ node.is_entrypoint !== params.is_entrypoint)
229
+ return false;
230
+ if (params.is_callable !== undefined &&
231
+ node.is_callable !== params.is_callable)
232
+ return false;
233
+ if (params.is_declaration !== undefined &&
234
+ node.is_declaration !== params.is_declaration)
235
+ return false;
236
+ if (params.is_container !== undefined &&
237
+ node.is_container !== params.is_container)
238
+ return false;
239
+ if (params.is_implemented !== undefined &&
240
+ node.is_implemented !== params.is_implemented)
241
+ return false;
242
+ if (params.ll_kind !== undefined &&
243
+ !node.low_level_kinds.some((item) => item.kind === params.ll_kind))
244
+ return false;
245
+ if (params.language !== undefined && node.language !== params.language)
246
+ return false;
247
+ if (params.visibility !== undefined &&
248
+ node.visibility !== params.visibility)
249
+ return false;
250
+ if (params.mutability !== undefined &&
251
+ node.mutability !== params.mutability)
252
+ return false;
253
+ if (params.no_deps !== undefined &&
254
+ params.no_deps &&
255
+ this.getFile(node.file_id).is_dependency)
256
+ return false;
257
+ if (params.is_root !== undefined &&
258
+ params.is_root === this.#reverseAdjacency.has(node.id))
259
+ return false;
260
+ return true;
261
+ });
184
262
  }
185
- /** Distinct languages in this snapshot (e.g. Solidity + Rust in a monorepo). */
186
- get languages() {
187
- this.#ensureBuilt();
188
- return new Set([...this.fileMap.values()].map((file) => file.language));
263
+ /**
264
+ * Lists edges. With `node_id`, each returned edge is a copy with `direction` set relative to
265
+ * that node; without it, `direction` is ignored and the snapshot's edges are returned as-is.
266
+ */
267
+ listEdges(params) {
268
+ this.#ensureBuilt(["nodes", "edges"]);
269
+ const edges = [...this.#edgeMap.values()];
270
+ const ofType = (edge) => params?.edge_type === undefined || edge.edge_type === params.edge_type;
271
+ if (!params?.node_id)
272
+ return edges.filter(ofType);
273
+ const node = this._resolveNodeLocId(params.node_id);
274
+ const out = [];
275
+ if (params.direction === "out") {
276
+ for (const edge of this.#adjacency.get(node.id) ?? [])
277
+ if (ofType(edge))
278
+ out.push({ ...edge, direction: "out" });
279
+ }
280
+ else if (params.direction === "in") {
281
+ for (const edge of this.#reverseAdjacency.get(node.id) ?? [])
282
+ if (ofType(edge))
283
+ out.push({ ...edge, direction: "in" });
284
+ }
285
+ else {
286
+ for (const edge of edges) {
287
+ if (!ofType(edge))
288
+ continue;
289
+ if (edge.src_id === node.id)
290
+ out.push({ ...edge, direction: "out" });
291
+ if (edge.dst_id === node.id)
292
+ out.push({ ...edge, direction: "in" });
293
+ }
294
+ }
295
+ return out;
189
296
  }
190
- getNodeLanguage(nodeId) {
191
- return this.getNode(nodeId).language;
297
+ listFiles() {
298
+ this.#ensureBuilt(["files"]);
299
+ return [...this.#fileMap.values()];
300
+ }
301
+ /** @internal The node for a full id or a short id. */
302
+ _resolveNodeLocId(ref) {
303
+ this.#ensureBuilt(["nodes"]);
304
+ const node = this.#nodeMap.get(ref);
305
+ if (node)
306
+ return node;
307
+ const nodeId = this.#shortIdToId.get(ref);
308
+ const byShortId = nodeId === undefined ? undefined : this.#nodeMap.get(nodeId);
309
+ if (byShortId)
310
+ return byShortId;
311
+ throw new NodeResolutionError(`${ref} is not a valid node reference`);
192
312
  }
193
313
  /**
194
- * Edges touching a node: outgoing first (by source position), then incoming.
195
- * Each returned edge is a copy with `direction` set relative to `nodeId`.
314
+ * The node's name preceded by its enclosing definitions, outermost first, and its module for
315
+ * languages that namespace by file.
196
316
  */
197
- getEdgesForNode(nodeId, { direction = null, edgeType = null } = {}) {
198
- this.#ensureBuilt();
199
- if (direction !== null && direction !== "in" && direction !== "out") {
200
- throw new Error(`invalid edge direction: ${String(direction)}`);
317
+ qualifiedParts(node) {
318
+ this.#ensureBuilt(["nodes", "edges"]);
319
+ const parts = [node.name];
320
+ const seen = new Set([node.id]);
321
+ let nodeId = node.id;
322
+ while (true) {
323
+ const parent = this.#reverseAdjacency
324
+ .get(nodeId)
325
+ ?.find((edge) => edge.edge_type === "defines")?.src_id;
326
+ if (parent === undefined || seen.has(parent))
327
+ break;
328
+ seen.add(parent);
329
+ parts.push(this.#nodeMap.get(parent).name);
330
+ nodeId = parent;
201
331
  }
202
- const out = [];
203
- const collect = (edges, dir) => {
204
- for (const edge of edges ?? []) {
205
- if (edgeType === null || edge.edge_type === edgeType)
206
- out.push({ ...edge, direction: dir });
332
+ if (node.language !== "solidity") {
333
+ // the module as the SARIF export writes it
334
+ const module = node.file_path
335
+ .replace(/\.py$/, "")
336
+ .replace(/\/__init__$/, "")
337
+ .replaceAll("/", ".");
338
+ parts.push(...module
339
+ .split(DELIMITER_RE)
340
+ .filter((part) => part)
341
+ .reverse());
342
+ }
343
+ return parts.reverse();
344
+ }
345
+ async #resolveNodeLocPhysical(ref) {
346
+ this.#ensureBuilt(["nodes", "files"]);
347
+ const resolveUri = () => {
348
+ const segments = ref.uri
349
+ .split("/")
350
+ .filter((part) => part !== "." && part !== "..");
351
+ for (let length = 1; length <= segments.length; length++) {
352
+ const suffix = segments.slice(-length).join("/");
353
+ const matches = [...this.#filePaths.keys()].filter((known) => known.split("/").slice(-length).join("/") === suffix);
354
+ const [match] = matches;
355
+ if (matches.length === 1 && match !== undefined)
356
+ return match;
207
357
  }
358
+ throw new NodeResolutionError(`could not resolve ${ref.uri} to exactly one file`);
208
359
  };
209
- if (direction !== "in")
210
- collect(this.#adjacency.get(nodeId), "out");
211
- if (direction !== "out")
212
- collect(this.#reverseAdjacency.get(nodeId), "in");
213
- return out;
214
- }
215
- /** All edges, optionally of one type. Edges have no direction unless queried against a node. */
216
- getEdges({ edgeType = null, } = {}) {
217
- this.#ensureBuilt();
218
- return edgeType === null
219
- ? [...this.edges]
220
- : this.edges.filter((edge) => edge.edge_type === edgeType);
360
+ const fileId = this.#filePaths.get(resolveUri());
361
+ const content = utf8Encoder.encode(await this.getFileContent(fileId));
362
+ const [byteStart, byteEnd] = this.#resolveByteRange(content, ref);
363
+ let minRange = 1_000_000;
364
+ let best = null;
365
+ for (const node of this.listNodes({ file_id: fileId })) {
366
+ if (node.src_start_pos <= byteStart && node.src_end_pos >= byteEnd) {
367
+ const range = node.src_end_pos - node.src_start_pos;
368
+ if (range < minRange) {
369
+ best = node;
370
+ minRange = range;
371
+ }
372
+ }
373
+ }
374
+ if (!best)
375
+ throw new NodeResolutionError("no node is contained to the physical location");
376
+ return best;
377
+ }
378
+ #resolveByteRange(content, loc) {
379
+ if (loc.byteOffset !== undefined && loc.byteLength !== undefined)
380
+ return [loc.byteOffset, loc.byteOffset + loc.byteLength];
381
+ if (loc.charOffset !== undefined && loc.charLength !== undefined) {
382
+ const text = utf8Decoder.decode(content);
383
+ return [
384
+ codePointsToBytes(text, loc.charOffset),
385
+ codePointsToBytes(text, loc.charOffset + loc.charLength),
386
+ ];
387
+ }
388
+ const lines = splitLines(content);
389
+ const lineStart = (line) => lines
390
+ .slice(0, line - 1)
391
+ .reduce((total, bytes) => total + bytes.length + 1, 0);
392
+ if (loc.startLine !== undefined && loc.endLine !== undefined) {
393
+ if (loc.startLine < 1 ||
394
+ loc.endLine > lines.length ||
395
+ loc.startLine > loc.endLine)
396
+ throw new NodeResolutionError(`lines ${loc.startLine}-${loc.endLine} are outside the file`);
397
+ if (loc.startColumn !== undefined && loc.endColumn !== undefined)
398
+ return [
399
+ lineStart(loc.startLine) + loc.startColumn - 1,
400
+ lineStart(loc.endLine) + loc.endColumn - 1,
401
+ ];
402
+ const first = lines[loc.startLine - 1];
403
+ const last = lines[loc.endLine - 1];
404
+ let indent = 0;
405
+ while (indent < first.length &&
406
+ ASCII_WHITESPACE.has(first[indent]))
407
+ indent++;
408
+ let end = last.length;
409
+ while (end > 0 && last[end - 1] === CARRIAGE_RETURN)
410
+ end--;
411
+ return [lineStart(loc.startLine) + indent, lineStart(loc.endLine) + end];
412
+ }
413
+ throw new NodeResolutionError("the region has no line, character or byte coordinates");
414
+ }
415
+ /** A file by its id, its path, or a path suffix that matches exactly one file. */
416
+ getFile(ref) {
417
+ this.#ensureBuilt(["files"]);
418
+ const file = this.#fileMap.get(ref);
419
+ if (file)
420
+ return file;
421
+ if (ref.includes(".") || ref.includes("/")) {
422
+ const exact = this.#filePaths.get(ref);
423
+ if (exact !== undefined)
424
+ return this.#fileMap.get(exact);
425
+ const candidates = [...this.#filePaths.keys()].filter((path) => path.endsWith(ref));
426
+ const [only] = candidates;
427
+ if (candidates.length === 1 && only !== undefined)
428
+ return this.#fileMap.get(this.#filePaths.get(only));
429
+ if (candidates.length > 1)
430
+ throw new Error(`${ref} is not specific enough, resolved to many paths ${candidates.join(", ")}`);
431
+ }
432
+ throw new Error(`${ref} is not a valid file reference`);
221
433
  }
222
- /** Resolves a snapshot edge by its row id. */
223
- getEdgeById(edgeId) {
224
- this.#ensureBuilt();
225
- return this.#edgeById.get(edgeId) ?? null;
434
+ /** Distinct languages in this snapshot (e.g. Solidity + Rust in a monorepo). */
435
+ get languages() {
436
+ if (!this.#isBuilt.nodes && !this.#isBuilt.files)
437
+ throw new Error("must build nodes or files");
438
+ return new Set(this.#languages);
226
439
  }
227
440
  /** Walks incoming edges until it reaches a node of `nodeType`. */
228
- traverseUpToNodeType(nodeId, nodeType) {
229
- const stack = [nodeId];
441
+ traverseUpToNodeType(sourceNodeId, nodeType) {
442
+ const stack = [sourceNodeId];
230
443
  const seen = new Set();
231
444
  while (stack.length) {
232
445
  const current = stack.pop();
233
446
  if (seen.has(current))
234
447
  continue;
235
448
  seen.add(current);
236
- const node = this.getNode(current);
449
+ const node = this._resolveNodeLocId(current);
237
450
  if (node.node_type === nodeType)
238
451
  return node;
239
- for (const edge of this.getEdgesForNode(current, { direction: "in" }))
452
+ for (const edge of this.listEdges({ node_id: current, direction: "in" }))
240
453
  stack.push(edge.src_id);
241
454
  }
242
455
  return null;
243
456
  }
244
- getNodesInFile(fileId) {
245
- this.#ensureBuilt();
246
- return [...(this.sourceMap.get(fileId) ?? [])];
247
- }
248
457
  /** Shortest path length treating the graph as undirected (-1 if disconnected). */
249
458
  getDistance(fromNodeId, toNodeId) {
250
459
  this.#ensureBuilt();
@@ -259,12 +468,12 @@ export class Graph {
259
468
  if (visited.has(nodeId))
260
469
  continue;
261
470
  visited.add(nodeId);
262
- for (const edge of this.getEdgesForNode(nodeId, { direction: "in" })) {
263
- if (!visited.has(edge.src_id))
471
+ for (const edge of this.listEdges({ node_id: nodeId })) {
472
+ if (edge.direction === "in" && !visited.has(edge.src_id))
264
473
  queue.push([edge.src_id, dist + 1]);
265
- }
266
- for (const edge of this.getEdgesForNode(nodeId, { direction: "out" })) {
267
- if (edge.dst_id && !visited.has(edge.dst_id))
474
+ if (edge.direction === "out" &&
475
+ edge.dst_id &&
476
+ !visited.has(edge.dst_id))
268
477
  queue.push([edge.dst_id, dist + 1]);
269
478
  }
270
479
  }
@@ -284,10 +493,12 @@ export class Graph {
284
493
  if (visited.has(nodeId))
285
494
  continue;
286
495
  visited.add(nodeId);
287
- for (const edge of this.getEdgesForNode(nodeId, { direction: "in" })) {
288
- if (edge.edge_type === "calls")
289
- queue.push(edge.src_id);
290
- }
496
+ for (const edge of this.listEdges({
497
+ node_id: nodeId,
498
+ direction: "in",
499
+ edge_type: "calls",
500
+ }))
501
+ queue.push(edge.src_id);
291
502
  }
292
503
  return false;
293
504
  }
@@ -304,51 +515,14 @@ export class Graph {
304
515
  while (stack.length) {
305
516
  const current = stack.pop();
306
517
  seen.add(current);
307
- const node = this.getNode(current);
518
+ const node = this._resolveNodeLocId(current);
308
519
  if (node.merkle_hash === merkleHash)
309
520
  return node.id;
310
- for (const edge of this.getEdgesForNode(current, { direction: "out" })) {
521
+ for (const edge of this.listEdges({ node_id: current, direction: "out" }))
311
522
  if (edge.dst_id && !seen.has(edge.dst_id))
312
523
  stack.push(edge.dst_id);
313
- }
314
524
  }
315
525
  return null;
316
526
  }
317
- getCallableTypes(language) {
318
- return language === "solidity"
319
- ? new Set([
320
- "function_definition",
321
- "fallback_receive_definition",
322
- "modifier_definition",
323
- "constructor_definition",
324
- ])
325
- : new Set();
326
- }
327
- getDeclarationTypes(language) {
328
- return language === "solidity"
329
- ? new Set([
330
- "enum_declaration",
331
- "error_declaration",
332
- "struct_declaration",
333
- "event_definition",
334
- "state_variable_declaration",
335
- "constant_variable_declaration",
336
- ])
337
- : new Set();
338
- }
339
- getExcludeTypes(language) {
340
- return language === "solidity"
341
- ? new Set(["if_statement", "ternary_expression", "try_statement"])
342
- : new Set();
343
- }
344
- getContainerTypes(language) {
345
- return language === "solidity"
346
- ? new Set([
347
- "contract_declaration",
348
- "library_declaration",
349
- "interface_declaration",
350
- ])
351
- : new Set();
352
- }
353
527
  }
354
528
  //# sourceMappingURL=graph.js.map