-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcodeql-development-mcp-server.js
More file actions
executable file
·9473 lines (9362 loc) · 324 KB
/
codeql-development-mcp-server.js
File metadata and controls
executable file
·9473 lines (9362 loc) · 324 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// src/utils/logger.ts
var logger;
var init_logger = __esm({
"src/utils/logger.ts"() {
"use strict";
logger = {
info: (message, ...args) => {
console.error(`[INFO] ${(/* @__PURE__ */ new Date()).toISOString()} ${message}`, ...args);
},
error: (message, ...args) => {
console.error(`[ERROR] ${(/* @__PURE__ */ new Date()).toISOString()} ${message}`, ...args);
},
warn: (message, ...args) => {
console.error(`[WARN] ${(/* @__PURE__ */ new Date()).toISOString()} ${message}`, ...args);
},
debug: (message, ...args) => {
if (process.env.DEBUG) {
console.error(`[DEBUG] ${(/* @__PURE__ */ new Date()).toISOString()} ${message}`, ...args);
}
}
};
}
});
// src/lib/server-config.ts
import { createHash } from "crypto";
function computeConfigHash(type2, config) {
const sortKeys = (_key, value) => {
if (value && typeof value === "object" && !Array.isArray(value)) {
const sorted = {};
for (const k of Object.keys(value).sort()) {
sorted[k] = value[k];
}
return sorted;
}
return value;
};
const canonical = JSON.stringify({ config, type: type2 }, sortKeys);
return createHash("sha256").update(canonical).digest("hex");
}
function buildQueryServerArgs(config) {
const args = [
"execute",
"query-server2"
];
if (config.searchPath) {
args.push(`--search-path=${config.searchPath}`);
}
if (config.commonCaches) {
args.push(`--common-caches=${config.commonCaches}`);
}
if (config.logdir) {
args.push(`--logdir=${config.logdir}`);
}
if (config.threads !== void 0) {
args.push(`--threads=${config.threads}`);
}
if (config.timeout !== void 0) {
args.push(`--timeout=${config.timeout}`);
}
if (config.maxDiskCache !== void 0) {
args.push(`--max-disk-cache=${config.maxDiskCache}`);
}
if (config.evaluatorLog) {
args.push(`--evaluator-log=${config.evaluatorLog}`);
}
if (config.debug) {
args.push("--debug");
args.push("--tuple-counting");
} else if (config.tupleCounting) {
args.push("--tuple-counting");
}
return args;
}
function buildCLIServerArgs(config) {
const args = [
"execute",
"cli-server"
];
if (config.commonCaches) {
args.push(`--common-caches=${config.commonCaches}`);
}
if (config.logdir) {
args.push(`--logdir=${config.logdir}`);
}
return args;
}
var init_server_config = __esm({
"src/lib/server-config.ts"() {
"use strict";
}
});
// src/utils/package-paths.ts
var package_paths_exports = {};
__export(package_paths_exports, {
getPackageRootDir: () => getPackageRootDir,
getPackageVersion: () => getPackageVersion,
getUserWorkspaceDir: () => getUserWorkspaceDir,
getWorkspaceRootDir: () => getWorkspaceRootDir,
packageRootDir: () => packageRootDir,
resolveToolQueryPackPath: () => resolveToolQueryPackPath,
workspaceRootDir: () => workspaceRootDir
});
import { dirname, resolve } from "path";
import { existsSync, readFileSync } from "fs";
import { fileURLToPath } from "url";
function isRunningFromSource(dir) {
const normalized = dir.replace(/\\/g, "/");
return /\/src(\/[^/]+)?$/.test(normalized);
}
function getPackageRootDir(currentDir = __dirname) {
return isRunningFromSource(currentDir) ? resolve(currentDir, "..", "..") : resolve(currentDir, "..");
}
function getWorkspaceRootDir(packageRoot) {
const pkgRoot = packageRoot ?? getPackageRootDir();
const parentDir = resolve(pkgRoot, "..");
try {
const parentPkgPath = resolve(parentDir, "package.json");
if (existsSync(parentPkgPath)) {
const parentPkg = JSON.parse(readFileSync(parentPkgPath, "utf8"));
if (parentPkg.workspaces) {
return parentDir;
}
}
} catch {
}
return pkgRoot;
}
function resolveToolQueryPackPath(language, packageRoot) {
const pkgRoot = packageRoot ?? getPackageRootDir();
return resolve(pkgRoot, "ql", language, "tools", "src");
}
function getPackageVersion() {
if (_cachedVersion !== void 0) return _cachedVersion;
try {
const pkgPath = resolve(getPackageRootDir(), "package.json");
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
_cachedVersion = pkg.version ?? "0.0.0";
} catch {
_cachedVersion = "0.0.0";
}
return _cachedVersion;
}
function getUserWorkspaceDir() {
if (process.env.CODEQL_MCP_WORKSPACE) {
return process.env.CODEQL_MCP_WORKSPACE;
}
if (workspaceRootDir === packageRootDir) {
return process.cwd();
}
return workspaceRootDir;
}
var __filename, __dirname, _cachedVersion, packageRootDir, workspaceRootDir;
var init_package_paths = __esm({
"src/utils/package-paths.ts"() {
"use strict";
__filename = fileURLToPath(import.meta.url);
__dirname = dirname(__filename);
packageRootDir = getPackageRootDir();
workspaceRootDir = getWorkspaceRootDir(packageRootDir);
}
});
// src/utils/temp-dir.ts
import { mkdirSync, mkdtempSync } from "fs";
import { isAbsolute, join, resolve as resolve2 } from "path";
function getProjectTmpBase() {
mkdirSync(PROJECT_TMP_BASE, { recursive: true });
return PROJECT_TMP_BASE;
}
function createProjectTempDir(prefix) {
const base = getProjectTmpBase();
return mkdtempSync(join(base, prefix));
}
function getProjectTmpDir(name) {
const dir = join(getProjectTmpBase(), name);
mkdirSync(dir, { recursive: true });
return dir;
}
var PROJECT_TMP_BASE;
var init_temp_dir = __esm({
"src/utils/temp-dir.ts"() {
"use strict";
init_package_paths();
PROJECT_TMP_BASE = process.env.CODEQL_MCP_TMP_DIR ? isAbsolute(process.env.CODEQL_MCP_TMP_DIR) ? process.env.CODEQL_MCP_TMP_DIR : resolve2(process.cwd(), process.env.CODEQL_MCP_TMP_DIR) : join(getPackageRootDir(), ".tmp");
}
});
// src/utils/process-ready.ts
import { clearTimeout, setTimeout as setTimeout2 } from "timers";
function waitForProcessReady(child, name, opts) {
const timeoutMs = opts?.timeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
return new Promise((resolve12, reject) => {
let settled = false;
const cleanup = () => {
settled = true;
child.stderr?.removeListener("data", onStderr);
child.stdout?.removeListener("data", onStdout);
child.removeListener("error", onError);
child.removeListener("exit", onExit);
clearTimeout(timer);
};
const onStderr = () => {
if (settled) return;
logger.debug(`${name}: ready (stderr output detected)`);
cleanup();
resolve12();
};
const onStdout = () => {
if (settled) return;
logger.debug(`${name}: ready (stdout output detected)`);
cleanup();
resolve12();
};
const onError = (error) => {
if (settled) return;
cleanup();
reject(new Error(`${name} failed to start: ${error.message}`));
};
const onExit = (code) => {
if (settled) return;
cleanup();
reject(new Error(`${name} exited before becoming ready (code: ${code})`));
};
const timer = setTimeout2(() => {
if (settled) return;
logger.warn(`${name}: readiness timeout (${timeoutMs} ms) \u2014 proceeding anyway`);
cleanup();
resolve12();
}, timeoutMs);
child.stderr?.on("data", onStderr);
child.stdout?.on("data", onStdout);
child.on("error", onError);
child.on("exit", onExit);
if (child.killed || child.exitCode !== null) {
cleanup();
reject(new Error(`${name} is not running (exitCode: ${child.exitCode})`));
}
});
}
var DEFAULT_READY_TIMEOUT_MS;
var init_process_ready = __esm({
"src/utils/process-ready.ts"() {
"use strict";
init_logger();
DEFAULT_READY_TIMEOUT_MS = 3e4;
}
});
// src/lib/language-server.ts
import { spawn } from "child_process";
import { EventEmitter } from "events";
import { setTimeout as setTimeout3, clearTimeout as clearTimeout2 } from "timers";
import { pathToFileURL } from "url";
import { delimiter, join as join2 } from "path";
var CodeQLLanguageServer;
var init_language_server = __esm({
"src/lib/language-server.ts"() {
"use strict";
init_logger();
init_package_paths();
init_temp_dir();
init_cli_executor();
init_process_ready();
CodeQLLanguageServer = class extends EventEmitter {
constructor(_options = {}) {
super();
this._options = _options;
}
server = null;
messageId = 1;
pendingResponses = /* @__PURE__ */ new Map();
isInitialized = false;
currentWorkspaceUri;
messageBuffer = "";
async start() {
if (this.server) {
throw new Error("Language server is already running");
}
logger.info("Starting CodeQL Language Server...");
const args = [
"execute",
"language-server",
"--check-errors=ON_CHANGE"
];
if (this._options.searchPath) {
args.push(`--search-path=${this._options.searchPath}`);
}
if (this._options.logdir) {
args.push(`--logdir=${this._options.logdir}`);
}
if (this._options.loglevel) {
args.push(`--loglevel=${this._options.loglevel}`);
}
if (this._options.synchronous) {
args.push("--synchronous");
}
if (this._options.verbosity) {
args.push(`--verbosity=${this._options.verbosity}`);
}
const spawnEnv = { ...process.env };
const codeqlDir = getResolvedCodeQLDir();
if (codeqlDir && spawnEnv.PATH) {
spawnEnv.PATH = `${codeqlDir}${delimiter}${spawnEnv.PATH}`;
} else if (codeqlDir) {
spawnEnv.PATH = codeqlDir;
}
this.server = spawn("codeql", args, {
stdio: ["pipe", "pipe", "pipe"],
env: spawnEnv
});
this.server.stderr?.on("data", (data) => {
logger.debug("CodeQL LS stderr:", data.toString());
});
this.server.stdout?.on("data", (data) => {
this.handleStdout(data);
});
this.server.on("error", (error) => {
logger.error("CodeQL Language Server error:", error);
this.emit("error", error);
});
this.server.on("exit", (code) => {
logger.info("CodeQL Language Server exited with code:", code);
this.server = null;
this.isInitialized = false;
this.emit("exit", code);
});
await waitForProcessReady(this.server, "CodeQL Language Server");
}
handleStdout(data) {
this.messageBuffer += data.toString();
let headerEnd = this.messageBuffer.indexOf("\r\n\r\n");
while (headerEnd !== -1) {
const header = this.messageBuffer.substring(0, headerEnd);
const contentLengthMatch = header.match(/Content-Length: (\d+)/);
if (contentLengthMatch) {
const contentLength = parseInt(contentLengthMatch[1]);
const messageStart = headerEnd + 4;
const messageEnd = messageStart + contentLength;
if (this.messageBuffer.length >= messageEnd) {
const messageContent = this.messageBuffer.substring(messageStart, messageEnd);
this.messageBuffer = this.messageBuffer.substring(messageEnd);
try {
const message = JSON.parse(messageContent);
this.handleMessage(message);
} catch (error) {
logger.error("Failed to parse LSP message:", error, messageContent);
}
headerEnd = this.messageBuffer.indexOf("\r\n\r\n");
} else {
break;
}
} else {
logger.error("Invalid LSP header:", header);
this.messageBuffer = "";
break;
}
}
}
handleMessage(message) {
logger.debug("Received LSP message:", message);
if (message.id !== void 0 && this.pendingResponses.has(Number(message.id))) {
const pending = this.pendingResponses.get(Number(message.id));
this.pendingResponses.delete(Number(message.id));
if (message.error) {
pending.reject(new Error(`LSP Error: ${message.error.message}`));
} else {
pending.resolve(message.result);
}
return;
}
if (message.method === "textDocument/publishDiagnostics") {
this.emit("diagnostics", message.params);
}
}
sendMessage(message) {
if (!this.server?.stdin) {
throw new Error("Language server is not running");
}
const messageStr = JSON.stringify(message);
const contentLength = Buffer.byteLength(messageStr, "utf8");
const header = `Content-Length: ${contentLength}\r
\r
`;
const fullMessage = header + messageStr;
logger.debug("Sending LSP message:", fullMessage);
this.server.stdin.write(fullMessage);
}
sendRequest(method, params) {
const id = this.messageId++;
const message = {
jsonrpc: "2.0",
id,
method,
params
};
return new Promise((resolve12, reject) => {
const timer = setTimeout3(() => {
if (this.pendingResponses.has(id)) {
this.pendingResponses.delete(id);
reject(new Error(`LSP request timeout for method: ${method}`));
}
}, 6e4);
this.pendingResponses.set(id, {
reject: (err) => {
clearTimeout2(timer);
reject(err);
},
resolve: (val) => {
clearTimeout2(timer);
resolve12(val);
}
});
this.sendMessage(message);
});
}
sendNotification(method, params) {
const message = {
jsonrpc: "2.0",
method,
params
};
this.sendMessage(message);
}
/**
* Initialize the language server with an optional workspace URI.
*
* If the server is already initialized with a different workspace, a
* `workspace/didChangeWorkspaceFolders` notification is sent to update
* the workspace context instead of requiring a full restart.
*/
async initialize(workspaceUri) {
if (this.isInitialized) {
if (workspaceUri && workspaceUri !== this.currentWorkspaceUri) {
await this.updateWorkspace(workspaceUri);
}
return;
}
logger.info("Initializing CodeQL Language Server...");
const initParams = {
processId: process.pid,
clientInfo: {
name: "codeql-development-mcp-server",
version: getPackageVersion()
},
capabilities: {
textDocument: {
completion: { completionItem: { snippetSupport: false } },
definition: {},
publishDiagnostics: {},
references: {},
synchronization: {
didClose: true,
didChange: true,
didOpen: true
}
},
workspace: {
workspaceFolders: true
}
}
};
if (workspaceUri) {
initParams.workspaceFolders = [{
uri: workspaceUri,
name: "codeql-workspace"
}];
}
await this.sendRequest("initialize", initParams);
this.sendNotification("initialized", {});
this.currentWorkspaceUri = workspaceUri;
this.isInitialized = true;
logger.info("CodeQL Language Server initialized successfully");
}
/**
* Update the workspace folders on a running, initialized server.
*/
async updateWorkspace(newUri) {
logger.info(`Updating workspace from ${this.currentWorkspaceUri} to ${newUri}`);
const removed = this.currentWorkspaceUri ? [{ uri: this.currentWorkspaceUri, name: "codeql-workspace" }] : [];
this.sendNotification("workspace/didChangeWorkspaceFolders", {
event: {
added: [{ uri: newUri, name: "codeql-workspace" }],
removed
}
});
this.currentWorkspaceUri = newUri;
}
/**
* Get the current workspace URI.
*/
getWorkspaceUri() {
return this.currentWorkspaceUri;
}
async evaluateQL(qlCode, uri) {
if (!this.isInitialized) {
throw new Error("Language server is not initialized");
}
const documentUri = uri || pathToFileURL(join2(getProjectTmpDir("lsp-eval"), "eval.ql")).href;
return new Promise((resolve12, reject) => {
let diagnosticsReceived = false;
const timeout = setTimeout3(() => {
if (!diagnosticsReceived) {
this.removeListener("diagnostics", diagnosticsHandler);
reject(new Error("Timeout waiting for diagnostics"));
}
}, 9e4);
const diagnosticsHandler = (params) => {
if (params.uri === documentUri) {
diagnosticsReceived = true;
clearTimeout2(timeout);
this.removeListener("diagnostics", diagnosticsHandler);
this.sendNotification("textDocument/didClose", {
textDocument: { uri: documentUri }
});
resolve12(params.diagnostics);
}
};
this.on("diagnostics", diagnosticsHandler);
this.sendNotification("textDocument/didOpen", {
textDocument: {
uri: documentUri,
languageId: "ql",
version: 1,
text: qlCode
}
});
});
}
// ---- LSP feature methods (issue #1) ----
/**
* Get code completions at a position in a document.
*/
async getCompletions(params) {
if (!this.isInitialized) {
throw new Error("Language server is not initialized");
}
if (!this.isRunning()) {
throw new Error("Language server process is not running");
}
const result = await this.sendRequest("textDocument/completion", params);
if (result && typeof result === "object" && "items" in result) {
return result.items;
}
return result || [];
}
/**
* Find the definition(s) of a symbol at a position.
*/
async getDefinition(params) {
if (!this.isInitialized) {
throw new Error("Language server is not initialized");
}
if (!this.isRunning()) {
throw new Error("Language server process is not running");
}
const result = await this.sendRequest("textDocument/definition", params);
return this.normalizeLocations(result);
}
/**
* Find all references to a symbol at a position.
*/
async getReferences(params) {
if (!this.isInitialized) {
throw new Error("Language server is not initialized");
}
if (!this.isRunning()) {
throw new Error("Language server process is not running");
}
const result = await this.sendRequest("textDocument/references", {
...params,
context: params.context ?? { includeDeclaration: true }
});
return this.normalizeLocations(result);
}
/**
* Open a text document in the language server.
* The document must be opened before requesting completions, definitions, etc.
*/
openDocument(uri, text, languageId = "ql", version = 1) {
if (!this.isInitialized) {
throw new Error("Language server is not initialized");
}
this.sendNotification("textDocument/didOpen", {
textDocument: { uri, languageId, version, text }
});
}
/**
* Close a text document in the language server.
*/
closeDocument(uri) {
if (!this.isInitialized) {
throw new Error("Language server is not initialized");
}
this.sendNotification("textDocument/didClose", {
textDocument: { uri }
});
}
/**
* Normalize a definition/references/implementation result to Location[].
* The LSP spec allows Location | Location[] | LocationLink[].
*/
normalizeLocations(result) {
if (!result) return [];
if (Array.isArray(result)) {
return result.map((item) => {
if ("targetUri" in item) {
return { uri: item.targetUri, range: item.targetRange };
}
return item;
});
}
if (typeof result === "object" && "uri" in result) {
return [result];
}
return [];
}
async shutdown() {
if (!this.server) {
return;
}
logger.info("Shutting down CodeQL Language Server...");
try {
await this.sendRequest("shutdown", {});
if (this.server) {
this.sendNotification("exit", {});
}
} catch (error) {
logger.warn("Error during graceful shutdown:", error);
}
await new Promise((resolve12) => {
const timer = setTimeout3(() => {
if (this.server) {
this.server.kill("SIGTERM");
}
resolve12();
}, 1e3);
if (this.server) {
this.server.once("exit", () => {
clearTimeout2(timer);
this.server = null;
resolve12();
});
} else {
clearTimeout2(timer);
resolve12();
}
});
this.isInitialized = false;
}
isRunning() {
return this.server !== null && !this.server.killed;
}
};
}
});
// src/lib/query-server.ts
import { spawn as spawn2 } from "child_process";
import { delimiter as delimiter2 } from "path";
import { EventEmitter as EventEmitter2 } from "events";
import { clearTimeout as clearTimeout3, setTimeout as setTimeout4 } from "timers";
var CodeQLQueryServer;
var init_query_server = __esm({
"src/lib/query-server.ts"() {
"use strict";
init_server_config();
init_cli_executor();
init_logger();
init_process_ready();
CodeQLQueryServer = class extends EventEmitter2 {
messageBuffer = "";
messageId = 1;
pendingRequests = /* @__PURE__ */ new Map();
process = null;
config;
constructor(config) {
super();
this.config = config;
}
/**
* Start the query-server2 process.
*/
async start() {
if (this.process) {
throw new Error("Query server is already running");
}
logger.info("Starting CodeQL Query Server (query-server2)...");
const args = buildQueryServerArgs(this.config);
const spawnEnv = { ...process.env };
const codeqlDir = getResolvedCodeQLDir();
if (codeqlDir && spawnEnv.PATH) {
spawnEnv.PATH = `${codeqlDir}${delimiter2}${spawnEnv.PATH}`;
} else if (codeqlDir) {
spawnEnv.PATH = codeqlDir;
}
this.process = spawn2("codeql", args, {
stdio: ["pipe", "pipe", "pipe"],
env: spawnEnv
});
this.process.stderr?.on("data", (data) => {
logger.debug("QueryServer2 stderr:", data.toString());
});
this.process.stdout?.on("data", (data) => {
this.handleStdout(data);
});
this.process.on("error", (error) => {
logger.error("Query server process error:", error);
this.emit("error", error);
});
this.process.on("exit", (code) => {
logger.info(`Query server exited with code: ${code}`);
this.rejectAllPending(new Error(`Query server exited with code: ${code}`));
this.process = null;
this.emit("exit", code);
});
await waitForProcessReady(this.process, "CodeQL Query Server");
logger.info("CodeQL Query Server started");
}
/**
* Send a request to the query server and await the response.
*
* @param method - The JSON-RPC method name.
* @param params - The method parameters.
* @param timeoutMs - Request timeout in milliseconds (default: 300000 = 5 min).
* @returns The result from the server.
*/
sendRequest(method, params, timeoutMs = 3e5) {
const id = this.messageId++;
const message = {
id,
jsonrpc: "2.0",
method,
params
};
return new Promise((resolve12, reject) => {
this.pendingRequests.set(id, { reject, resolve: resolve12 });
try {
this.sendRaw(message);
} catch (error) {
this.pendingRequests.delete(id);
reject(error instanceof Error ? error : new Error(String(error)));
return;
}
const timer = setTimeout4(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Query server request timeout for method: ${method}`));
}
}, timeoutMs);
const originalResolve = resolve12;
const originalReject = reject;
const wrapped = {
reject: (err) => {
clearTimeout3(timer);
originalReject(err);
},
resolve: (val) => {
clearTimeout3(timer);
originalResolve(val);
}
};
this.pendingRequests.set(id, wrapped);
});
}
/**
* Gracefully shut down the query server.
*/
async shutdown() {
if (!this.process) {
return;
}
logger.info("Shutting down CodeQL Query Server...");
try {
await this.sendRequest("shutdown", {}, 5e3);
} catch (error) {
logger.warn("Error during query server graceful shutdown:", error);
}
await new Promise((resolve12) => {
const timer = setTimeout4(() => {
if (this.process) {
this.process.kill("SIGTERM");
this.process = null;
}
resolve12();
}, 2e3);
if (this.process) {
this.process.once("exit", () => {
clearTimeout3(timer);
this.process = null;
resolve12();
});
} else {
clearTimeout3(timer);
resolve12();
}
});
}
/**
* Whether the query server process is running.
*/
isRunning() {
return this.process !== null && !this.process.killed;
}
// ---- private helpers ----
handleStdout(data) {
this.messageBuffer += data.toString();
let headerEnd = this.messageBuffer.indexOf("\r\n\r\n");
while (headerEnd !== -1) {
const header = this.messageBuffer.substring(0, headerEnd);
const contentLengthMatch = header.match(/Content-Length: (\d+)/);
if (contentLengthMatch) {
const contentLength = parseInt(contentLengthMatch[1]);
const messageStart = headerEnd + 4;
const messageEnd = messageStart + contentLength;
if (this.messageBuffer.length >= messageEnd) {
const messageContent = this.messageBuffer.substring(messageStart, messageEnd);
this.messageBuffer = this.messageBuffer.substring(messageEnd);
try {
const message = JSON.parse(messageContent);
this.handleMessage(message);
} catch (error) {
logger.error("Failed to parse query server message:", error);
}
headerEnd = this.messageBuffer.indexOf("\r\n\r\n");
} else {
break;
}
} else {
logger.error("Invalid query server header:", header);
this.messageBuffer = "";
break;
}
}
}
handleMessage(message) {
logger.debug("QueryServer2 message:", message);
if (message.id !== void 0 && this.pendingRequests.has(Number(message.id))) {
const pending = this.pendingRequests.get(Number(message.id));
this.pendingRequests.delete(Number(message.id));
if (message.error) {
pending.reject(new Error(`Query server error: ${message.error.message}`));
} else {
pending.resolve(message.result);
}
return;
}
if (message.method) {
this.emit("notification", { method: message.method, params: message.params });
}
}
rejectAllPending(error) {
for (const [id, pending] of this.pendingRequests) {
pending.reject(error);
this.pendingRequests.delete(id);
}
}
sendRaw(message) {
if (!this.process?.stdin) {
throw new Error("Query server is not running");
}
const body = JSON.stringify(message);
const contentLength = Buffer.byteLength(body, "utf8");
const frame = `Content-Length: ${contentLength}\r
\r
${body}`;
this.process.stdin.write(frame);
}
};
}
});
// src/lib/cli-server.ts
import { spawn as spawn3 } from "child_process";
import { delimiter as delimiter3 } from "path";
import { EventEmitter as EventEmitter3 } from "events";
import { clearTimeout as clearTimeout4, setTimeout as setTimeout5 } from "timers";
var CodeQLCLIServer;
var init_cli_server = __esm({
"src/lib/cli-server.ts"() {
"use strict";
init_server_config();
init_cli_executor();
init_logger();
init_process_ready();
CodeQLCLIServer = class extends EventEmitter3 {
commandInProgress = false;
commandQueue = [];
config;
currentReject = null;
currentResolve = null;
nullBuffer = Buffer.alloc(1);
process = null;
stdoutBuffer = "";
constructor(config) {
super();
this.config = config;
}
/**
* Start the cli-server process.
*/
async start() {
if (this.process) {
throw new Error("CLI server is already running");
}
logger.info("Starting CodeQL CLI Server...");
const args = buildCLIServerArgs(this.config);
const spawnEnv = { ...process.env };
const codeqlDir = getResolvedCodeQLDir();
if (codeqlDir && spawnEnv.PATH) {
spawnEnv.PATH = `${codeqlDir}${delimiter3}${spawnEnv.PATH}`;
} else if (codeqlDir) {
spawnEnv.PATH = codeqlDir;
}
this.process = spawn3("codeql", args, {
stdio: ["pipe", "pipe", "pipe"],
env: spawnEnv
});
this.process.stdout?.on("data", (data) => {
this.handleStdout(data);
});
this.process.stderr?.on("data", (data) => {
logger.debug("CLIServer stderr:", data.toString());
});
this.process.on("error", (error) => {
logger.error("CLI server process error:", error);
if (this.currentReject) {
this.currentReject(error);
this.currentReject = null;
this.currentResolve = null;
}
this.emit("error", error);
});
this.process.on("exit", (code) => {
logger.info(`CLI server exited with code: ${code}`);
if (this.currentReject) {
this.currentReject(new Error(`CLI server exited unexpectedly with code: ${code}`));
this.currentReject = null;
this.currentResolve = null;
}
this.process = null;
this.emit("exit", code);
});
await waitForProcessReady(this.process, "CodeQL CLI Server");
logger.info("CodeQL CLI Server started");
}
/**
* Run a CodeQL CLI command through the persistent server.
*
* Commands are serialized and queued; only one command runs at a time.
*
* @param args - The full command arguments (e.g. `['resolve', 'qlpacks']`).
* @returns The stdout output from the command.
*/
runCommand(args) {
return new Promise((resolve12, reject) => {
const execute = () => {
this.executeCommand({ args, reject, resolve: resolve12 });
};
if (this.commandInProgress) {
this.commandQueue.push(execute);
} else {
execute();
}
});
}
/**
* Gracefully shut down the CLI server.
*/
async shutdown() {
if (!this.process) {
return;
}
logger.info("Shutting down CodeQL CLI Server...");
try {
this.process.stdin?.write(JSON.stringify(["shutdown"]), "utf8");
this.process.stdin?.write(this.nullBuffer);
} catch (error) {
logger.warn("Error during CLI server shutdown request:", error);
}
await new Promise((resolve12) => {
const timer = setTimeout5(() => {
if (this.process) {
this.process.kill("SIGTERM");
this.process = null;
}
resolve12();
}, 2e3);