@saluzi/codegraph 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/dist/bin/codegraph.d.ts +25 -0
  2. package/dist/bin/node-version-check.d.ts +37 -0
  3. package/dist/bin/uninstall.d.ts +14 -0
  4. package/dist/context/formatter.d.ts +33 -0
  5. package/dist/context/formatter.js +244 -0
  6. package/dist/context/index.d.ts +117 -0
  7. package/dist/context/index.js +1050 -0
  8. package/dist/db/index.d.ts +101 -0
  9. package/dist/db/index.js +250 -0
  10. package/dist/db/migrations.d.ts +47 -0
  11. package/dist/db/migrations.js +131 -0
  12. package/dist/db/queries.d.ts +291 -0
  13. package/dist/db/queries.js +1349 -0
  14. package/dist/db/schema.sql +151 -0
  15. package/dist/db/sqlite-adapter.d.ts +49 -0
  16. package/dist/db/sqlite-adapter.js +141 -0
  17. package/dist/directory.d.ts +62 -0
  18. package/dist/directory.js +264 -0
  19. package/dist/errors.d.ts +149 -0
  20. package/dist/errors.js +219 -0
  21. package/dist/extraction/dfm-extractor.d.ts +31 -0
  22. package/dist/extraction/dfm-extractor.js +151 -0
  23. package/dist/extraction/grammars.d.ts +94 -0
  24. package/dist/extraction/grammars.js +357 -0
  25. package/dist/extraction/index.d.ts +148 -0
  26. package/dist/extraction/index.js +1286 -0
  27. package/dist/extraction/languages/c-cpp.d.ts +4 -0
  28. package/dist/extraction/languages/c-cpp.js +126 -0
  29. package/dist/extraction/languages/csharp.d.ts +3 -0
  30. package/dist/extraction/languages/csharp.js +72 -0
  31. package/dist/extraction/languages/dart.d.ts +3 -0
  32. package/dist/extraction/languages/dart.js +192 -0
  33. package/dist/extraction/languages/go.d.ts +3 -0
  34. package/dist/extraction/languages/go.js +58 -0
  35. package/dist/extraction/languages/index.d.ts +10 -0
  36. package/dist/extraction/languages/index.js +49 -0
  37. package/dist/extraction/languages/java.d.ts +3 -0
  38. package/dist/extraction/languages/java.js +64 -0
  39. package/dist/extraction/languages/javascript.d.ts +3 -0
  40. package/dist/extraction/languages/javascript.js +90 -0
  41. package/dist/extraction/languages/kotlin.d.ts +3 -0
  42. package/dist/extraction/languages/kotlin.js +253 -0
  43. package/dist/extraction/languages/lua.d.ts +3 -0
  44. package/dist/extraction/languages/lua.js +150 -0
  45. package/dist/extraction/languages/luau.d.ts +3 -0
  46. package/dist/extraction/languages/luau.js +37 -0
  47. package/dist/extraction/languages/pascal.d.ts +3 -0
  48. package/dist/extraction/languages/pascal.js +66 -0
  49. package/dist/extraction/languages/php.d.ts +3 -0
  50. package/dist/extraction/languages/php.js +107 -0
  51. package/dist/extraction/languages/python.d.ts +3 -0
  52. package/dist/extraction/languages/python.js +56 -0
  53. package/dist/extraction/languages/ruby.d.ts +3 -0
  54. package/dist/extraction/languages/ruby.js +114 -0
  55. package/dist/extraction/languages/rust.d.ts +3 -0
  56. package/dist/extraction/languages/rust.js +109 -0
  57. package/dist/extraction/languages/scala.d.ts +3 -0
  58. package/dist/extraction/languages/scala.js +139 -0
  59. package/dist/extraction/languages/swift.d.ts +3 -0
  60. package/dist/extraction/languages/swift.js +91 -0
  61. package/dist/extraction/languages/typescript.d.ts +3 -0
  62. package/dist/extraction/languages/typescript.js +129 -0
  63. package/dist/extraction/liquid-extractor.d.ts +52 -0
  64. package/dist/extraction/liquid-extractor.js +313 -0
  65. package/dist/extraction/parse-worker.d.ts +8 -0
  66. package/dist/extraction/parse-worker.js +94 -0
  67. package/dist/extraction/svelte-extractor.d.ts +56 -0
  68. package/dist/extraction/svelte-extractor.js +272 -0
  69. package/dist/extraction/tree-sitter-helpers.d.ts +39 -0
  70. package/dist/extraction/tree-sitter-helpers.js +103 -0
  71. package/dist/extraction/tree-sitter-types.d.ts +191 -0
  72. package/dist/extraction/tree-sitter-types.js +10 -0
  73. package/dist/extraction/tree-sitter.d.ts +238 -0
  74. package/dist/extraction/tree-sitter.js +2430 -0
  75. package/dist/extraction/vue-extractor.d.ts +36 -0
  76. package/dist/extraction/vue-extractor.js +163 -0
  77. package/dist/extraction/wasm/tree-sitter-c.wasm +0 -0
  78. package/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  79. package/dist/extraction/wasm/tree-sitter-cpp.wasm +0 -0
  80. package/dist/extraction/wasm/tree-sitter-dart.wasm +0 -0
  81. package/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  82. package/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  83. package/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  84. package/dist/extraction/wasm/tree-sitter-kotlin.wasm +0 -0
  85. package/dist/extraction/wasm/tree-sitter-lua.wasm +0 -0
  86. package/dist/extraction/wasm/tree-sitter-luau.wasm +0 -0
  87. package/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  88. package/dist/extraction/wasm/tree-sitter-php.wasm +0 -0
  89. package/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  90. package/dist/extraction/wasm/tree-sitter-ruby.wasm +0 -0
  91. package/dist/extraction/wasm/tree-sitter-rust.wasm +0 -0
  92. package/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  93. package/dist/extraction/wasm/tree-sitter-swift.wasm +0 -0
  94. package/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  95. package/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  96. package/dist/extraction/wasm-runtime-flags.d.ts +46 -0
  97. package/dist/extraction/wasm-runtime-flags.js +105 -0
  98. package/dist/graph/index.d.ts +8 -0
  99. package/dist/graph/index.js +13 -0
  100. package/dist/graph/queries.d.ts +109 -0
  101. package/dist/graph/queries.js +366 -0
  102. package/dist/graph/traversal.d.ts +137 -0
  103. package/dist/graph/traversal.js +528 -0
  104. package/dist/index.d.ts +509 -0
  105. package/dist/index.js +800 -0
  106. package/dist/installer/claude-md-template.d.ts +19 -0
  107. package/dist/installer/config-writer.d.ts +29 -0
  108. package/dist/installer/index.d.ts +140 -0
  109. package/dist/installer/instructions-template.d.ts +30 -0
  110. package/dist/installer/targets/claude.d.ts +55 -0
  111. package/dist/installer/targets/codex.d.ts +18 -0
  112. package/dist/installer/targets/cursor.d.ts +35 -0
  113. package/dist/installer/targets/hermes.d.ts +18 -0
  114. package/dist/installer/targets/opencode.d.ts +30 -0
  115. package/dist/installer/targets/registry.d.ts +38 -0
  116. package/dist/installer/targets/shared.d.ts +92 -0
  117. package/dist/installer/targets/toml.d.ts +64 -0
  118. package/dist/installer/targets/types.d.ts +122 -0
  119. package/dist/mcp/index.d.ts +98 -0
  120. package/dist/mcp/server-instructions.d.ts +20 -0
  121. package/dist/mcp/tools.d.ts +269 -0
  122. package/dist/mcp/transport.d.ts +117 -0
  123. package/dist/resolution/frameworks/cargo-workspace.d.ts +20 -0
  124. package/dist/resolution/frameworks/cargo-workspace.js +225 -0
  125. package/dist/resolution/frameworks/csharp.d.ts +8 -0
  126. package/dist/resolution/frameworks/csharp.js +213 -0
  127. package/dist/resolution/frameworks/drupal.d.ts +51 -0
  128. package/dist/resolution/frameworks/drupal.js +335 -0
  129. package/dist/resolution/frameworks/express.d.ts +8 -0
  130. package/dist/resolution/frameworks/express.js +225 -0
  131. package/dist/resolution/frameworks/go.d.ts +8 -0
  132. package/dist/resolution/frameworks/go.js +158 -0
  133. package/dist/resolution/frameworks/index.d.ts +52 -0
  134. package/dist/resolution/frameworks/index.js +137 -0
  135. package/dist/resolution/frameworks/java.d.ts +8 -0
  136. package/dist/resolution/frameworks/java.js +177 -0
  137. package/dist/resolution/frameworks/laravel.d.ts +13 -0
  138. package/dist/resolution/frameworks/laravel.js +248 -0
  139. package/dist/resolution/frameworks/nestjs.d.ts +26 -0
  140. package/dist/resolution/frameworks/nestjs.js +374 -0
  141. package/dist/resolution/frameworks/python.d.ts +10 -0
  142. package/dist/resolution/frameworks/python.js +278 -0
  143. package/dist/resolution/frameworks/react.d.ts +8 -0
  144. package/dist/resolution/frameworks/react.js +272 -0
  145. package/dist/resolution/frameworks/ruby.d.ts +8 -0
  146. package/dist/resolution/frameworks/ruby.js +198 -0
  147. package/dist/resolution/frameworks/rust.d.ts +8 -0
  148. package/dist/resolution/frameworks/rust.js +207 -0
  149. package/dist/resolution/frameworks/svelte.d.ts +9 -0
  150. package/dist/resolution/frameworks/svelte.js +249 -0
  151. package/dist/resolution/frameworks/swift.d.ts +10 -0
  152. package/dist/resolution/frameworks/swift.js +376 -0
  153. package/dist/resolution/frameworks/vue.d.ts +9 -0
  154. package/dist/resolution/frameworks/vue.js +306 -0
  155. package/dist/resolution/import-resolver.d.ts +61 -0
  156. package/dist/resolution/import-resolver.js +663 -0
  157. package/dist/resolution/index.d.ts +118 -0
  158. package/dist/resolution/index.js +744 -0
  159. package/dist/resolution/lru-cache.d.ts +24 -0
  160. package/dist/resolution/lru-cache.js +62 -0
  161. package/dist/resolution/name-matcher.d.ts +50 -0
  162. package/dist/resolution/name-matcher.js +384 -0
  163. package/dist/resolution/path-aliases.d.ts +72 -0
  164. package/dist/resolution/path-aliases.js +238 -0
  165. package/dist/resolution/strip-comments.d.ts +40 -0
  166. package/dist/resolution/strip-comments.js +441 -0
  167. package/dist/resolution/types.d.ts +181 -0
  168. package/dist/resolution/types.js +8 -0
  169. package/dist/search/query-parser.d.ts +61 -0
  170. package/dist/search/query-parser.js +177 -0
  171. package/dist/search/query-utils.d.ts +59 -0
  172. package/dist/search/query-utils.js +383 -0
  173. package/dist/sync/git-hooks.d.ts +54 -0
  174. package/dist/sync/git-hooks.js +223 -0
  175. package/dist/sync/index.d.ts +25 -0
  176. package/dist/sync/index.js +28 -0
  177. package/dist/sync/watch-policy.d.ts +51 -0
  178. package/dist/sync/watch-policy.js +124 -0
  179. package/dist/sync/watcher.d.ts +83 -0
  180. package/dist/sync/watcher.js +192 -0
  181. package/dist/types.d.ts +433 -0
  182. package/dist/types.js +75 -0
  183. package/dist/ui/glyphs.d.ts +42 -0
  184. package/dist/ui/shimmer-progress.d.ts +11 -0
  185. package/dist/ui/shimmer-worker.d.ts +2 -0
  186. package/dist/ui/types.d.ts +20 -0
  187. package/dist/utils.d.ts +231 -0
  188. package/dist/utils.js +549 -0
  189. package/package.json +24 -0
@@ -0,0 +1,744 @@
1
+ "use strict";
2
+ /**
3
+ * Reference Resolution Orchestrator
4
+ *
5
+ * Coordinates all reference resolution strategies.
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
41
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
42
+ };
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.ReferenceResolver = void 0;
45
+ exports.createResolver = createResolver;
46
+ const fs = __importStar(require("fs"));
47
+ const path = __importStar(require("path"));
48
+ const name_matcher_1 = require("./name-matcher");
49
+ const import_resolver_1 = require("./import-resolver");
50
+ const frameworks_1 = require("./frameworks");
51
+ const path_aliases_1 = require("./path-aliases");
52
+ const errors_1 = require("../errors");
53
+ const lru_cache_1 = require("./lru-cache");
54
+ /**
55
+ * Cache size limits. Each per-resolver cache is bounded so memory
56
+ * stays flat on large codebases (20k+ files). Sizes were chosen to
57
+ * cover the working set for typical resolution batches without
58
+ * exceeding a few hundred MB worst-case. Override via the env var
59
+ * `CODEGRAPH_RESOLVER_CACHE_SIZE` (single integer applied to all
60
+ * caches) when tuning for very large or very small projects.
61
+ */
62
+ const DEFAULT_CACHE_LIMIT = 5_000;
63
+ function resolveCacheLimit() {
64
+ const raw = process.env.CODEGRAPH_RESOLVER_CACHE_SIZE;
65
+ if (!raw)
66
+ return DEFAULT_CACHE_LIMIT;
67
+ const parsed = Number.parseInt(raw, 10);
68
+ if (Number.isFinite(parsed) && parsed > 0)
69
+ return parsed;
70
+ return DEFAULT_CACHE_LIMIT;
71
+ }
72
+ // Re-export types
73
+ __exportStar(require("./types"), exports);
74
+ // Pre-built Sets for O(1) built-in lookups (allocated once, shared across all instances)
75
+ const JS_BUILT_INS = new Set([
76
+ 'console', 'window', 'document', 'global', 'process',
77
+ 'Promise', 'Array', 'Object', 'String', 'Number', 'Boolean',
78
+ 'Date', 'Math', 'JSON', 'RegExp', 'Error', 'Map', 'Set',
79
+ 'setTimeout', 'setInterval', 'clearTimeout', 'clearInterval',
80
+ 'fetch', 'require', 'module', 'exports', '__dirname', '__filename',
81
+ ]);
82
+ const REACT_HOOKS = new Set([
83
+ 'useState', 'useEffect', 'useContext', 'useReducer', 'useCallback',
84
+ 'useMemo', 'useRef', 'useLayoutEffect', 'useImperativeHandle', 'useDebugValue',
85
+ ]);
86
+ const PYTHON_BUILT_INS = new Set([
87
+ 'print', 'len', 'range', 'str', 'int', 'float', 'list', 'dict', 'set', 'tuple',
88
+ 'open', 'input', 'type', 'isinstance', 'hasattr', 'getattr', 'setattr',
89
+ 'super', 'self', 'cls', 'None', 'True', 'False',
90
+ ]);
91
+ const PYTHON_BUILT_IN_TYPES = new Set([
92
+ 'list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'bool',
93
+ 'bytes', 'bytearray', 'frozenset', 'object', 'super',
94
+ ]);
95
+ const PYTHON_BUILT_IN_METHODS = new Set([
96
+ 'append', 'extend', 'insert', 'remove', 'pop', 'clear', 'sort', 'reverse', 'copy',
97
+ 'update', 'keys', 'values', 'items', 'get',
98
+ 'add', 'discard', 'union', 'intersection', 'difference',
99
+ 'split', 'join', 'strip', 'lstrip', 'rstrip', 'replace', 'lower', 'upper',
100
+ 'startswith', 'endswith', 'find', 'index', 'count', 'encode', 'decode',
101
+ 'format', 'isdigit', 'isalpha', 'isalnum',
102
+ 'read', 'write', 'readline', 'readlines', 'close', 'flush', 'seek',
103
+ ]);
104
+ const GO_STDLIB_PACKAGES = new Set([
105
+ 'fmt', 'os', 'io', 'net', 'http', 'log', 'math', 'sort', 'sync',
106
+ 'time', 'path', 'bytes', 'strings', 'strconv', 'errors', 'context',
107
+ 'json', 'xml', 'csv', 'html', 'template', 'regexp', 'reflect',
108
+ 'runtime', 'testing', 'flag', 'bufio', 'crypto', 'encoding',
109
+ 'filepath', 'hash', 'mime', 'rand', 'signal', 'sql', 'syscall',
110
+ 'unicode', 'unsafe', 'atomic', 'binary', 'debug', 'exec', 'heap',
111
+ 'ring', 'scanner', 'tar', 'zip', 'gzip', 'zlib', 'tls', 'url',
112
+ 'user', 'pprof', 'trace', 'ast', 'build', 'parser', 'printer',
113
+ 'token', 'types', 'cgo', 'plugin', 'race', 'ioutil',
114
+ // Kubernetes-common stdlib aliases
115
+ 'utilruntime', 'utilwait', 'utilnet',
116
+ ]);
117
+ const GO_BUILT_INS = new Set([
118
+ 'make', 'new', 'len', 'cap', 'append', 'copy', 'delete', 'close',
119
+ 'panic', 'recover', 'print', 'println', 'complex', 'real', 'imag',
120
+ 'error', 'nil', 'true', 'false', 'iota',
121
+ 'int', 'int8', 'int16', 'int32', 'int64',
122
+ 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'uintptr',
123
+ 'float32', 'float64', 'complex64', 'complex128',
124
+ 'string', 'bool', 'byte', 'rune', 'any',
125
+ ]);
126
+ const PASCAL_UNIT_PREFIXES = [
127
+ 'System.', 'Winapi.', 'Vcl.', 'Fmx.', 'Data.', 'Datasnap.',
128
+ 'Soap.', 'Xml.', 'Web.', 'REST.', 'FireDAC.', 'IBX.',
129
+ 'IdHTTP', 'IdTCP', 'IdSSL',
130
+ ];
131
+ const PASCAL_BUILT_INS = new Set([
132
+ 'System', 'SysUtils', 'Classes', 'Types', 'Variants', 'StrUtils',
133
+ 'Math', 'DateUtils', 'IOUtils', 'Generics.Collections', 'Generics.Defaults',
134
+ 'Rtti', 'TypInfo', 'SyncObjs', 'RegularExpressions',
135
+ 'SysInit', 'Windows', 'Messages', 'Graphics', 'Controls', 'Forms',
136
+ 'Dialogs', 'StdCtrls', 'ExtCtrls', 'ComCtrls', 'Menus', 'ActnList',
137
+ 'WriteLn', 'Write', 'ReadLn', 'Read', 'Inc', 'Dec', 'Ord', 'Chr',
138
+ 'Length', 'SetLength', 'High', 'Low', 'Assigned', 'FreeAndNil',
139
+ 'Format', 'IntToStr', 'StrToInt', 'FloatToStr', 'StrToFloat',
140
+ 'Trim', 'UpperCase', 'LowerCase', 'Pos', 'Copy', 'Delete', 'Insert',
141
+ 'Now', 'Date', 'Time', 'DateToStr', 'StrToDate',
142
+ 'Raise', 'Exit', 'Break', 'Continue', 'Abort',
143
+ 'True', 'False', 'nil', 'Self', 'Result',
144
+ 'Create', 'Destroy', 'Free',
145
+ 'TObject', 'TComponent', 'TPersistent', 'TInterfacedObject',
146
+ 'TList', 'TStringList', 'TStrings', 'TStream', 'TMemoryStream', 'TFileStream',
147
+ 'Exception', 'EAbort', 'EConvertError', 'EAccessViolation',
148
+ 'IInterface', 'IUnknown',
149
+ ]);
150
+ /**
151
+ * Reference Resolver
152
+ *
153
+ * Orchestrates reference resolution using multiple strategies.
154
+ */
155
+ class ReferenceResolver {
156
+ projectRoot;
157
+ queries;
158
+ context;
159
+ frameworks = [];
160
+ // All per-resolver caches are LRU-bounded. Previously these were
161
+ // unbounded Maps that grew with every distinct lookup and OOM'd on
162
+ // codebases with 20k+ files (see issue: unbounded cache growth).
163
+ nodeCache; // per-file node cache
164
+ fileCache; // per-file content cache
165
+ importMappingCache;
166
+ reExportCache;
167
+ nameCache; // name → nodes cache
168
+ lowerNameCache; // lower(name) → nodes cache
169
+ qualifiedNameCache; // qualified_name → nodes cache
170
+ knownNames = null; // all known symbol names for fast pre-filtering
171
+ knownFiles = null;
172
+ cachesWarmed = false;
173
+ // tsconfig/jsconfig path-alias map. `undefined` = not yet computed,
174
+ // `null` = computed and absent. Treated as immutable for the
175
+ // resolver's lifetime; callers re-create the resolver if config changes.
176
+ projectAliases = undefined;
177
+ constructor(projectRoot, queries) {
178
+ this.projectRoot = projectRoot;
179
+ this.queries = queries;
180
+ const limit = resolveCacheLimit();
181
+ // The content cache is heavier (full file text), so we give it a
182
+ // smaller budget than the metadata caches.
183
+ const contentLimit = Math.max(64, Math.floor(limit / 5));
184
+ this.nodeCache = new lru_cache_1.LRUCache(limit);
185
+ this.fileCache = new lru_cache_1.LRUCache(contentLimit);
186
+ this.importMappingCache = new lru_cache_1.LRUCache(limit);
187
+ this.reExportCache = new lru_cache_1.LRUCache(limit);
188
+ this.nameCache = new lru_cache_1.LRUCache(limit);
189
+ this.lowerNameCache = new lru_cache_1.LRUCache(limit);
190
+ this.qualifiedNameCache = new lru_cache_1.LRUCache(limit);
191
+ this.context = this.createContext();
192
+ }
193
+ /**
194
+ * Initialize the resolver (detect frameworks, etc.)
195
+ */
196
+ initialize() {
197
+ this.frameworks = (0, frameworks_1.detectFrameworks)(this.context);
198
+ this.clearCaches();
199
+ }
200
+ /**
201
+ * Pre-build lightweight caches for resolution.
202
+ * Node lookups are now handled by indexed SQLite queries instead of
203
+ * loading all nodes into memory (which caused OOM on large codebases).
204
+ * We cache the set of known symbol names for fast pre-filtering.
205
+ */
206
+ warmCaches() {
207
+ if (this.cachesWarmed)
208
+ return;
209
+ // Only cache the set of known file paths (lightweight string set)
210
+ this.knownFiles = new Set(this.queries.getAllFilePaths());
211
+ // Cache all distinct symbol names for fast pre-filtering (just strings, not full nodes)
212
+ this.knownNames = new Set(this.queries.getAllNodeNames());
213
+ this.cachesWarmed = true;
214
+ }
215
+ /**
216
+ * Clear internal caches
217
+ */
218
+ clearCaches() {
219
+ this.nodeCache.clear();
220
+ this.fileCache.clear();
221
+ this.importMappingCache.clear();
222
+ this.reExportCache.clear();
223
+ this.nameCache.clear();
224
+ this.lowerNameCache.clear();
225
+ this.qualifiedNameCache.clear();
226
+ this.knownNames = null;
227
+ this.knownFiles = null;
228
+ this.cachesWarmed = false;
229
+ }
230
+ /**
231
+ * Create the resolution context
232
+ */
233
+ createContext() {
234
+ return {
235
+ getNodesInFile: (filePath) => {
236
+ if (!this.nodeCache.has(filePath)) {
237
+ this.nodeCache.set(filePath, this.queries.getNodesByFile(filePath));
238
+ }
239
+ return this.nodeCache.get(filePath);
240
+ },
241
+ getNodesByName: (name) => {
242
+ const cached = this.nameCache.get(name);
243
+ if (cached !== undefined)
244
+ return cached;
245
+ const result = this.queries.getNodesByName(name);
246
+ this.nameCache.set(name, result);
247
+ return result;
248
+ },
249
+ getNodesByQualifiedName: (qualifiedName) => {
250
+ const cached = this.qualifiedNameCache.get(qualifiedName);
251
+ if (cached !== undefined)
252
+ return cached;
253
+ const result = this.queries.getNodesByQualifiedNameExact(qualifiedName);
254
+ this.qualifiedNameCache.set(qualifiedName, result);
255
+ return result;
256
+ },
257
+ getNodesByKind: (kind) => {
258
+ return this.queries.getNodesByKind(kind);
259
+ },
260
+ fileExists: (filePath) => {
261
+ // Check pre-built known files set first (O(1))
262
+ if (this.knownFiles) {
263
+ const normalized = filePath.replace(/\\/g, '/');
264
+ if (this.knownFiles.has(filePath) || this.knownFiles.has(normalized)) {
265
+ return true;
266
+ }
267
+ }
268
+ // Fall back to filesystem for files not yet indexed
269
+ const fullPath = path.join(this.projectRoot, filePath);
270
+ try {
271
+ return fs.existsSync(fullPath);
272
+ }
273
+ catch (error) {
274
+ (0, errors_1.logDebug)('Error checking file existence', { filePath, error: String(error) });
275
+ return false;
276
+ }
277
+ },
278
+ readFile: (filePath) => {
279
+ if (this.fileCache.has(filePath)) {
280
+ return this.fileCache.get(filePath);
281
+ }
282
+ const fullPath = path.join(this.projectRoot, filePath);
283
+ try {
284
+ const content = fs.readFileSync(fullPath, 'utf-8');
285
+ this.fileCache.set(filePath, content);
286
+ return content;
287
+ }
288
+ catch (error) {
289
+ (0, errors_1.logDebug)('Failed to read file for resolution', { filePath, error: String(error) });
290
+ this.fileCache.set(filePath, null);
291
+ return null;
292
+ }
293
+ },
294
+ getProjectRoot: () => this.projectRoot,
295
+ getAllFiles: () => {
296
+ return this.queries.getAllFilePaths();
297
+ },
298
+ listDirectories: (relativePath) => {
299
+ const target = relativePath === '.' || relativePath === ''
300
+ ? this.projectRoot
301
+ : path.join(this.projectRoot, relativePath);
302
+ try {
303
+ return fs
304
+ .readdirSync(target, { withFileTypes: true })
305
+ .filter((entry) => entry.isDirectory())
306
+ .map((entry) => entry.name);
307
+ }
308
+ catch (error) {
309
+ (0, errors_1.logDebug)('Failed to list directory for resolution', {
310
+ relativePath,
311
+ error: String(error),
312
+ });
313
+ return [];
314
+ }
315
+ },
316
+ getNodesByLowerName: (lowerName) => {
317
+ const cached = this.lowerNameCache.get(lowerName);
318
+ if (cached !== undefined)
319
+ return cached;
320
+ const result = this.queries.getNodesByLowerName(lowerName);
321
+ this.lowerNameCache.set(lowerName, result);
322
+ return result;
323
+ },
324
+ getImportMappings: (filePath, language) => {
325
+ const cacheKey = filePath;
326
+ const cached = this.importMappingCache.get(cacheKey);
327
+ if (cached)
328
+ return cached;
329
+ const content = this.context.readFile(filePath);
330
+ if (!content) {
331
+ this.importMappingCache.set(cacheKey, []);
332
+ return [];
333
+ }
334
+ const mappings = (0, import_resolver_1.extractImportMappings)(filePath, content, language);
335
+ this.importMappingCache.set(cacheKey, mappings);
336
+ return mappings;
337
+ },
338
+ getProjectAliases: () => {
339
+ if (this.projectAliases === undefined) {
340
+ this.projectAliases = (0, path_aliases_1.loadProjectAliases)(this.projectRoot);
341
+ }
342
+ return this.projectAliases;
343
+ },
344
+ getReExports: (filePath, language) => {
345
+ const cached = this.reExportCache.get(filePath);
346
+ if (cached)
347
+ return cached;
348
+ const content = this.context.readFile(filePath);
349
+ if (!content) {
350
+ this.reExportCache.set(filePath, []);
351
+ return [];
352
+ }
353
+ const reExports = (0, import_resolver_1.extractReExports)(content, language);
354
+ this.reExportCache.set(filePath, reExports);
355
+ return reExports;
356
+ },
357
+ };
358
+ }
359
+ /**
360
+ * Resolve all unresolved references
361
+ */
362
+ resolveAll(unresolvedRefs, onProgress) {
363
+ // Pre-load all nodes into memory for fast lookups
364
+ this.warmCaches();
365
+ const resolved = [];
366
+ const unresolved = [];
367
+ const byMethod = {};
368
+ // Convert to our internal format, using denormalized fields when available
369
+ const refs = unresolvedRefs.map((ref) => ({
370
+ fromNodeId: ref.fromNodeId,
371
+ referenceName: ref.referenceName,
372
+ referenceKind: ref.referenceKind,
373
+ line: ref.line,
374
+ column: ref.column,
375
+ filePath: ref.filePath || this.getFilePathFromNodeId(ref.fromNodeId),
376
+ language: ref.language || this.getLanguageFromNodeId(ref.fromNodeId),
377
+ })).filter((ref) => ref.referenceName != null && ref.referenceName !== '');
378
+ const total = refs.length;
379
+ let lastReportedPercent = -1;
380
+ for (let i = 0; i < refs.length; i++) {
381
+ const ref = refs[i]; // Array index is guaranteed to be in bounds
382
+ const result = this.resolveOne(ref);
383
+ if (result) {
384
+ resolved.push(result);
385
+ byMethod[result.resolvedBy] = (byMethod[result.resolvedBy] || 0) + 1;
386
+ }
387
+ else {
388
+ unresolved.push(ref);
389
+ }
390
+ // Report progress every 1% to avoid too many updates
391
+ if (onProgress) {
392
+ const currentPercent = Math.floor((i / total) * 100);
393
+ if (currentPercent > lastReportedPercent) {
394
+ lastReportedPercent = currentPercent;
395
+ onProgress(i + 1, total);
396
+ }
397
+ }
398
+ }
399
+ // Final progress report
400
+ if (onProgress && total > 0) {
401
+ onProgress(total, total);
402
+ }
403
+ return {
404
+ resolved,
405
+ unresolved,
406
+ stats: {
407
+ total: refs.length,
408
+ resolved: resolved.length,
409
+ unresolved: unresolved.length,
410
+ byMethod,
411
+ },
412
+ };
413
+ }
414
+ /**
415
+ * Check if a reference name has any possible match in the codebase.
416
+ * Uses the pre-built knownNames set to skip expensive resolution
417
+ * for names that definitely don't exist as symbols.
418
+ */
419
+ hasAnyPossibleMatch(name) {
420
+ if (!this.knownNames)
421
+ return true; // no pre-filter available
422
+ // Direct name match
423
+ if (this.knownNames.has(name))
424
+ return true;
425
+ // For qualified names like "obj.method" or "Class::method", check the parts
426
+ const dotIdx = name.indexOf('.');
427
+ if (dotIdx > 0) {
428
+ const receiver = name.substring(0, dotIdx);
429
+ const member = name.substring(dotIdx + 1);
430
+ if (this.knownNames.has(receiver) || this.knownNames.has(member))
431
+ return true;
432
+ // Also check capitalized receiver (instance-method resolution)
433
+ const capitalized = receiver.charAt(0).toUpperCase() + receiver.slice(1);
434
+ if (this.knownNames.has(capitalized))
435
+ return true;
436
+ }
437
+ const colonIdx = name.indexOf('::');
438
+ if (colonIdx > 0) {
439
+ const receiver = name.substring(0, colonIdx);
440
+ const member = name.substring(colonIdx + 2);
441
+ if (this.knownNames.has(receiver) || this.knownNames.has(member))
442
+ return true;
443
+ }
444
+ // For path-like references (e.g., "snippets/drawer-menu.liquid"), check the filename
445
+ const slashIdx = name.lastIndexOf('/');
446
+ if (slashIdx > 0) {
447
+ const fileName = name.substring(slashIdx + 1);
448
+ if (this.knownNames.has(fileName))
449
+ return true;
450
+ }
451
+ return false;
452
+ }
453
+ /**
454
+ * Does `ref.referenceName` match an import declared in its containing
455
+ * file? Used as a pre-filter escape so re-export chain resolution
456
+ * still gets a chance when the name has no project-wide declaration.
457
+ */
458
+ matchesAnyImport(ref) {
459
+ const imports = this.context.getImportMappings(ref.filePath, ref.language);
460
+ if (imports.length === 0)
461
+ return false;
462
+ for (const imp of imports) {
463
+ if (imp.localName === ref.referenceName ||
464
+ ref.referenceName.startsWith(imp.localName + '.')) {
465
+ return true;
466
+ }
467
+ }
468
+ return false;
469
+ }
470
+ /**
471
+ * Resolve a single reference
472
+ */
473
+ resolveOne(ref) {
474
+ // Skip built-in/external references
475
+ if (this.isBuiltInOrExternal(ref)) {
476
+ return null;
477
+ }
478
+ // Fast pre-filter: skip if no symbol with this name exists anywhere
479
+ // AND the name doesn't match a local import. The import escape is
480
+ // necessary because re-export rename chains (`import { login }
481
+ // from './barrel'` where the barrel has `export { signIn as login }
482
+ // from './auth'`) intentionally call a name that has no
483
+ // declaration anywhere — only the renamed upstream symbol does.
484
+ if (!this.hasAnyPossibleMatch(ref.referenceName) && !this.matchesAnyImport(ref)) {
485
+ return null;
486
+ }
487
+ const candidates = [];
488
+ // Strategy 1: Try framework-specific resolution
489
+ for (const framework of this.frameworks) {
490
+ const result = framework.resolve(ref, this.context);
491
+ if (result) {
492
+ if (result.confidence >= 0.9)
493
+ return result; // High confidence, return immediately
494
+ candidates.push(result);
495
+ }
496
+ }
497
+ // Strategy 2: Try import-based resolution
498
+ const importResult = (0, import_resolver_1.resolveViaImport)(ref, this.context);
499
+ if (importResult) {
500
+ if (importResult.confidence >= 0.9)
501
+ return importResult;
502
+ candidates.push(importResult);
503
+ }
504
+ // Strategy 3: Try name matching
505
+ const nameResult = (0, name_matcher_1.matchReference)(ref, this.context);
506
+ if (nameResult) {
507
+ candidates.push(nameResult);
508
+ }
509
+ if (candidates.length === 0)
510
+ return null;
511
+ // Return highest confidence candidate
512
+ return candidates.reduce((best, curr) => curr.confidence > best.confidence ? curr : best);
513
+ }
514
+ /**
515
+ * Create edges from resolved references
516
+ */
517
+ createEdges(resolved) {
518
+ return resolved.map((ref) => {
519
+ let kind = ref.original.referenceKind;
520
+ // Promote "extends" to "implements" when a class/struct targets an interface
521
+ if (kind === 'extends') {
522
+ const targetNode = this.queries.getNodeById(ref.targetNodeId);
523
+ if (targetNode && (targetNode.kind === 'interface' || targetNode.kind === 'protocol')) {
524
+ const sourceNode = this.queries.getNodeById(ref.original.fromNodeId);
525
+ if (sourceNode && sourceNode.kind !== 'interface' && sourceNode.kind !== 'protocol') {
526
+ kind = 'implements';
527
+ }
528
+ }
529
+ }
530
+ // Promote "calls" to "instantiates" when the resolved target is a
531
+ // class/struct. Languages without a `new` keyword (Python, Ruby)
532
+ // express instantiation as `Foo()` — extraction can't tell that
533
+ // apart from a function call without symbol info, but resolution
534
+ // can: if `Foo` resolves to a class, the call IS an instantiation.
535
+ if (kind === 'calls') {
536
+ const targetNode = this.queries.getNodeById(ref.targetNodeId);
537
+ if (targetNode && (targetNode.kind === 'class' || targetNode.kind === 'struct')) {
538
+ kind = 'instantiates';
539
+ }
540
+ }
541
+ return {
542
+ source: ref.original.fromNodeId,
543
+ target: ref.targetNodeId,
544
+ kind,
545
+ line: ref.original.line,
546
+ column: ref.original.column,
547
+ metadata: {
548
+ confidence: ref.confidence,
549
+ resolvedBy: ref.resolvedBy,
550
+ },
551
+ };
552
+ });
553
+ }
554
+ /**
555
+ * Resolve and persist edges to database
556
+ */
557
+ resolveAndPersist(unresolvedRefs, onProgress) {
558
+ const result = this.resolveAll(unresolvedRefs, onProgress);
559
+ // Create edges from resolved references
560
+ const edges = this.createEdges(result.resolved);
561
+ // Insert edges into database
562
+ if (edges.length > 0) {
563
+ this.queries.insertEdges(edges);
564
+ }
565
+ // Clean up resolved refs from unresolved_refs table so metrics are accurate
566
+ if (result.resolved.length > 0) {
567
+ this.queries.deleteSpecificResolvedReferences(result.resolved.map((r) => ({
568
+ fromNodeId: r.original.fromNodeId,
569
+ referenceName: r.original.referenceName,
570
+ referenceKind: r.original.referenceKind,
571
+ })));
572
+ }
573
+ return result;
574
+ }
575
+ /**
576
+ * Resolve and persist in batches to keep memory bounded.
577
+ * Processes unresolved references in chunks, persisting edges and cleaning
578
+ * up resolved refs after each batch to avoid accumulating large arrays.
579
+ */
580
+ async resolveAndPersistBatched(onProgress, batchSize = 5000) {
581
+ this.warmCaches();
582
+ // Remove null/empty reference_name rows that would cause infinite batch loops
583
+ this.queries.deleteNullReferenceNames();
584
+ const total = this.queries.getUnresolvedReferencesCount();
585
+ let processed = 0;
586
+ const aggregateStats = {
587
+ total: 0,
588
+ resolved: 0,
589
+ unresolved: 0,
590
+ byMethod: {},
591
+ };
592
+ // Process in batches. We always read from offset 0 because resolved refs
593
+ // are deleted after each batch, shifting the remaining rows forward.
594
+ while (true) {
595
+ const batch = this.queries.getUnresolvedReferencesBatch(0, batchSize);
596
+ if (batch.length === 0)
597
+ break;
598
+ const result = this.resolveAll(batch);
599
+ // Persist edges immediately
600
+ const edges = this.createEdges(result.resolved);
601
+ if (edges.length > 0) {
602
+ this.queries.insertEdges(edges);
603
+ }
604
+ // Clean up resolved refs so they don't appear in the next batch
605
+ if (result.resolved.length > 0) {
606
+ this.queries.deleteSpecificResolvedReferences(result.resolved.map((r) => ({
607
+ fromNodeId: r.original.fromNodeId,
608
+ referenceName: r.original.referenceName,
609
+ referenceKind: r.original.referenceKind,
610
+ })));
611
+ }
612
+ // Delete unresolvable refs from this batch to avoid re-processing them
613
+ if (result.unresolved.length > 0) {
614
+ this.queries.deleteSpecificResolvedReferences(result.unresolved.map((r) => ({
615
+ fromNodeId: r.fromNodeId,
616
+ referenceName: r.referenceName,
617
+ referenceKind: r.referenceKind,
618
+ })));
619
+ }
620
+ // Aggregate stats
621
+ aggregateStats.total += result.stats.total;
622
+ aggregateStats.resolved += result.stats.resolved;
623
+ aggregateStats.unresolved += result.stats.unresolved;
624
+ for (const [method, count] of Object.entries(result.stats.byMethod)) {
625
+ aggregateStats.byMethod[method] = (aggregateStats.byMethod[method] || 0) + count;
626
+ }
627
+ processed += batch.length;
628
+ onProgress?.(processed, total);
629
+ // Yield so progress UI can render between batches
630
+ await new Promise(resolve => setImmediate(resolve));
631
+ // If nothing was resolved or removed in this batch, we'd loop forever
632
+ // on the same rows. Break to avoid infinite loop.
633
+ if (result.resolved.length === 0 && result.unresolved.length === batch.length) {
634
+ break;
635
+ }
636
+ }
637
+ return {
638
+ resolved: [],
639
+ unresolved: [],
640
+ stats: aggregateStats,
641
+ };
642
+ }
643
+ /**
644
+ * Get detected frameworks
645
+ */
646
+ getDetectedFrameworks() {
647
+ return this.frameworks.map((f) => f.name);
648
+ }
649
+ /**
650
+ * Check if reference is to a built-in or external symbol
651
+ */
652
+ isBuiltInOrExternal(ref) {
653
+ const name = ref.referenceName;
654
+ const isJsTs = ref.language === 'typescript' || ref.language === 'javascript'
655
+ || ref.language === 'tsx' || ref.language === 'jsx';
656
+ // JavaScript/TypeScript built-ins
657
+ if (isJsTs && JS_BUILT_INS.has(name)) {
658
+ return true;
659
+ }
660
+ // Common JS/TS library calls (console.log, Math.floor, JSON.parse)
661
+ if (isJsTs && (name.startsWith('console.') || name.startsWith('Math.') || name.startsWith('JSON.'))) {
662
+ return true;
663
+ }
664
+ // React hooks from React itself
665
+ if (isJsTs && REACT_HOOKS.has(name)) {
666
+ return true;
667
+ }
668
+ // Python built-ins (bare calls only — dotted calls like console.print are method calls)
669
+ if (ref.language === 'python' && PYTHON_BUILT_INS.has(name)) {
670
+ return true;
671
+ }
672
+ // Python built-in method calls (e.g., list.extend, dict.update)
673
+ if (ref.language === 'python') {
674
+ const dotIdx = name.indexOf('.');
675
+ if (dotIdx > 0) {
676
+ const receiver = name.substring(0, dotIdx);
677
+ const method = name.substring(dotIdx + 1);
678
+ // Filter calls on built-in types (list.append, dict.update, etc.)
679
+ if (PYTHON_BUILT_IN_TYPES.has(receiver)) {
680
+ return true;
681
+ }
682
+ // Filter built-in methods on non-class receivers
683
+ // (e.g., items.append where items is a local list variable)
684
+ // But allow if the capitalized receiver matches a known codebase class
685
+ if (PYTHON_BUILT_IN_METHODS.has(method)) {
686
+ const capitalized = receiver.charAt(0).toUpperCase() + receiver.slice(1);
687
+ if (!this.knownNames?.has(capitalized)) {
688
+ return true;
689
+ }
690
+ }
691
+ }
692
+ if (PYTHON_BUILT_IN_METHODS.has(name)) {
693
+ return true;
694
+ }
695
+ }
696
+ // Go standard library packages — refs like "fmt.Println", "http.ListenAndServe", etc.
697
+ if (ref.language === 'go') {
698
+ const dotIdx = name.indexOf('.');
699
+ if (dotIdx > 0) {
700
+ const pkg = name.substring(0, dotIdx);
701
+ if (GO_STDLIB_PACKAGES.has(pkg)) {
702
+ return true;
703
+ }
704
+ }
705
+ if (GO_BUILT_INS.has(name)) {
706
+ return true;
707
+ }
708
+ }
709
+ // Pascal/Delphi built-ins and standard library units
710
+ if (ref.language === 'pascal') {
711
+ if (PASCAL_UNIT_PREFIXES.some((p) => name.startsWith(p))) {
712
+ return true;
713
+ }
714
+ if (PASCAL_BUILT_INS.has(name)) {
715
+ return true;
716
+ }
717
+ }
718
+ return false;
719
+ }
720
+ /**
721
+ * Get file path from node ID
722
+ */
723
+ getFilePathFromNodeId(nodeId) {
724
+ const node = this.queries.getNodeById(nodeId);
725
+ return node?.filePath || '';
726
+ }
727
+ /**
728
+ * Get language from node ID
729
+ */
730
+ getLanguageFromNodeId(nodeId) {
731
+ const node = this.queries.getNodeById(nodeId);
732
+ return node?.language || 'unknown';
733
+ }
734
+ }
735
+ exports.ReferenceResolver = ReferenceResolver;
736
+ /**
737
+ * Create a reference resolver instance
738
+ */
739
+ function createResolver(projectRoot, queries) {
740
+ const resolver = new ReferenceResolver(projectRoot, queries);
741
+ resolver.initialize();
742
+ return resolver;
743
+ }
744
+ //# sourceMappingURL=index.js.map