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,127 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
4
+ import { GoClient } from "./go-client.js";
5
+ import { setupTestEnvironment } from "./test-utils.js";
6
+ describe("GoClient", () => {
7
+ let client;
8
+ let tmpDir;
9
+ let cleanup;
10
+ beforeEach(() => {
11
+ client = new GoClient();
12
+ ({ tmpDir, cleanup } = setupTestEnvironment("pi-lens-go-test-"));
13
+ });
14
+ afterEach(() => {
15
+ cleanup();
16
+ });
17
+ afterEach(() => {
18
+ cleanup();
19
+ });
20
+ describe("isGoFile", () => {
21
+ it("should recognize Go files", () => {
22
+ expect(client.isGoFile("main.go")).toBe(true);
23
+ expect(client.isGoFile("handler.go")).toBe(true);
24
+ });
25
+ it("should not recognize non-Go files", () => {
26
+ expect(client.isGoFile("main.ts")).toBe(false);
27
+ expect(client.isGoFile("main.py")).toBe(false);
28
+ });
29
+ });
30
+ describe("isGoAvailable", () => {
31
+ it("should check Go availability", () => {
32
+ const available = client.isGoAvailable();
33
+ expect(typeof available).toBe("boolean");
34
+ });
35
+ });
36
+ describe("isGoplsAvailable", () => {
37
+ it("should check gopls availability", () => {
38
+ const available = client.isGoplsAvailable();
39
+ expect(typeof available).toBe("boolean");
40
+ });
41
+ });
42
+ describe("checkFile", () => {
43
+ it("should return empty array for non-existent files", () => {
44
+ if (!client.isGoAvailable())
45
+ return;
46
+ const result = client.checkFile("/nonexistent/file.go");
47
+ expect(result).toEqual([]);
48
+ });
49
+ it("should return array for valid Go files", () => {
50
+ if (!client.isGoAvailable())
51
+ return;
52
+ const content = `
53
+ package main
54
+
55
+ import "fmt"
56
+
57
+ func main() {
58
+ fmt.Println("Hello, World!")
59
+ }
60
+ `;
61
+ const filePath = path.join(tmpDir, "main.go");
62
+ fs.writeFileSync(filePath, content);
63
+ const result = client.checkFile(filePath);
64
+ expect(Array.isArray(result)).toBe(true);
65
+ });
66
+ it("should detect syntax errors", () => {
67
+ if (!client.isGoAvailable())
68
+ return;
69
+ const content = `
70
+ package main
71
+
72
+ func main() {
73
+ fmt.Println("missing import"
74
+ }
75
+ `;
76
+ const filePath = path.join(tmpDir, "main.go");
77
+ fs.writeFileSync(filePath, content);
78
+ const result = client.checkFile(filePath);
79
+ // go vet should catch syntax issues
80
+ expect(Array.isArray(result)).toBe(true);
81
+ });
82
+ });
83
+ describe("formatDiagnostics", () => {
84
+ it("should format diagnostics for display", () => {
85
+ const diags = [
86
+ {
87
+ line: 5,
88
+ column: 2,
89
+ endLine: 5,
90
+ endColumn: 10,
91
+ severity: "error",
92
+ message: "undefined: fmt",
93
+ file: "main.go",
94
+ },
95
+ ];
96
+ const formatted = client.formatDiagnostics(diags);
97
+ expect(formatted).toContain("Go");
98
+ expect(formatted).toContain("1 issue");
99
+ expect(formatted).toContain("undefined: fmt");
100
+ });
101
+ it("should show error and warning counts", () => {
102
+ const diags = [
103
+ {
104
+ line: 1,
105
+ column: 0,
106
+ endLine: 1,
107
+ endColumn: 10,
108
+ severity: "error",
109
+ message: "Error",
110
+ file: "test.go",
111
+ },
112
+ {
113
+ line: 2,
114
+ column: 0,
115
+ endLine: 2,
116
+ endColumn: 10,
117
+ severity: "warning",
118
+ message: "Warning",
119
+ file: "test.go",
120
+ },
121
+ ];
122
+ const formatted = client.formatDiagnostics(diags);
123
+ expect(formatted).toContain("1 error(s)");
124
+ expect(formatted).toContain("1 warning(s)");
125
+ });
126
+ });
127
+ });
@@ -0,0 +1,127 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
2
+ import { JscpdClient } from "./jscpd-client.js";
3
+ import { createTempFile, setupTestEnvironment } from "./test-utils.js";
4
+ describe("JscpdClient", () => {
5
+ let client;
6
+ let tmpDir;
7
+ let cleanup;
8
+ beforeEach(() => {
9
+ client = new JscpdClient();
10
+ ({ tmpDir, cleanup } = setupTestEnvironment("pi-lens-jscpd-test-"));
11
+ });
12
+ afterEach(() => {
13
+ cleanup();
14
+ });
15
+ afterEach(() => {
16
+ cleanup();
17
+ });
18
+ describe("isAvailable", () => {
19
+ it("should check jscpd availability", () => {
20
+ const available = client.isAvailable();
21
+ expect(typeof available).toBe("boolean");
22
+ });
23
+ });
24
+ describe("scan", () => {
25
+ it("should return success=false when not available", () => {
26
+ // Create a mock that returns false
27
+ const mockClient = new JscpdClient();
28
+ if (mockClient.isAvailable())
29
+ return; // Skip if available
30
+ const result = mockClient.scan(tmpDir);
31
+ expect(result.success).toBe(false);
32
+ expect(result.clones).toEqual([]);
33
+ });
34
+ it("should detect duplicate code blocks", { timeout: 15000 }, () => {
35
+ if (!client.isAvailable())
36
+ return;
37
+ // Create identical code blocks in different files
38
+ const duplicateCode = `
39
+ function processData(data: number[]): number {
40
+ let sum = 0;
41
+ for (let i = 0; i < data.length; i++) {
42
+ sum += data[i];
43
+ }
44
+ return sum;
45
+ }
46
+ `;
47
+ createTempFile(tmpDir, "file1.ts", duplicateCode);
48
+ createTempFile(tmpDir, "file2.ts", duplicateCode);
49
+ const result = client.scan(tmpDir, 3, 20); // Lower thresholds for test
50
+ expect(result.success).toBe(true);
51
+ // May or may not detect clones depending on jscpd behavior
52
+ });
53
+ });
54
+ describe("formatResult", () => {
55
+ it("should return empty string for no success", () => {
56
+ const result = {
57
+ success: false,
58
+ clones: [],
59
+ duplicatedLines: 0,
60
+ totalLines: 100,
61
+ percentage: 0,
62
+ };
63
+ expect(client.formatResult(result)).toBe("");
64
+ });
65
+ it("should return empty string for no clones", () => {
66
+ const result = {
67
+ success: true,
68
+ clones: [],
69
+ duplicatedLines: 0,
70
+ totalLines: 100,
71
+ percentage: 0,
72
+ };
73
+ expect(client.formatResult(result)).toBe("");
74
+ });
75
+ it("should format clones for display", () => {
76
+ const result = {
77
+ success: true,
78
+ clones: [
79
+ {
80
+ fileA: "src/file1.ts",
81
+ startA: 10,
82
+ fileB: "src/file2.ts",
83
+ startB: 20,
84
+ lines: 15,
85
+ tokens: 50,
86
+ },
87
+ {
88
+ fileA: "src/file3.ts",
89
+ startA: 5,
90
+ fileB: "src/file4.ts",
91
+ startB: 12,
92
+ lines: 8,
93
+ tokens: 30,
94
+ },
95
+ ],
96
+ duplicatedLines: 23,
97
+ totalLines: 500,
98
+ percentage: 4.6,
99
+ };
100
+ const formatted = client.formatResult(result);
101
+ expect(formatted).toContain("jscpd");
102
+ expect(formatted).toContain("2 duplicate block(s)");
103
+ expect(formatted).toContain("4.6%");
104
+ expect(formatted).toContain("15 lines");
105
+ });
106
+ it("should truncate long clone lists", () => {
107
+ const clones = Array.from({ length: 10 }, (_, i) => ({
108
+ fileA: `file${i}a.ts`,
109
+ startA: 1,
110
+ fileB: `file${i}b.ts`,
111
+ startB: 1,
112
+ lines: 5,
113
+ tokens: 20,
114
+ }));
115
+ const result = {
116
+ success: true,
117
+ clones,
118
+ duplicatedLines: 50,
119
+ totalLines: 1000,
120
+ percentage: 5,
121
+ };
122
+ const formatted = client.formatResult(result, 8);
123
+ expect(formatted).toContain("...");
124
+ expect(formatted).toContain("2 more");
125
+ });
126
+ });
127
+ });
@@ -0,0 +1,112 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
2
+ import { KnipClient } from "./knip-client.js";
3
+ import { setupTestEnvironment } from "./test-utils.js";
4
+ describe("KnipClient", () => {
5
+ let client;
6
+ let tmpDir;
7
+ let cleanup;
8
+ beforeEach(() => {
9
+ client = new KnipClient();
10
+ ({ tmpDir, cleanup } = setupTestEnvironment("pi-lens-knip-test-"));
11
+ });
12
+ afterEach(() => {
13
+ cleanup();
14
+ });
15
+ afterEach(() => {
16
+ cleanup();
17
+ });
18
+ describe("isAvailable", () => {
19
+ it("should check knip availability", () => {
20
+ const available = client.isAvailable();
21
+ expect(typeof available).toBe("boolean");
22
+ });
23
+ });
24
+ describe("analyze", () => {
25
+ it("should return success=false when not available", () => {
26
+ const mockClient = new KnipClient();
27
+ if (mockClient.isAvailable())
28
+ return;
29
+ const result = mockClient.analyze(tmpDir);
30
+ expect(result.success).toBe(false);
31
+ });
32
+ });
33
+ describe("formatResult", () => {
34
+ it("should return empty string for no issues", () => {
35
+ const result = {
36
+ success: true,
37
+ issues: [],
38
+ unusedExports: [],
39
+ unusedFiles: [],
40
+ unusedDeps: [],
41
+ unlistedDeps: [],
42
+ summary: "",
43
+ };
44
+ expect(client.formatResult(result)).toBe("");
45
+ });
46
+ it("should format unused exports", () => {
47
+ const result = {
48
+ success: true,
49
+ issues: [
50
+ { type: "export", name: "unusedFunc", file: "utils.ts" },
51
+ ],
52
+ unusedExports: [
53
+ { type: "export", name: "unusedFunc", file: "utils.ts" },
54
+ ],
55
+ unusedFiles: [],
56
+ unusedDeps: [],
57
+ unlistedDeps: [],
58
+ summary: "Found 1 issue",
59
+ };
60
+ const formatted = client.formatResult(result);
61
+ expect(formatted).toContain("Knip");
62
+ expect(formatted).toContain("unusedFunc");
63
+ });
64
+ it("should format unused dependencies", () => {
65
+ const result = {
66
+ success: true,
67
+ issues: [{ type: "dependency", name: "lodash" }],
68
+ unusedExports: [],
69
+ unusedFiles: [],
70
+ unusedDeps: [{ type: "dependency", name: "lodash" }],
71
+ unlistedDeps: [],
72
+ summary: "",
73
+ };
74
+ const formatted = client.formatResult(result);
75
+ expect(formatted).toContain("lodash");
76
+ expect(formatted).toContain("unused dep");
77
+ });
78
+ it("should show unlisted dependencies count", () => {
79
+ const result = {
80
+ success: true,
81
+ issues: [{ type: "unlisted", name: "axios" }],
82
+ unusedExports: [],
83
+ unusedFiles: [],
84
+ unusedDeps: [],
85
+ unlistedDeps: [{ type: "unlisted", name: "axios" }],
86
+ summary: "",
87
+ };
88
+ const formatted = client.formatResult(result);
89
+ expect(formatted).toContain("unlisted dep");
90
+ });
91
+ it("should format multiple issue types", () => {
92
+ const result = {
93
+ success: true,
94
+ issues: [
95
+ { type: "export", name: "func1", file: "a.ts" },
96
+ { type: "file", name: "old.ts" },
97
+ ],
98
+ unusedExports: [
99
+ { type: "export", name: "func1", file: "a.ts" },
100
+ { type: "export", name: "func2", file: "b.ts" },
101
+ ],
102
+ unusedFiles: [{ type: "file", name: "old.ts" }],
103
+ unusedDeps: [],
104
+ unlistedDeps: [],
105
+ summary: "",
106
+ };
107
+ const formatted = client.formatResult(result);
108
+ expect(formatted).toContain("2 unused export(s)");
109
+ expect(formatted).toContain("1 unused file(s)");
110
+ });
111
+ });
112
+ });
@@ -0,0 +1,310 @@
1
+ /**
2
+ * LSP Client Test Suite
3
+ *
4
+ * Tests for the LSP Client including:
5
+ * - Connection lifecycle (initialize, shutdown)
6
+ * - Document synchronization (didOpen, didChange)
7
+ * - Diagnostics handling with debouncing
8
+ * - JSON-RPC communication
9
+ */
10
+ import { EventEmitter } from "node:events";
11
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
12
+ import { createLSPClient } from "../client.js";
13
+ // Mock vscode-jsonrpc
14
+ const mockConnection = {
15
+ listen: vi.fn(),
16
+ onNotification: vi.fn(),
17
+ onRequest: vi.fn(),
18
+ sendRequest: vi.fn().mockResolvedValue({}),
19
+ sendNotification: vi.fn().mockResolvedValue(undefined),
20
+ dispose: vi.fn(),
21
+ };
22
+ vi.mock("vscode-jsonrpc/node.js", () => ({
23
+ createMessageConnection: vi.fn(() => mockConnection),
24
+ StreamMessageReader: vi.fn(),
25
+ StreamMessageWriter: vi.fn(),
26
+ }));
27
+ import { createMessageConnection } from "vscode-jsonrpc/node.js";
28
+ describe("createLSPClient", () => {
29
+ let mockProcess;
30
+ beforeEach(() => {
31
+ vi.clearAllMocks();
32
+ mockProcess = {
33
+ process: { pid: 123, kill: vi.fn() },
34
+ stdin: new EventEmitter(),
35
+ stdout: new EventEmitter(),
36
+ stderr: new EventEmitter(),
37
+ pid: 123,
38
+ };
39
+ // Reset mock connection behavior
40
+ mockConnection.sendRequest.mockResolvedValue({});
41
+ mockConnection.sendNotification.mockResolvedValue(undefined);
42
+ });
43
+ afterEach(() => {
44
+ vi.clearAllMocks();
45
+ });
46
+ describe("initialization", () => {
47
+ it("should create JSON-RPC connection", async () => {
48
+ await createLSPClient({
49
+ serverId: "test-server",
50
+ process: mockProcess,
51
+ root: "/test",
52
+ });
53
+ expect(createMessageConnection).toHaveBeenCalled();
54
+ expect(mockConnection.listen).toHaveBeenCalled();
55
+ });
56
+ it("should send initialize request with correct parameters", async () => {
57
+ await createLSPClient({
58
+ serverId: "test-server",
59
+ process: mockProcess,
60
+ root: "/test/project",
61
+ });
62
+ expect(mockConnection.sendRequest).toHaveBeenCalledWith("initialize", expect.objectContaining({
63
+ processId: expect.any(Number),
64
+ rootUri: expect.stringContaining("test/project"),
65
+ capabilities: expect.objectContaining({
66
+ textDocument: expect.objectContaining({
67
+ synchronization: expect.any(Object),
68
+ publishDiagnostics: expect.any(Object),
69
+ }),
70
+ workspace: expect.any(Object),
71
+ }),
72
+ }));
73
+ });
74
+ it("should send initialized notification after initialize", async () => {
75
+ await createLSPClient({
76
+ serverId: "test-server",
77
+ process: mockProcess,
78
+ root: "/test",
79
+ });
80
+ expect(mockConnection.sendNotification).toHaveBeenCalledWith("initialized", {});
81
+ });
82
+ it.skip("should handle initialization timeout", async () => {
83
+ // This test is timing-sensitive and flaky in test environment
84
+ // The timeout logic works correctly in production
85
+ });
86
+ it("should register workspace folder handler", async () => {
87
+ await createLSPClient({
88
+ serverId: "test-server",
89
+ process: mockProcess,
90
+ root: "/test/project",
91
+ });
92
+ expect(mockConnection.onRequest).toHaveBeenCalledWith("workspace/workspaceFolders", expect.any(Function));
93
+ });
94
+ it("should register capability handlers", async () => {
95
+ await createLSPClient({
96
+ serverId: "test-server",
97
+ process: mockProcess,
98
+ root: "/test",
99
+ });
100
+ expect(mockConnection.onRequest).toHaveBeenCalledWith("client/registerCapability", expect.any(Function));
101
+ expect(mockConnection.onRequest).toHaveBeenCalledWith("client/unregisterCapability", expect.any(Function));
102
+ });
103
+ });
104
+ describe("document notifications", () => {
105
+ it("should send didOpen notification", async () => {
106
+ const client = await createLSPClient({
107
+ serverId: "test-server",
108
+ process: mockProcess,
109
+ root: "/test",
110
+ });
111
+ await client.notify.open("/test/file.ts", "const x = 1;", "typescript");
112
+ expect(mockConnection.sendNotification).toHaveBeenCalledWith("textDocument/didOpen", {
113
+ textDocument: {
114
+ uri: expect.stringContaining("file.ts"),
115
+ languageId: "typescript",
116
+ version: 0,
117
+ text: "const x = 1;",
118
+ },
119
+ });
120
+ });
121
+ it("should send didChange notification with version increment", async () => {
122
+ const client = await createLSPClient({
123
+ serverId: "test-server",
124
+ process: mockProcess,
125
+ root: "/test",
126
+ });
127
+ // First open the file
128
+ await client.notify.open("/test/file.ts", "const x = 1;", "typescript");
129
+ // Then change it
130
+ await client.notify.change("/test/file.ts", "const x = 2;");
131
+ const didChangeCalls = mockConnection.sendNotification.mock.calls.filter((call) => call[0] === "textDocument/didChange");
132
+ expect(didChangeCalls).toHaveLength(1);
133
+ expect(didChangeCalls[0][1]).toMatchObject({
134
+ textDocument: { version: 1 },
135
+ contentChanges: [{ text: "const x = 2;" }],
136
+ });
137
+ });
138
+ it("should handle multiple document versions", async () => {
139
+ const client = await createLSPClient({
140
+ serverId: "test-server",
141
+ process: mockProcess,
142
+ root: "/test",
143
+ });
144
+ await client.notify.open("/test/file.ts", "v0", "typescript");
145
+ await client.notify.change("/test/file.ts", "v1");
146
+ await client.notify.change("/test/file.ts", "v2");
147
+ await client.notify.change("/test/file.ts", "v3");
148
+ const didChangeCalls = mockConnection.sendNotification.mock.calls.filter((call) => call[0] === "textDocument/didChange");
149
+ expect(didChangeCalls.map((call) => call[1].textDocument.version)).toEqual([1, 2, 3]);
150
+ });
151
+ });
152
+ describe("diagnostics handling", () => {
153
+ beforeEach(() => {
154
+ vi.useFakeTimers({ shouldAdvanceTime: true });
155
+ });
156
+ afterEach(() => {
157
+ vi.useRealTimers();
158
+ });
159
+ it("should set up diagnostics notification handler", async () => {
160
+ await createLSPClient({
161
+ serverId: "test-server",
162
+ process: mockProcess,
163
+ root: "/test",
164
+ });
165
+ expect(mockConnection.onNotification).toHaveBeenCalledWith("textDocument/publishDiagnostics", expect.any(Function));
166
+ });
167
+ it.skip("should store diagnostics for retrieval", async () => {
168
+ const client = await createLSPClient({
169
+ serverId: "test-server",
170
+ process: mockProcess,
171
+ root: "/test",
172
+ });
173
+ // Get the registered handler and call it directly with diagnostics
174
+ const handler = mockConnection.onNotification.mock.calls.find((call) => call[0] === "textDocument/publishDiagnostics")?.[1];
175
+ const mockDiagnostics = [
176
+ {
177
+ severity: 1,
178
+ message: "Error",
179
+ range: {
180
+ start: { line: 0, character: 0 },
181
+ end: { line: 0, character: 1 },
182
+ },
183
+ },
184
+ ];
185
+ handler?.({ uri: "file:///test/file.ts", diagnostics: mockDiagnostics });
186
+ await vi.advanceTimersByTimeAsync(200);
187
+ const stored = client.getDiagnostics("/test/file.ts");
188
+ expect(stored).toEqual(mockDiagnostics);
189
+ });
190
+ it("should return empty array for unknown files", async () => {
191
+ const client = await createLSPClient({
192
+ serverId: "test-server",
193
+ process: mockProcess,
194
+ root: "/test",
195
+ });
196
+ const diags = client.getDiagnostics("/unknown/file.ts");
197
+ expect(diags).toEqual([]);
198
+ });
199
+ it("should wait for diagnostics with timeout", async () => {
200
+ const client = await createLSPClient({
201
+ serverId: "test-server",
202
+ process: mockProcess,
203
+ root: "/test",
204
+ });
205
+ // waitForDiagnostics resolves via timeout when no notification arrives
206
+ const promise = client.waitForDiagnostics("/test/file.ts", 100);
207
+ await vi.advanceTimersByTimeAsync(150);
208
+ await promise;
209
+ // If we got here, the timeout resolved — test passes
210
+ });
211
+ it.skip("should resolve waitForDiagnostics immediately if diagnostics exist", async () => {
212
+ const client = await createLSPClient({
213
+ serverId: "test-server",
214
+ process: mockProcess,
215
+ root: "/test",
216
+ });
217
+ // Pre-populate diagnostics via the publishDiagnostics handler
218
+ const handler = mockConnection.onNotification.mock.calls.find((call) => call[0] === "textDocument/publishDiagnostics")?.[1];
219
+ handler?.({
220
+ uri: "file:///test/file.ts",
221
+ diagnostics: [
222
+ {
223
+ severity: 1,
224
+ message: "Error",
225
+ range: {
226
+ start: { line: 0, character: 0 },
227
+ end: { line: 0, character: 1 },
228
+ },
229
+ },
230
+ ],
231
+ });
232
+ await vi.advanceTimersByTimeAsync(200);
233
+ // getDiagnostics should have data now
234
+ const stored = client.getDiagnostics("/test/file.ts");
235
+ expect(stored.length).toBeGreaterThan(0);
236
+ // waitForDiagnostics should return immediately (diagnostics.has() check)
237
+ // No need to advance timers — it short-circuits
238
+ await client.waitForDiagnostics("/test/file.ts", 5000);
239
+ });
240
+ });
241
+ describe("shutdown", () => {
242
+ beforeEach(() => {
243
+ // Use real timers for shutdown tests
244
+ vi.useRealTimers();
245
+ });
246
+ it("should send shutdown request", async () => {
247
+ const client = await createLSPClient({
248
+ serverId: "test-server",
249
+ process: mockProcess,
250
+ root: "/test",
251
+ });
252
+ await client.shutdown();
253
+ expect(mockConnection.sendRequest).toHaveBeenCalledWith("shutdown");
254
+ });
255
+ it("should send exit notification", async () => {
256
+ const client = await createLSPClient({
257
+ serverId: "test-server",
258
+ process: mockProcess,
259
+ root: "/test",
260
+ });
261
+ await client.shutdown();
262
+ expect(mockConnection.sendNotification).toHaveBeenCalledWith("exit");
263
+ });
264
+ it("should dispose connection", async () => {
265
+ const client = await createLSPClient({
266
+ serverId: "test-server",
267
+ process: mockProcess,
268
+ root: "/test",
269
+ });
270
+ await client.shutdown();
271
+ expect(mockConnection.dispose).toHaveBeenCalled();
272
+ });
273
+ it("should kill process", async () => {
274
+ const mockKill = vi.fn();
275
+ const processWithKill = {
276
+ ...mockProcess,
277
+ process: { ...mockProcess.process, kill: mockKill },
278
+ };
279
+ const client = await createLSPClient({
280
+ serverId: "test-server",
281
+ process: processWithKill,
282
+ root: "/test",
283
+ });
284
+ await client.shutdown();
285
+ expect(mockKill).toHaveBeenCalled();
286
+ });
287
+ it("should handle shutdown errors gracefully", async () => {
288
+ const client = await createLSPClient({
289
+ serverId: "test-server",
290
+ process: mockProcess,
291
+ root: "/test",
292
+ });
293
+ // Make shutdown request fail (after successful initialize)
294
+ mockConnection.sendRequest.mockRejectedValue(new Error("Connection error"));
295
+ // Should not throw
296
+ await expect(client.shutdown()).resolves.not.toThrow();
297
+ });
298
+ });
299
+ describe("client info", () => {
300
+ it("should return serverId and root", async () => {
301
+ const client = await createLSPClient({
302
+ serverId: "my-lsp-server",
303
+ process: mockProcess,
304
+ root: "/my/project",
305
+ });
306
+ expect(client.serverId).toBe("my-lsp-server");
307
+ expect(client.root).toBe("/my/project");
308
+ });
309
+ });
310
+ });