pi-lens 3.2.0 → 3.3.1

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 (77) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -10
  3. package/clients/__tests__/file-time.test.js +216 -0
  4. package/clients/__tests__/format-service.test.js +245 -0
  5. package/clients/__tests__/formatters.test.js +271 -0
  6. package/clients/agent-behavior-client.test.js +94 -0
  7. package/clients/biome-client.test.js +144 -0
  8. package/clients/cache-manager.test.js +197 -0
  9. package/clients/complexity-client.test.js +234 -0
  10. package/clients/dependency-checker.test.js +60 -0
  11. package/clients/dispatch/__tests__/autofix-integration.test.js +245 -0
  12. package/clients/dispatch/__tests__/runner-registration.test.js +234 -0
  13. package/clients/dispatch/__tests__/runner-registration.test.ts +2 -2
  14. package/clients/dispatch/dispatcher.edge.test.js +82 -0
  15. package/clients/dispatch/dispatcher.format.test.js +46 -0
  16. package/clients/dispatch/dispatcher.inline.test.js +74 -0
  17. package/clients/dispatch/dispatcher.test.js +116 -0
  18. package/clients/dispatch/runners/architect.test.js +138 -0
  19. package/clients/dispatch/runners/ast-grep-napi.test.js +106 -0
  20. package/clients/dispatch/runners/lsp.js +42 -5
  21. package/clients/dispatch/runners/oxlint.test.js +230 -0
  22. package/clients/dispatch/runners/pyright.test.js +98 -0
  23. package/clients/dispatch/runners/python-slop.test.js +203 -0
  24. package/clients/dispatch/runners/scan_codebase.test.js +89 -0
  25. package/clients/dispatch/runners/shellcheck.test.js +98 -0
  26. package/clients/dispatch/runners/spellcheck.test.js +158 -0
  27. package/clients/dispatch/utils/format-utils.js +1 -6
  28. package/clients/dispatch/utils/format-utils.ts +1 -6
  29. package/clients/dogfood.test.js +201 -0
  30. package/clients/file-kinds.test.js +169 -0
  31. package/clients/formatters.js +1 -1
  32. package/clients/go-client.test.js +127 -0
  33. package/clients/jscpd-client.test.js +127 -0
  34. package/clients/knip-client.test.js +112 -0
  35. package/clients/lsp/__tests__/client.test.js +310 -0
  36. package/clients/lsp/__tests__/client.test.ts +1 -46
  37. package/clients/lsp/__tests__/config.test.js +167 -0
  38. package/clients/lsp/__tests__/error-recovery.test.js +213 -0
  39. package/clients/lsp/__tests__/integration.test.js +127 -0
  40. package/clients/lsp/__tests__/launch.test.js +313 -0
  41. package/clients/lsp/__tests__/server.test.js +259 -0
  42. package/clients/lsp/__tests__/service.test.js +435 -0
  43. package/clients/lsp/client.js +32 -44
  44. package/clients/lsp/client.ts +36 -45
  45. package/clients/lsp/launch.js +11 -6
  46. package/clients/lsp/launch.ts +11 -6
  47. package/clients/lsp/server.js +27 -2
  48. package/clients/metrics-client.test.js +141 -0
  49. package/clients/ruff-client.test.js +132 -0
  50. package/clients/rust-client.test.js +108 -0
  51. package/clients/sanitize.test.js +177 -0
  52. package/clients/secrets-scanner.test.js +100 -0
  53. package/clients/test-runner-client.test.js +192 -0
  54. package/clients/todo-scanner.test.js +301 -0
  55. package/clients/type-coverage-client.test.js +105 -0
  56. package/clients/typescript-client.codefix.test.js +157 -0
  57. package/clients/typescript-client.test.js +105 -0
  58. package/commands/rate.test.js +119 -0
  59. package/index.ts +66 -72
  60. package/package.json +1 -1
  61. package/clients/bus/bus.js +0 -191
  62. package/clients/bus/bus.ts +0 -251
  63. package/clients/bus/events.js +0 -214
  64. package/clients/bus/events.ts +0 -279
  65. package/clients/bus/index.js +0 -8
  66. package/clients/bus/index.ts +0 -9
  67. package/clients/bus/integration.js +0 -158
  68. package/clients/bus/integration.ts +0 -227
  69. package/clients/dispatch/bus-dispatcher.js +0 -178
  70. package/clients/dispatch/bus-dispatcher.ts +0 -258
  71. package/clients/services/__tests__/effect-integration.test.ts +0 -111
  72. package/clients/services/effect-integration.js +0 -198
  73. package/clients/services/effect-integration.ts +0 -276
  74. package/clients/services/index.js +0 -7
  75. package/clients/services/index.ts +0 -8
  76. package/clients/services/runner-service.js +0 -134
  77. package/clients/services/runner-service.ts +0 -225
@@ -0,0 +1,435 @@
1
+ /**
2
+ * LSP Service Test Suite
3
+ *
4
+ * Tests for the LSP Service layer including:
5
+ * - Client lifecycle management
6
+ * - Effect-TS integration
7
+ * - File operations (open/update/getDiagnostics)
8
+ * - Server availability checking
9
+ * - Cleanup and shutdown
10
+ */
11
+ import { Effect } from "effect";
12
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
13
+ import { getLSPService, LSPService, lspEffect, resetLSPService, } from "../index.js";
14
+ // Mock the dependencies
15
+ vi.mock("../server.js", async () => {
16
+ const actual = await vi.importActual("../server.js");
17
+ return {
18
+ ...actual,
19
+ getServersForFileWithConfig: vi.fn(),
20
+ };
21
+ });
22
+ vi.mock("../config.js", () => ({
23
+ initLSPConfig: vi.fn(),
24
+ getServersForFileWithConfig: vi.fn(),
25
+ }));
26
+ vi.mock("../language.js", () => ({
27
+ getLanguageId: vi.fn(() => "typescript"),
28
+ }));
29
+ vi.mock("../launch.js", () => ({
30
+ launchLSP: vi.fn(),
31
+ }));
32
+ vi.mock("../client.js", () => ({
33
+ createLSPClient: vi.fn(),
34
+ }));
35
+ import { createLSPClient as mockCreateLSPClient } from "../client.js";
36
+ import { getServersForFileWithConfig as mockGetServersForFile } from "../config.js";
37
+ describe("LSPService", () => {
38
+ let service;
39
+ beforeEach(() => {
40
+ resetLSPService();
41
+ service = getLSPService();
42
+ vi.clearAllMocks();
43
+ });
44
+ afterEach(async () => {
45
+ await service.shutdown();
46
+ resetLSPService();
47
+ });
48
+ describe("constructor", () => {
49
+ it("should initialize with empty state", () => {
50
+ const status = service.getStatus();
51
+ expect(status).toEqual([]);
52
+ });
53
+ it("should create fresh LSPState", () => {
54
+ // Verify service was created with initial state
55
+ expect(service).toBeDefined();
56
+ expect(service).toBeInstanceOf(LSPService);
57
+ });
58
+ });
59
+ describe("hasLSP", () => {
60
+ it("should return false when no servers match file extension", async () => {
61
+ vi.mocked(mockGetServersForFile).mockReturnValue([]);
62
+ const result = await service.hasLSP("/test/file.unknown");
63
+ expect(result).toBe(false);
64
+ });
65
+ it("should return true when server matches and provides root", async () => {
66
+ const mockServer = {
67
+ id: "typescript",
68
+ name: "TypeScript Server",
69
+ extensions: [".ts"],
70
+ root: vi.fn().mockResolvedValue("/project"),
71
+ spawn: vi.fn(),
72
+ };
73
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
74
+ const result = await service.hasLSP("/project/test.ts");
75
+ expect(result).toBe(true);
76
+ });
77
+ it("should return false when server cannot determine root", async () => {
78
+ const mockServer = {
79
+ id: "typescript",
80
+ name: "TypeScript Server",
81
+ extensions: [".ts"],
82
+ root: vi.fn().mockResolvedValue(undefined),
83
+ spawn: vi.fn(),
84
+ };
85
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
86
+ const result = await service.hasLSP("/project/test.ts");
87
+ expect(result).toBe(false);
88
+ });
89
+ it("should check all matching servers until root is found", async () => {
90
+ const server1 = {
91
+ id: "server1",
92
+ name: "Server 1",
93
+ extensions: [".ts"],
94
+ root: vi.fn().mockResolvedValue(undefined),
95
+ spawn: vi.fn(),
96
+ };
97
+ const server2 = {
98
+ id: "server2",
99
+ name: "Server 2",
100
+ extensions: [".ts"],
101
+ root: vi.fn().mockResolvedValue("/project"),
102
+ spawn: vi.fn(),
103
+ };
104
+ vi.mocked(mockGetServersForFile).mockReturnValue([server1, server2]);
105
+ const result = await service.hasLSP("/project/test.ts");
106
+ expect(result).toBe(true);
107
+ expect(server1.root).toHaveBeenCalled();
108
+ expect(server2.root).toHaveBeenCalled();
109
+ });
110
+ });
111
+ describe("getClientForFile", () => {
112
+ it("should return undefined when no servers match", async () => {
113
+ vi.mocked(mockGetServersForFile).mockReturnValue([]);
114
+ const result = await service.getClientForFile("/test/file.unknown");
115
+ expect(result).toBeUndefined();
116
+ });
117
+ it("should cache and reuse existing client", async () => {
118
+ const mockClient = createMockClient();
119
+ const mockServer = {
120
+ id: "typescript",
121
+ name: "TypeScript Server",
122
+ extensions: [".ts"],
123
+ root: vi.fn().mockResolvedValue("/project"),
124
+ spawn: vi.fn().mockResolvedValue({
125
+ process: { pid: 123 },
126
+ }),
127
+ };
128
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
129
+ vi.mocked(mockCreateLSPClient).mockResolvedValue(mockClient);
130
+ // First call creates client
131
+ const result1 = await service.getClientForFile("/project/test.ts");
132
+ expect(result1).toBeDefined();
133
+ expect(mockCreateLSPClient).toHaveBeenCalledTimes(1);
134
+ // Second call returns cached client
135
+ const result2 = await service.getClientForFile("/project/other.ts");
136
+ expect(result2?.client).toBe(result1?.client);
137
+ expect(mockCreateLSPClient).toHaveBeenCalledTimes(1); // Not called again
138
+ });
139
+ it("should handle server spawn failure", async () => {
140
+ const mockSpawn = vi.fn().mockRejectedValue(new Error("Spawn failed"));
141
+ const mockServer = {
142
+ id: "typescript",
143
+ name: "TypeScript Server",
144
+ extensions: [".ts"],
145
+ root: vi.fn().mockResolvedValue("/project"),
146
+ spawn: mockSpawn,
147
+ };
148
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
149
+ const result = await service.getClientForFile("/project/test.ts");
150
+ expect(result).toBeUndefined();
151
+ });
152
+ it("should try next server when first fails", async () => {
153
+ const mockClient = createMockClient();
154
+ const failingServer = {
155
+ id: "server1",
156
+ name: "Failing Server",
157
+ extensions: [".ts"],
158
+ root: vi.fn().mockResolvedValue("/project"),
159
+ spawn: vi.fn().mockRejectedValue(new Error("Spawn failed")),
160
+ };
161
+ const workingServer = {
162
+ id: "server2",
163
+ name: "Working Server",
164
+ extensions: [".ts"],
165
+ root: vi.fn().mockResolvedValue("/project"),
166
+ spawn: vi.fn().mockResolvedValue({
167
+ process: { pid: 456 },
168
+ }),
169
+ };
170
+ vi.mocked(mockGetServersForFile).mockReturnValue([
171
+ failingServer,
172
+ workingServer,
173
+ ]);
174
+ vi.mocked(mockCreateLSPClient).mockResolvedValue(mockClient);
175
+ const result = await service.getClientForFile("/project/test.ts");
176
+ expect(result).toBeDefined();
177
+ expect(result?.info.id).toBe("server2");
178
+ });
179
+ });
180
+ describe("openFile", () => {
181
+ it("should send didOpen notification with correct parameters", async () => {
182
+ const mockClient = createMockClient();
183
+ const mockServer = {
184
+ id: "typescript",
185
+ name: "TypeScript Server",
186
+ extensions: [".ts"],
187
+ root: vi.fn().mockResolvedValue("/project"),
188
+ spawn: vi.fn().mockResolvedValue({
189
+ process: { pid: 123 },
190
+ }),
191
+ };
192
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
193
+ vi.mocked(mockCreateLSPClient).mockResolvedValue(mockClient);
194
+ await service.openFile("/project/test.ts", "const x = 1;");
195
+ expect(mockClient.notify.open).toHaveBeenCalledWith("/project/test.ts", "const x = 1;", "typescript");
196
+ });
197
+ it("should do nothing when no LSP available", async () => {
198
+ vi.mocked(mockGetServersForFile).mockReturnValue([]);
199
+ // Should not throw
200
+ await expect(service.openFile("/test.unknown", "content")).resolves.not.toThrow();
201
+ });
202
+ });
203
+ describe("updateFile", () => {
204
+ it("should send didChange notification", async () => {
205
+ const mockClient = createMockClient();
206
+ const mockServer = {
207
+ id: "typescript",
208
+ name: "TypeScript Server",
209
+ extensions: [".ts"],
210
+ root: vi.fn().mockResolvedValue("/project"),
211
+ spawn: vi.fn().mockResolvedValue({
212
+ process: { pid: 123 },
213
+ }),
214
+ };
215
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
216
+ vi.mocked(mockCreateLSPClient).mockResolvedValue(mockClient);
217
+ await service.updateFile("/project/test.ts", "const x = 2;");
218
+ expect(mockClient.notify.change).toHaveBeenCalledWith("/project/test.ts", "const x = 2;");
219
+ });
220
+ });
221
+ describe("getDiagnostics", () => {
222
+ it("should return diagnostics from client", async () => {
223
+ const mockDiagnostics = [
224
+ {
225
+ severity: 1,
226
+ message: "Type error",
227
+ range: {
228
+ start: { line: 0, character: 0 },
229
+ end: { line: 0, character: 5 },
230
+ },
231
+ },
232
+ ];
233
+ const mockClient = createMockClient(mockDiagnostics);
234
+ const mockServer = {
235
+ id: "typescript",
236
+ name: "TypeScript Server",
237
+ extensions: [".ts"],
238
+ root: vi.fn().mockResolvedValue("/project"),
239
+ spawn: vi.fn().mockResolvedValue({
240
+ process: { pid: 123 },
241
+ }),
242
+ };
243
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
244
+ vi.mocked(mockCreateLSPClient).mockResolvedValue(mockClient);
245
+ const result = await service.getDiagnostics("/project/test.ts");
246
+ expect(result).toEqual(mockDiagnostics);
247
+ expect(mockClient.waitForDiagnostics).toHaveBeenCalled();
248
+ });
249
+ it("should return empty array when no LSP available", async () => {
250
+ vi.mocked(mockGetServersForFile).mockReturnValue([]);
251
+ const result = await service.getDiagnostics("/test.unknown");
252
+ expect(result).toEqual([]);
253
+ });
254
+ });
255
+ describe("shutdown", () => {
256
+ it("should shutdown all clients", async () => {
257
+ const mockClient1 = createMockClient();
258
+ const mockClient2 = createMockClient();
259
+ // Add clients to service
260
+ const mockServer1 = {
261
+ id: "typescript",
262
+ name: "TypeScript Server",
263
+ extensions: [".ts"],
264
+ root: vi.fn().mockResolvedValue("/project1"),
265
+ spawn: vi.fn().mockResolvedValue({ process: { pid: 1 } }),
266
+ };
267
+ const mockServer2 = {
268
+ id: "python",
269
+ name: "Python Server",
270
+ extensions: [".py"],
271
+ root: vi.fn().mockResolvedValue("/project2"),
272
+ spawn: vi.fn().mockResolvedValue({ process: { pid: 2 } }),
273
+ };
274
+ vi.mocked(mockGetServersForFile)
275
+ .mockReturnValueOnce([mockServer1])
276
+ .mockReturnValueOnce([mockServer2]);
277
+ vi.mocked(mockCreateLSPClient)
278
+ .mockResolvedValueOnce(mockClient1)
279
+ .mockResolvedValueOnce(mockClient2);
280
+ // Create clients
281
+ await service.getClientForFile("/project1/test.ts");
282
+ await service.getClientForFile("/project2/test.py");
283
+ await service.shutdown();
284
+ expect(mockClient1.shutdown).toHaveBeenCalled();
285
+ expect(mockClient2.shutdown).toHaveBeenCalled();
286
+ });
287
+ it("should handle shutdown errors gracefully", async () => {
288
+ const mockClient = createMockClient();
289
+ mockClient.shutdown.mockRejectedValue(new Error("Shutdown failed"));
290
+ const mockServer = {
291
+ id: "typescript",
292
+ name: "TypeScript Server",
293
+ extensions: [".ts"],
294
+ root: vi.fn().mockResolvedValue("/project"),
295
+ spawn: vi.fn().mockResolvedValue({ process: { pid: 123 } }),
296
+ };
297
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
298
+ vi.mocked(mockCreateLSPClient).mockResolvedValue(mockClient);
299
+ await service.getClientForFile("/project/test.ts");
300
+ // Should not throw even when client shutdown fails
301
+ await expect(service.shutdown()).resolves.not.toThrow();
302
+ });
303
+ });
304
+ describe("getStatus", () => {
305
+ it("should return status of all active clients", async () => {
306
+ const mockClient = createMockClient();
307
+ const mockServer = {
308
+ id: "typescript",
309
+ name: "TypeScript Server",
310
+ extensions: [".ts"],
311
+ root: vi.fn().mockResolvedValue("/project"),
312
+ spawn: vi.fn().mockResolvedValue({ process: { pid: 123 } }),
313
+ };
314
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
315
+ vi.mocked(mockCreateLSPClient).mockResolvedValue(mockClient);
316
+ await service.getClientForFile("/project/test.ts");
317
+ const status = service.getStatus();
318
+ expect(status).toHaveLength(1);
319
+ expect(status[0]).toEqual({
320
+ serverId: "typescript",
321
+ root: "/project",
322
+ connected: true,
323
+ });
324
+ });
325
+ });
326
+ });
327
+ describe("lspEffect", () => {
328
+ let service;
329
+ let effect;
330
+ beforeEach(() => {
331
+ resetLSPService();
332
+ service = getLSPService();
333
+ effect = lspEffect(service);
334
+ vi.clearAllMocks();
335
+ });
336
+ afterEach(async () => {
337
+ await service.shutdown();
338
+ resetLSPService();
339
+ });
340
+ describe("openFile Effect", () => {
341
+ it("should wrap openFile in Effect", async () => {
342
+ const mockClient = createMockClient();
343
+ const mockServer = {
344
+ id: "typescript",
345
+ name: "TypeScript Server",
346
+ extensions: [".ts"],
347
+ root: vi.fn().mockResolvedValue("/project"),
348
+ spawn: vi.fn().mockResolvedValue({ process: { pid: 123 } }),
349
+ };
350
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
351
+ vi.mocked(mockCreateLSPClient).mockResolvedValue(mockClient);
352
+ const program = effect.openFile("/project/test.ts", "content");
353
+ const result = await Effect.runPromise(program);
354
+ expect(result).toBeUndefined();
355
+ expect(mockClient.notify.open).toHaveBeenCalled();
356
+ });
357
+ it("should handle errors in Effect", async () => {
358
+ vi.mocked(mockGetServersForFile).mockReturnValue([]);
359
+ const program = effect.openFile("/test.unknown", "content");
360
+ // Should complete successfully (no-op for unknown files)
361
+ await expect(Effect.runPromise(program)).resolves.not.toThrow();
362
+ });
363
+ });
364
+ describe("getDiagnostics Effect", () => {
365
+ it("should wrap getDiagnostics in Effect", async () => {
366
+ const mockDiagnostics = [
367
+ {
368
+ severity: 1,
369
+ message: "Error",
370
+ range: {
371
+ start: { line: 0, character: 0 },
372
+ end: { line: 0, character: 1 },
373
+ },
374
+ },
375
+ ];
376
+ const mockClient = createMockClient(mockDiagnostics);
377
+ const mockServer = {
378
+ id: "typescript",
379
+ name: "TypeScript Server",
380
+ extensions: [".ts"],
381
+ root: vi.fn().mockResolvedValue("/project"),
382
+ spawn: vi.fn().mockResolvedValue({ process: { pid: 123 } }),
383
+ };
384
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
385
+ vi.mocked(mockCreateLSPClient).mockResolvedValue(mockClient);
386
+ const program = effect.getDiagnostics("/project/test.ts");
387
+ const result = await Effect.runPromise(program);
388
+ expect(result).toEqual(mockDiagnostics);
389
+ });
390
+ });
391
+ describe("hasLSP Effect", () => {
392
+ it("should wrap hasLSP in Effect", async () => {
393
+ const mockServer = {
394
+ id: "typescript",
395
+ name: "TypeScript Server",
396
+ extensions: [".ts"],
397
+ root: vi.fn().mockResolvedValue("/project"),
398
+ spawn: vi.fn(),
399
+ };
400
+ vi.mocked(mockGetServersForFile).mockReturnValue([mockServer]);
401
+ const program = effect.hasLSP("/project/test.ts");
402
+ const result = await Effect.runPromise(program);
403
+ expect(result).toBe(true);
404
+ });
405
+ });
406
+ describe("shutdown Effect", () => {
407
+ it("should wrap shutdown in Effect", async () => {
408
+ const program = effect.shutdown();
409
+ const result = await Effect.runPromise(program);
410
+ expect(result).toBeUndefined();
411
+ });
412
+ });
413
+ });
414
+ // Helper function to create mock client
415
+ function createMockClient(diagnostics = []) {
416
+ return {
417
+ serverId: "test-server",
418
+ root: "/test",
419
+ connection: {},
420
+ notify: {
421
+ open: vi.fn().mockResolvedValue(undefined),
422
+ change: vi.fn().mockResolvedValue(undefined),
423
+ },
424
+ getDiagnostics: vi.fn().mockReturnValue(diagnostics),
425
+ getAllDiagnostics: vi.fn().mockReturnValue(new Map()),
426
+ waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
427
+ definition: vi.fn().mockResolvedValue([]),
428
+ references: vi.fn().mockResolvedValue([]),
429
+ hover: vi.fn().mockResolvedValue(null),
430
+ documentSymbol: vi.fn().mockResolvedValue([]),
431
+ workspaceSymbol: vi.fn().mockResolvedValue([]),
432
+ implementation: vi.fn().mockResolvedValue([]),
433
+ shutdown: vi.fn().mockResolvedValue(undefined),
434
+ };
435
+ }
@@ -7,12 +7,12 @@
7
7
  * - Diagnostics with debouncing
8
8
  * - Request/response handling
9
9
  */
10
+ import { EventEmitter } from "node:events";
10
11
  import { pathToFileURL } from "node:url";
11
12
  import { createMessageConnection, StreamMessageReader, StreamMessageWriter, } from "vscode-jsonrpc/node.js";
12
- import { DiagnosticFound } from "../bus/events.js";
13
13
  import { normalizeMapKey, uriToPath } from "./path-utils.js";
14
14
  // --- Constants ---
15
- const DIAGNOSTICS_DEBOUNCE_MS = 150;
15
+ const DIAGNOSTICS_DEBOUNCE_MS = 150; // ms — waits for follow-up semantic diagnostics
16
16
  const INITIALIZE_TIMEOUT_MS = 120000; // 2 minutes (was 45s) - allows time for npx to download packages
17
17
  // --- Client Factory ---
18
18
  export async function createLSPClient(options) {
@@ -22,6 +22,11 @@ export async function createLSPClient(options) {
22
22
  // Track diagnostics per file
23
23
  const diagnostics = new Map();
24
24
  const pendingDiagnostics = new Map();
25
+ // Local event emitter — signals waitForDiagnostics when new diagnostics arrive.
26
+ // Scoped to this client instance; replaces global bus pub/sub.
27
+ // setMaxListeners guards against Node.js warning for concurrent waitForDiagnostics calls.
28
+ const diagnosticEmitter = new EventEmitter();
29
+ diagnosticEmitter.setMaxListeners(50);
25
30
  // Handle incoming diagnostics with debouncing
26
31
  connection.onNotification("textDocument/publishDiagnostics", (params) => {
27
32
  const filePath = uriToPath(params.uri);
@@ -33,28 +38,8 @@ export async function createLSPClient(options) {
33
38
  const timer = setTimeout(() => {
34
39
  diagnostics.set(filePath, newDiags);
35
40
  pendingDiagnostics.delete(filePath);
36
- // Publish to bus
37
- // Defensive: filter out malformed diagnostics that may lack range
38
- const validDiags = newDiags.filter((d) => d.range?.start?.line !== undefined);
39
- DiagnosticFound.publish({
40
- runnerId: serverId,
41
- filePath,
42
- diagnostics: validDiags.map((d) => ({
43
- id: `${serverId}:${d.code ?? "unknown"}:${d.range.start.line}`,
44
- message: d.message,
45
- filePath,
46
- line: d.range.start.line + 1,
47
- column: d.range.start.character + 1,
48
- severity: severityFromNumber(d.severity),
49
- semantic: d.severity === 1
50
- ? "blocking"
51
- : d.severity === 2
52
- ? "warning"
53
- : "silent",
54
- tool: serverId,
55
- })),
56
- durationMs: 0,
57
- });
41
+ // Signal any active waitForDiagnostics calls for this file.
42
+ diagnosticEmitter.emit("diagnostics", filePath);
58
43
  }, DIAGNOSTICS_DEBOUNCE_MS);
59
44
  pendingDiagnostics.set(filePath, timer);
60
45
  });
@@ -88,10 +73,7 @@ export async function createLSPClient(options) {
88
73
  workDoneProgress: true,
89
74
  },
90
75
  workspace: {
91
- workspaceFolders: {
92
- supported: true,
93
- changeNotifications: true,
94
- },
76
+ workspaceFolders: true, // Simple boolean for broader compatibility
95
77
  configuration: true,
96
78
  didChangeWatchedFiles: {
97
79
  dynamicRegistration: true,
@@ -171,29 +153,33 @@ export async function createLSPClient(options) {
171
153
  },
172
154
  async waitForDiagnostics(filePath, timeoutMs = 10000) {
173
155
  const normalizedPath = normalizeMapKey(filePath);
156
+ // Fast path: diagnostics already available
174
157
  if (diagnostics.has(normalizedPath))
175
158
  return;
176
- // Use bus subscription like OpenCode - more reliable than polling
177
159
  return new Promise((resolve) => {
178
160
  let debounceTimer;
179
- // Subscribe to diagnostic events from this server
180
- const unsub = DiagnosticFound.subscribe((event) => {
181
- if (event.properties.filePath === normalizedPath &&
182
- event.properties.runnerId === serverId) {
183
- // Debounce to allow LSP to send follow-up diagnostics (e.g., semantic after syntax)
184
- if (debounceTimer)
185
- clearTimeout(debounceTimer);
186
- debounceTimer = setTimeout(() => {
187
- unsub();
188
- clearTimeout(timeout);
189
- resolve();
190
- }, DIAGNOSTICS_DEBOUNCE_MS);
191
- }
192
- });
161
+ // Listen on the local emitter for this client's diagnostic notifications.
162
+ // No runnerId filter needed — this emitter is scoped to this client instance.
163
+ const onDiagnostics = (fp) => {
164
+ if (normalizeMapKey(fp) !== normalizedPath)
165
+ return;
166
+ // Debounce: reset on each event to catch follow-up semantic diagnostics
167
+ // (LSP often sends syntax diagnostics first, semantic ones shortly after).
168
+ if (debounceTimer)
169
+ clearTimeout(debounceTimer);
170
+ debounceTimer = setTimeout(() => {
171
+ diagnosticEmitter.off("diagnostics", onDiagnostics);
172
+ clearTimeout(timeout);
173
+ resolve();
174
+ }, DIAGNOSTICS_DEBOUNCE_MS);
175
+ };
176
+ diagnosticEmitter.on("diagnostics", onDiagnostics);
177
+ // Timeout fallback: resolve even if no diagnostics arrive
178
+ // (some files have no errors, or the server may be slow)
193
179
  const timeout = setTimeout(() => {
194
180
  if (debounceTimer)
195
181
  clearTimeout(debounceTimer);
196
- unsub();
182
+ diagnosticEmitter.off("diagnostics", onDiagnostics);
197
183
  resolve();
198
184
  }, timeoutMs);
199
185
  });
@@ -283,6 +269,8 @@ export async function createLSPClient(options) {
283
269
  clearTimeout(timer);
284
270
  }
285
271
  pendingDiagnostics.clear();
272
+ // Remove all diagnostic listeners (cancels any in-flight waitForDiagnostics)
273
+ diagnosticEmitter.removeAllListeners();
286
274
  // Graceful shutdown
287
275
  try {
288
276
  await connection.sendRequest("shutdown");