@pugi/cli 0.1.0-beta.3 → 0.1.0-beta.4

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.
@@ -1,631 +0,0 @@
1
- /**
2
- * LSP client wrapper — α7.7 Phase 1 (LSP tool + worktree + apply_patch).
3
- *
4
- * Wraps a Language Server Protocol server process (started locally via
5
- * stdio) behind a small async surface used by the LSP tools:
6
- *
7
- * - hover(file, line, col)
8
- * - definition(file, line, col)
9
- * - references(file, line, col)
10
- * - diagnostics(file)
11
- *
12
- * Why no `vscode-languageserver-protocol` dep:
13
- *
14
- * The α6.6+ posture for `apps/pugi-cli` keeps the dep tree intentionally
15
- * lean (zod, ink, react, undici, tar — that's most of it). Pulling
16
- * `vscode-languageserver-protocol` + transitive `vscode-jsonrpc` for
17
- * four operations would expand the install footprint disproportionately.
18
- * The LSP framing protocol (Content-Length headers + JSON-RPC bodies)
19
- * is documented in the LSP spec §3 and stable since 2017; we implement
20
- * the framer ourselves in ~80 LOC. Pulling in the official packages
21
- * later (when we add 20+ operations) stays an open option — every
22
- * public surface here mirrors the official type names so a future swap
23
- * is mechanical.
24
- *
25
- * Why we spawn `npx <server>` for stock languages:
26
- *
27
- * - typescript-language-server: `npx typescript-language-server --stdio`
28
- * - pyright: `pyright-langserver --stdio` (operator-installed)
29
- * - gopls: `gopls` (operator-installed via `go install`)
30
- * - rust-analyzer: `rust-analyzer` (operator-installed via `rustup`)
31
- *
32
- * `npx typescript-language-server` resolves the binary from the
33
- * workspace's `node_modules/.bin` first, then falls back to the global
34
- * npm cache. The other servers are operator-installed system binaries
35
- * (we run `which <name>` once at start and fail loud with
36
- * `lsp_unavailable` if absent — see `detectServer` below). This keeps
37
- * `pugi` install-time zero-deps for non-TS workspaces.
38
- *
39
- * Lifecycle contract:
40
- *
41
- * 1. `startLspClient(lang, opts)` spawns the server, performs the LSP
42
- * `initialize` handshake, sends `initialized`, and returns a client.
43
- * 2. Each operation auto-opens the target file via `textDocument/didOpen`
44
- * on first touch (we keep a `Set<string>` of opened URIs). Files are
45
- * never closed mid-session — the server is per-CLI-invocation and
46
- * the process exit cleans up.
47
- * 3. `stop()` sends `shutdown` + `exit` (best-effort) and SIGKILLs the
48
- * child after a 1s grace window so the CLI never hangs on a
49
- * misbehaving server.
50
- *
51
- * Cancellation: every async operation accepts an optional CancellationToken
52
- * (α6.9). On abort, we send LSP `$/cancelRequest` for the in-flight ID and
53
- * reject the promise with `OperatorAbortedError`.
54
- *
55
- * Privacy: requests stay client-side. There is no Anvil round-trip; the
56
- * server process reads ONLY the files the operator's code actually opens.
57
- * The `pugi privacy airgapped` mode does not need to gate this surface
58
- * because the LSP server is local; we still honor the mode by skipping
59
- * the optional update-check banner inside the CLI command surface.
60
- *
61
- * Brand voice: ASCII only, no emoji, no banned words.
62
- */
63
- import { spawn, spawnSync } from 'node:child_process';
64
- import { pathToFileURL } from 'node:url';
65
- import { readFileSync } from 'node:fs';
66
- import { resolve, sep } from 'node:path';
67
- import { OperatorAbortedError } from '../../tools/file-tools.js';
68
- const LANGUAGE_SERVERS = {
69
- ts: {
70
- command: 'npx',
71
- args: ['--yes', 'typescript-language-server', '--stdio'],
72
- languageId: 'typescript',
73
- probe: 'npx',
74
- },
75
- js: {
76
- command: 'npx',
77
- args: ['--yes', 'typescript-language-server', '--stdio'],
78
- languageId: 'javascript',
79
- probe: 'npx',
80
- },
81
- py: {
82
- command: 'pyright-langserver',
83
- args: ['--stdio'],
84
- languageId: 'python',
85
- probe: 'pyright-langserver',
86
- },
87
- go: {
88
- command: 'gopls',
89
- args: [],
90
- languageId: 'go',
91
- probe: 'gopls',
92
- },
93
- rust: {
94
- command: 'rust-analyzer',
95
- args: [],
96
- languageId: 'rust',
97
- probe: 'rust-analyzer',
98
- },
99
- };
100
- const DEFAULT_REQUEST_TIMEOUT_MS = 5_000;
101
- /**
102
- * Returned by `startLspClient`. Methods are async; every method honors
103
- * the optional `CancellationToken` parameter.
104
- */
105
- export class LspClient {
106
- cwd;
107
- child;
108
- server;
109
- openedFiles = new Set();
110
- pending = new Map();
111
- diagnosticsByUri = new Map();
112
- requestTimeoutMs;
113
- nextId = 1;
114
- buffer = Buffer.alloc(0);
115
- stopped = false;
116
- constructor(child, server, opts) {
117
- this.child = child;
118
- this.server = server;
119
- this.cwd = opts.cwd;
120
- this.requestTimeoutMs = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
121
- child.stdout.on('data', (chunk) => this.onStdout(chunk));
122
- // Stderr is the server's diagnostic channel; we swallow it so a
123
- // chatty server (e.g. tsserver `debug:` lines) does not leak into
124
- // the operator-facing CLI stream. Operators can re-run with
125
- // `PUGI_LSP_DEBUG=1` to surface stderr.
126
- if (process.env.PUGI_LSP_DEBUG === '1') {
127
- child.stderr.on('data', (chunk) => process.stderr.write(chunk));
128
- }
129
- else {
130
- child.stderr.on('data', () => { });
131
- }
132
- child.on('exit', () => this.onExit());
133
- }
134
- /**
135
- * Send `shutdown` + `exit`, then SIGKILL after a 1s grace window so
136
- * a hung server never blocks CLI termination. Idempotent.
137
- */
138
- async stop() {
139
- if (this.stopped)
140
- return;
141
- this.stopped = true;
142
- try {
143
- await this.sendRequest('shutdown', null, undefined);
144
- this.sendNotification('exit', null);
145
- }
146
- catch {
147
- // Best-effort. A server that ignored shutdown gets the SIGKILL
148
- // path below.
149
- }
150
- const killTimer = setTimeout(() => {
151
- try {
152
- this.child.kill('SIGKILL');
153
- }
154
- catch {
155
- // already exited
156
- }
157
- }, 1_000);
158
- killTimer.unref();
159
- // Reject any in-flight requests so callers do not hang on the
160
- // shutdown path. We drain the map first to avoid the reject
161
- // callback re-entering and mutating the map mid-iteration.
162
- const snapshot = Array.from(this.pending.entries());
163
- this.pending.clear();
164
- for (const [, entry] of snapshot) {
165
- clearTimeout(entry.timer);
166
- entry.reject(new Error('lsp_stopped'));
167
- }
168
- }
169
- async hover(file, pos, token) {
170
- return this.withDocument(file, async (uri) => {
171
- const raw = await this.sendRequest('textDocument/hover', {
172
- textDocument: { uri },
173
- position: pos,
174
- }, token);
175
- if (raw === null || raw === undefined)
176
- return { ok: true, value: null };
177
- const value = normalizeHover(raw);
178
- return { ok: true, value };
179
- });
180
- }
181
- async definition(file, pos, token) {
182
- return this.withDocument(file, async (uri) => {
183
- const raw = await this.sendRequest('textDocument/definition', {
184
- textDocument: { uri },
185
- position: pos,
186
- }, token);
187
- const locations = normalizeLocations(raw, this.cwd);
188
- return { ok: true, value: locations };
189
- });
190
- }
191
- async references(file, pos, token) {
192
- return this.withDocument(file, async (uri) => {
193
- const raw = await this.sendRequest('textDocument/references', {
194
- textDocument: { uri },
195
- position: pos,
196
- context: { includeDeclaration: true },
197
- }, token);
198
- const locations = normalizeLocations(raw, this.cwd);
199
- return { ok: true, value: locations };
200
- });
201
- }
202
- /**
203
- * Diagnostics in LSP arrive as PUSH (`textDocument/publishDiagnostics`)
204
- * not pull. We open the document, wait one short tick for the server
205
- * to drain its first analysis pass, and return what is cached.
206
- * Servers that emit diagnostics asynchronously (gopls, rust-analyzer)
207
- * may take longer; the caller can extend `requestTimeoutMs` to allow
208
- * for the cold start.
209
- */
210
- async diagnostics(file, token) {
211
- return this.withDocument(file, async (uri) => {
212
- // Give the server one analysis cycle before reading the cache.
213
- // 200ms is enough for a warm tsserver; a cold server returns the
214
- // empty array and the caller can re-poll.
215
- await new Promise((res) => {
216
- const wait = setTimeout(res, 200);
217
- wait.unref();
218
- if (token) {
219
- token.onAbort(() => {
220
- clearTimeout(wait);
221
- res();
222
- });
223
- }
224
- });
225
- if (token && token.isAborted) {
226
- return { ok: false, reason: 'operator_aborted', detail: 'lspDiagnostics aborted' };
227
- }
228
- const cached = this.diagnosticsByUri.get(uri) ?? [];
229
- return { ok: true, value: cached };
230
- });
231
- }
232
- /**
233
- * Ensure the file is open server-side, then run `op`. The first call
234
- * for a path sends `textDocument/didOpen` with the on-disk content;
235
- * subsequent calls skip the open.
236
- */
237
- async withDocument(file, op) {
238
- let absPath;
239
- try {
240
- absPath = resolve(this.cwd, file);
241
- if (!absPath.startsWith(this.cwd + sep) && absPath !== this.cwd) {
242
- return {
243
- ok: false,
244
- reason: 'lsp_error',
245
- detail: `path escapes workspace: ${file}`,
246
- };
247
- }
248
- }
249
- catch (error) {
250
- return {
251
- ok: false,
252
- reason: 'lsp_error',
253
- detail: error instanceof Error ? error.message : String(error),
254
- };
255
- }
256
- const uri = pathToFileURL(absPath).toString();
257
- if (!this.openedFiles.has(uri)) {
258
- try {
259
- const text = readFileSync(absPath, 'utf8');
260
- this.sendNotification('textDocument/didOpen', {
261
- textDocument: {
262
- uri,
263
- languageId: this.server.languageId,
264
- version: 1,
265
- text,
266
- },
267
- });
268
- this.openedFiles.add(uri);
269
- }
270
- catch (error) {
271
- return {
272
- ok: false,
273
- reason: 'lsp_error',
274
- detail: `cannot read ${file}: ${error instanceof Error ? error.message : String(error)}`,
275
- };
276
- }
277
- }
278
- try {
279
- return await op(uri);
280
- }
281
- catch (error) {
282
- if (error instanceof OperatorAbortedError) {
283
- return { ok: false, reason: 'operator_aborted', detail: error.message };
284
- }
285
- if (error instanceof Error && error.message === 'request_timeout') {
286
- return { ok: false, reason: 'request_timeout', detail: 'lsp request timed out' };
287
- }
288
- return {
289
- ok: false,
290
- reason: 'lsp_error',
291
- detail: error instanceof Error ? error.message : String(error),
292
- };
293
- }
294
- }
295
- sendRequest(method, params, token) {
296
- const id = this.nextId++;
297
- const payload = { jsonrpc: '2.0', id, method, params };
298
- return new Promise((resolveFn, rejectFn) => {
299
- const timer = setTimeout(() => {
300
- if (this.pending.has(id)) {
301
- this.pending.delete(id);
302
- rejectFn(new Error('request_timeout'));
303
- }
304
- }, this.requestTimeoutMs);
305
- timer.unref();
306
- this.pending.set(id, { resolve: resolveFn, reject: rejectFn, timer });
307
- if (token) {
308
- token.onAbort(() => {
309
- if (this.pending.has(id)) {
310
- this.pending.delete(id);
311
- clearTimeout(timer);
312
- // Best-effort cancel notification to the server. Some
313
- // servers ignore $/cancelRequest; the local reject below
314
- // is what frees the caller.
315
- try {
316
- this.sendNotification('$/cancelRequest', { id });
317
- }
318
- catch {
319
- // server may already be gone
320
- }
321
- rejectFn(new OperatorAbortedError('lsp_request'));
322
- }
323
- });
324
- }
325
- try {
326
- this.writeMessage(payload);
327
- }
328
- catch (error) {
329
- this.pending.delete(id);
330
- clearTimeout(timer);
331
- rejectFn(error instanceof Error ? error : new Error(String(error)));
332
- }
333
- });
334
- }
335
- sendNotification(method, params) {
336
- this.writeMessage({ jsonrpc: '2.0', method, params });
337
- }
338
- writeMessage(payload) {
339
- const body = JSON.stringify(payload);
340
- const message = `Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`;
341
- this.child.stdin.write(message, 'utf8');
342
- }
343
- onStdout(chunk) {
344
- this.buffer = Buffer.concat([this.buffer, chunk]);
345
- while (true) {
346
- const headerEnd = this.buffer.indexOf('\r\n\r\n');
347
- if (headerEnd < 0)
348
- return;
349
- const headerText = this.buffer.subarray(0, headerEnd).toString('ascii');
350
- const lengthMatch = headerText.match(/Content-Length:\s*(\d+)/i);
351
- if (!lengthMatch || lengthMatch[1] === undefined) {
352
- // Malformed header — drop the buffer and resync at the next message.
353
- this.buffer = Buffer.alloc(0);
354
- return;
355
- }
356
- const length = Number.parseInt(lengthMatch[1], 10);
357
- const bodyStart = headerEnd + 4;
358
- if (this.buffer.length < bodyStart + length)
359
- return;
360
- const bodyText = this.buffer.subarray(bodyStart, bodyStart + length).toString('utf8');
361
- this.buffer = this.buffer.subarray(bodyStart + length);
362
- try {
363
- const message = JSON.parse(bodyText);
364
- this.handleMessage(message);
365
- }
366
- catch {
367
- // Garbage body — drop and continue parsing the next message.
368
- }
369
- }
370
- }
371
- handleMessage(message) {
372
- // Response — has `id` and either `result` or `error`.
373
- if (typeof message['id'] === 'number') {
374
- const id = message['id'];
375
- const entry = this.pending.get(id);
376
- if (!entry)
377
- return;
378
- this.pending.delete(id);
379
- clearTimeout(entry.timer);
380
- if ('error' in message && message['error']) {
381
- const err = message['error'];
382
- entry.reject(new Error(`lsp_error code=${err.code ?? 'unknown'}: ${err.message ?? 'no message'}`));
383
- return;
384
- }
385
- entry.resolve(message['result'] ?? null);
386
- return;
387
- }
388
- // Notification from server.
389
- if (message['method'] === 'textDocument/publishDiagnostics') {
390
- const params = message['params'];
391
- if (!params)
392
- return;
393
- const uri = typeof params.uri === 'string' ? params.uri : null;
394
- if (!uri)
395
- return;
396
- const raw = Array.isArray(params.diagnostics) ? params.diagnostics : [];
397
- const normalized = [];
398
- for (const item of raw) {
399
- const parsed = normalizeDiagnostic(item);
400
- if (parsed)
401
- normalized.push(parsed);
402
- }
403
- this.diagnosticsByUri.set(uri, normalized);
404
- }
405
- }
406
- onExit() {
407
- if (this.stopped)
408
- return;
409
- this.stopped = true;
410
- const snapshot = Array.from(this.pending.entries());
411
- this.pending.clear();
412
- for (const [, entry] of snapshot) {
413
- clearTimeout(entry.timer);
414
- entry.reject(new Error('lsp_server_exited'));
415
- }
416
- }
417
- }
418
- /**
419
- * Start an LSP client for the given language. Returns either an `LspClient`
420
- * ready to use, or a structured failure (`lsp_unavailable`,
421
- * `language_unsupported`).
422
- *
423
- * The returned client requires `await client.initialize()` BEFORE any
424
- * operation. We do not inline the initialize into the spawn so test
425
- * harnesses can intercept the handshake and assert on its contents.
426
- */
427
- export async function startLspClient(lang, opts) {
428
- const server = opts.serverOverride ?? LANGUAGE_SERVERS[lang];
429
- if (!server) {
430
- return {
431
- ok: false,
432
- reason: 'language_unsupported',
433
- detail: `no LSP server registered for language: ${lang}`,
434
- };
435
- }
436
- if (!opts.serverOverride) {
437
- const available = detectBinary(server.probe);
438
- if (!available) {
439
- return {
440
- ok: false,
441
- reason: 'lsp_unavailable',
442
- detail: `${server.probe} not found on PATH. ` +
443
- `Install the language server first ` +
444
- `(see https://pugi.io/docs/cli/lsp for per-language commands).`,
445
- };
446
- }
447
- }
448
- let child;
449
- try {
450
- child = spawn(server.command, [...server.args], {
451
- cwd: opts.cwd,
452
- stdio: ['pipe', 'pipe', 'pipe'],
453
- });
454
- }
455
- catch (error) {
456
- return {
457
- ok: false,
458
- reason: 'lsp_unavailable',
459
- detail: `failed to spawn ${server.command}: ${error instanceof Error ? error.message : String(error)}`,
460
- };
461
- }
462
- const client = new LspClient(child, server, opts);
463
- try {
464
- await initializeHandshake(client, opts.cwd);
465
- }
466
- catch (error) {
467
- await client.stop();
468
- return {
469
- ok: false,
470
- reason: 'lsp_error',
471
- detail: `initialize failed: ${error instanceof Error ? error.message : String(error)}`,
472
- };
473
- }
474
- return { ok: true, value: client };
475
- }
476
- async function initializeHandshake(client, cwd) {
477
- const rootUri = pathToFileURL(cwd).toString();
478
- // Use the public sendRequest path via a method call. We piggyback on
479
- // `LspClient`'s internal `sendRequest` by exposing a single test-grade
480
- // surface (`__lspRaw__`); production callers never need this.
481
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
482
- const internal = client;
483
- await internal.sendRequest('initialize', {
484
- processId: process.pid,
485
- rootUri,
486
- capabilities: {
487
- textDocument: {
488
- hover: { contentFormat: ['plaintext', 'markdown'] },
489
- definition: { linkSupport: false },
490
- references: {},
491
- publishDiagnostics: { relatedInformation: false },
492
- },
493
- },
494
- workspaceFolders: [{ uri: rootUri, name: 'pugi-workspace' }],
495
- }, undefined);
496
- internal.sendNotification('initialized', {});
497
- }
498
- function detectBinary(name) {
499
- // Cross-platform `which` — spawnSync of the binary with --version is
500
- // too aggressive (some servers don't honor --version). Use `which`
501
- // on POSIX and `where` on Windows. Failures are non-fatal — we just
502
- // report unavailable.
503
- const probe = process.platform === 'win32' ? 'where' : 'which';
504
- try {
505
- const result = spawnSync(probe, [name], { stdio: 'ignore' });
506
- return result.status === 0;
507
- }
508
- catch {
509
- return false;
510
- }
511
- }
512
- function normalizeHover(raw) {
513
- // LSP `Hover.contents` can be:
514
- // - string
515
- // - { kind: 'markdown' | 'plaintext', value: string }
516
- // - Array<string | { language: string, value: string }>
517
- if (!raw || typeof raw !== 'object') {
518
- return { content: String(raw ?? ''), raw };
519
- }
520
- const obj = raw;
521
- const range = parseRange(obj.range);
522
- const body = obj.contents;
523
- if (typeof body === 'string') {
524
- return { content: body, range, raw };
525
- }
526
- if (Array.isArray(body)) {
527
- const parts = [];
528
- for (const item of body) {
529
- if (typeof item === 'string')
530
- parts.push(item);
531
- else if (item && typeof item === 'object' && 'value' in item) {
532
- const value = item.value;
533
- if (typeof value === 'string')
534
- parts.push(value);
535
- }
536
- }
537
- return { content: parts.join('\n'), range, raw };
538
- }
539
- if (body && typeof body === 'object' && 'value' in body) {
540
- const value = body.value;
541
- return { content: typeof value === 'string' ? value : '', range, raw };
542
- }
543
- return { content: '', range, raw };
544
- }
545
- function normalizeLocations(raw, cwd) {
546
- if (!raw)
547
- return [];
548
- const items = Array.isArray(raw) ? raw : [raw];
549
- const out = [];
550
- for (const item of items) {
551
- if (!item || typeof item !== 'object')
552
- continue;
553
- const obj = item;
554
- const uri = typeof obj.uri === 'string' ? obj.uri : typeof obj.targetUri === 'string' ? obj.targetUri : null;
555
- const range = parseRange(obj.range ?? obj.targetRange);
556
- if (!uri || !range)
557
- continue;
558
- let path = '';
559
- try {
560
- const url = new URL(uri);
561
- if (url.protocol === 'file:') {
562
- const abs = decodeURIComponent(url.pathname);
563
- if (abs.startsWith(cwd + sep) || abs === cwd) {
564
- path = abs.slice(cwd.length + 1);
565
- }
566
- }
567
- }
568
- catch {
569
- path = '';
570
- }
571
- out.push({ uri, path, range });
572
- }
573
- return out;
574
- }
575
- function parseRange(raw) {
576
- if (!raw || typeof raw !== 'object')
577
- return undefined;
578
- const obj = raw;
579
- const start = parsePosition(obj.start);
580
- const end = parsePosition(obj.end);
581
- if (!start || !end)
582
- return undefined;
583
- return { start, end };
584
- }
585
- function parsePosition(raw) {
586
- if (!raw || typeof raw !== 'object')
587
- return undefined;
588
- const obj = raw;
589
- if (typeof obj.line !== 'number' || typeof obj.character !== 'number')
590
- return undefined;
591
- return { line: obj.line, character: obj.character };
592
- }
593
- function normalizeDiagnostic(raw) {
594
- if (!raw || typeof raw !== 'object')
595
- return null;
596
- const obj = raw;
597
- const range = parseRange(obj.range);
598
- if (!range)
599
- return null;
600
- if (typeof obj.message !== 'string')
601
- return null;
602
- const severityRaw = typeof obj.severity === 'number' ? obj.severity : 1;
603
- const severity = (severityRaw >= 1 && severityRaw <= 4 ? severityRaw : 1);
604
- const labels = {
605
- 1: 'error',
606
- 2: 'warning',
607
- 3: 'info',
608
- 4: 'hint',
609
- };
610
- const out = {
611
- severity,
612
- severityLabel: labels[severity],
613
- message: obj.message,
614
- range,
615
- ...(typeof obj.source === 'string' ? { source: obj.source } : {}),
616
- ...(typeof obj.code === 'string' || typeof obj.code === 'number' ? { code: obj.code } : {}),
617
- };
618
- return out;
619
- }
620
- /**
621
- * Test-only surface so specs can hand-craft an `LspClient` over a mock
622
- * stdio pipe without paying for the real `startLspClient` spawn cost.
623
- * The exported shape mirrors what the constructor needs.
624
- */
625
- export const __test__ = {
626
- LANGUAGE_SERVERS,
627
- normalizeHover,
628
- normalizeLocations,
629
- normalizeDiagnostic,
630
- };
631
- //# sourceMappingURL=client.js.map