@pal-code/core 0.0.21 → 0.0.23

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.
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Minimal stdio LSP client (roadmap #2).
3
+ *
4
+ * Scope check: this is not a general LSP implementation. It does exactly one
5
+ * job — start a server, open the files that were just edited, collect the
6
+ * diagnostics the server publishes for them, shut down. No completion, no
7
+ * hover, no workspace symbols, no multi-workspace, no `workspace/configuration`
8
+ * fan-out. Every one of those would be another few hundred lines of state that
9
+ * nothing in pal calls.
10
+ *
11
+ * The hard requirement is the one from `diagnostics.ts`: `noteEditedFile()` is
12
+ * fire-and-forget and the tool handler must never wait longer than its budget.
13
+ * So every await here races a deadline, and the client resolves to `null` on
14
+ * *any* trouble. A missing binary, a server that never initialises, a server
15
+ * that publishes nothing — all the same outcome, and the caller falls back to
16
+ * biome/tsc.
17
+ */
18
+
19
+ import {readFileSync} from 'fs';
20
+ import {log} from '../logger.js';
21
+ import {FrameDecoder, encodeMessage} from './framing.js';
22
+ import {type LspDiagnostic, mapDiagnostics} from './diagnostics-map.js';
23
+ import {fallbackWorkspaceConfig} from './diagnostics-map.js';
24
+ import type {ServerSpec} from './servers.js';
25
+ import type {DiagnosticError} from '../diagnostics.js';
26
+
27
+ /** JSON-RPC ids for requests this client sends. Server ids are echoed back. */
28
+ const INIT_REQUEST = 1;
29
+ const SHUTDOWN_REQUEST = 999_999;
30
+
31
+ interface PendingRequest {
32
+ resolve: (value: unknown) => void;
33
+ reject: (err: Error) => void;
34
+ }
35
+
36
+ export interface LspRunOptions {
37
+ spec: ServerSpec;
38
+ files: readonly string[];
39
+ cwd: string;
40
+ budgetMs: number;
41
+ }
42
+
43
+ /**
44
+ * Start a server, collect diagnostics for `files`, stop it.
45
+ *
46
+ * Returns `null` for "no opinion" — the signal that the caller should fall back.
47
+ * Returns `[]` only when a server actually answered and said the files are clean.
48
+ */
49
+ export async function runLspChecks(opts: LspRunOptions): Promise<DiagnosticError[] | null> {
50
+ const deadline = Date.now() + opts.budgetMs;
51
+ const remaining = () => Math.max(0, deadline - Date.now());
52
+
53
+ const client = new LspClient(opts);
54
+ try {
55
+ const started = await client.start(remaining());
56
+ if (!started) return null;
57
+
58
+ const published = await client.collect(remaining());
59
+ if (published === null) return null;
60
+
61
+ const mapped = mapDiagnostics(published, opts.files, opts.cwd);
62
+ return mapped.map((m) => ({path: m.path, line: m.line, message: m.message}));
63
+ } catch (err) {
64
+ // Never reach the model, never break the edit.
65
+ log('lsp-run-failed', {
66
+ command: opts.spec.command,
67
+ message: err instanceof Error ? err.message : String(err),
68
+ });
69
+ return null;
70
+ } finally {
71
+ await client.stop();
72
+ }
73
+ }
74
+
75
+ class LspClient {
76
+ private proc: ReturnType<typeof Bun.spawn> | null = null;
77
+ private readonly decoder = new FrameDecoder();
78
+ private readonly pending = new Map<number, PendingRequest>();
79
+ /** Latest `publishDiagnostics` payload per URI — servers resend whole files. */
80
+ private readonly published = new Map<string, LspDiagnostic[]>();
81
+ private nextId = 10;
82
+ private exited = false;
83
+ private sawDiagnostics = false;
84
+ private lastPublishAt = 0;
85
+
86
+ constructor(private readonly opts: LspRunOptions) {}
87
+
88
+ /**
89
+ * Spawn + `initialize` + `initialized` + `didOpen` for every file.
90
+ *
91
+ * Returns false — not throws — when the server cannot be brought up, because
92
+ * "binary vanished between `isAvailable` and here" is a race, not a bug.
93
+ */
94
+ async start(budgetMs: number): Promise<boolean> {
95
+ const bin = this.resolveBinary();
96
+ if (bin === null) return false;
97
+
98
+ try {
99
+ this.proc = Bun.spawn([bin, ...this.opts.spec.args], {
100
+ stdin: 'pipe',
101
+ stdout: 'pipe',
102
+ stderr: 'pipe',
103
+ cwd: this.opts.cwd,
104
+ });
105
+ } catch (err) {
106
+ log('lsp-spawn-failed', {
107
+ command: this.opts.spec.command,
108
+ message: err instanceof Error ? err.message : String(err),
109
+ });
110
+ return false;
111
+ }
112
+
113
+ this.pumpStdout();
114
+ // stderr is drained but ignored: servers log chat to it constantly, and
115
+ // letting the pipe fill would block the server mid-initialise.
116
+ this.drainStderr();
117
+ this.watchExit();
118
+
119
+ const initResult = await this.request(
120
+ 'initialize',
121
+ {
122
+ processId: process.pid,
123
+ rootUri: null,
124
+ capabilities: {
125
+ // Only diagnostics are wanted; declaring less keeps servers from
126
+ // sending things this client would ignore anyway.
127
+ textDocument: {synchronization: {didSave: false, dynamicRegistration: false}},
128
+ workspace: {configuration: false, workspaceFolders: false},
129
+ },
130
+ ...(fallbackWorkspaceConfig(this.opts.spec.languageId) ?? {}),
131
+ },
132
+ budgetMs,
133
+ );
134
+ if (initResult === null) return false;
135
+
136
+ this.send({jsonrpc: '2.0', method: 'initialized', params: {}});
137
+ for (const file of this.opts.files) this.didOpen(file);
138
+ return true;
139
+ }
140
+
141
+ /**
142
+ * Wait for the server to publish diagnostics, bounded by the budget.
143
+ *
144
+ * Servers are asynchronous and give no "I'm done analysing" signal in the base
145
+ * protocol. Two ways out: a publish arrives, then a short quiet period passes
146
+ * with no further publish (a server that reports 40 errors sends them as
147
+ * several publishes, and stopping at the first would under-report); or a
148
+ * `didOpen`-driven publish arrives and the server goes quiet. If nothing at all
149
+ * arrives, resolve `null` rather than pretending the files are clean — an empty
150
+ * result would tell the model "your edit is fine", which is exactly the
151
+ * false-negative that makes auto-diagnostics untrustworthy.
152
+ */
153
+ async collect(budgetMs: number): Promise<Map<string, LspDiagnostic[]> | null> {
154
+ const hardDeadline = Date.now() + budgetMs;
155
+
156
+ while (Date.now() < hardDeadline) {
157
+ if (this.exited && !this.sawDiagnostics) return null;
158
+ if (this.sawDiagnostics && this.quietFor(150)) return this.published;
159
+ await sleep(25);
160
+ }
161
+
162
+ return this.sawDiagnostics ? this.published : null;
163
+ }
164
+
165
+ private quietFor(ms: number): boolean {
166
+ return Date.now() - this.lastPublishAt >= ms;
167
+ }
168
+
169
+ /** `shutdown` → `exit` → SIGKILL if it lingers. Never throws. */
170
+ async stop(): Promise<void> {
171
+ const proc = this.proc;
172
+ if (proc === null) return;
173
+ this.proc = null;
174
+
175
+ try {
176
+ if (!this.exited) {
177
+ this.send({jsonrpc: '2.0', id: SHUTDOWN_REQUEST, method: 'shutdown', params: null});
178
+ this.send({jsonrpc: '2.0', method: 'exit', params: null});
179
+ }
180
+ // Give it a moment to exit on its own; a wedged server must not outlive
181
+ // the edit, so SIGKILL is the fallback rather than an indefinite wait.
182
+ const timer = setTimeout(() => {
183
+ try {
184
+ proc.kill(9);
185
+ } catch {
186
+ /* already gone */
187
+ }
188
+ }, 200);
189
+ try {
190
+ await Promise.race([proc.exited, sleep(300)]);
191
+ } finally {
192
+ clearTimeout(timer);
193
+ }
194
+ try {
195
+ proc.kill(9);
196
+ } catch {
197
+ /* already gone */
198
+ }
199
+ } catch {
200
+ /* shutting down is best-effort */
201
+ }
202
+ }
203
+
204
+ // ---- internals -----------------------------------------------------------
205
+
206
+ private resolveBinary(): string | null {
207
+ try {
208
+ return Bun.which(this.opts.spec.command) ?? null;
209
+ } catch {
210
+ return null;
211
+ }
212
+ }
213
+
214
+ private request(method: string, params: unknown, budgetMs: number): Promise<unknown | null> {
215
+ const id = this.nextId++;
216
+ const promise = new Promise<unknown>((resolve, reject) => {
217
+ this.pending.set(id, {resolve, reject});
218
+ });
219
+
220
+ this.send({jsonrpc: '2.0', id, method, params});
221
+
222
+ return Promise.race([
223
+ promise.then((v) => v).catch(() => null),
224
+ sleep(budgetMs).then(() => null),
225
+ ]);
226
+ }
227
+
228
+ private send(payload: unknown): void {
229
+ const proc = this.proc;
230
+ if (proc === null || this.exited) return;
231
+ try {
232
+ const stdin = proc.stdin as {write?: (chunk: string) => void} | undefined;
233
+ stdin?.write?.(encodeMessage(payload));
234
+ } catch {
235
+ /* stdin closed — the exit handler will surface it */
236
+ }
237
+ }
238
+
239
+ private didOpen(file: string): void {
240
+ const abs = file;
241
+ let text: string;
242
+ try {
243
+ text = readFileSync(abs, 'utf8');
244
+ } catch {
245
+ return;
246
+ }
247
+ this.send({
248
+ jsonrpc: '2.0',
249
+ method: 'textDocument/didOpen',
250
+ params: {
251
+ textDocument: {
252
+ uri: pathToUri(abs),
253
+ languageId: this.opts.spec.languageId,
254
+ version: 1,
255
+ text,
256
+ },
257
+ },
258
+ });
259
+ }
260
+
261
+ private pumpStdout(): void {
262
+ const proc = this.proc;
263
+ const stdout = proc?.stdout as ReadableStream<Uint8Array> | undefined;
264
+ if (!stdout) return;
265
+
266
+ void (async () => {
267
+ const reader = stdout.getReader();
268
+ try {
269
+ for (;;) {
270
+ const {done, value} = await reader.read();
271
+ if (done) return;
272
+ if (!value) continue;
273
+ for (const frame of this.decoder.push(value)) {
274
+ if (frame.parseError) {
275
+ log('lsp-bad-frame', {error: frame.parseError});
276
+ continue;
277
+ }
278
+ this.handle(frame.body);
279
+ }
280
+ }
281
+ } catch {
282
+ /* stream torn down with the process */
283
+ }
284
+ })();
285
+ }
286
+
287
+ private drainStderr(): void {
288
+ const stderr = this.proc?.stderr as ReadableStream<Uint8Array> | undefined;
289
+ if (!stderr) return;
290
+ void (async () => {
291
+ try {
292
+ const reader = stderr.getReader();
293
+ for (;;) {
294
+ const {done} = await reader.read();
295
+ if (done) return;
296
+ }
297
+ } catch {
298
+ /* ignored on purpose */
299
+ }
300
+ })();
301
+ }
302
+
303
+ private watchExit(): void {
304
+ const proc = this.proc;
305
+ if (!proc) return;
306
+ void Promise.resolve(proc.exited).then(() => {
307
+ this.exited = true;
308
+ for (const [, pending] of this.pending) pending.reject(new Error('lsp exited'));
309
+ this.pending.clear();
310
+ });
311
+ }
312
+
313
+ private handle(body: unknown): void {
314
+ if (typeof body !== 'object' || body === null) return;
315
+ const msg = body as {
316
+ id?: number;
317
+ method?: string;
318
+ result?: unknown;
319
+ params?: {uri?: string; diagnostics?: LspDiagnostic[]};
320
+ };
321
+
322
+ // Response to one of our requests.
323
+ if (typeof msg.id === 'number' && msg.method === undefined) {
324
+ const pending = this.pending.get(msg.id);
325
+ if (pending) {
326
+ this.pending.delete(msg.id);
327
+ pending.resolve(msg.result);
328
+ }
329
+ return;
330
+ }
331
+
332
+ if (msg.method === 'textDocument/publishDiagnostics' && msg.params?.uri) {
333
+ this.published.set(msg.params.uri, msg.params.diagnostics ?? []);
334
+ this.lastPublishAt = Date.now();
335
+ this.sawDiagnostics = true;
336
+ return;
337
+ }
338
+
339
+ // Server → client requests. Answering `null`/`null` keeps every server we
340
+ // target happy without implementing any of them; silence would stall it.
341
+ if (typeof msg.id === 'number' && msg.method !== undefined) {
342
+ if (msg.method === 'workspace/configuration') {
343
+ const items = (msg.params as unknown as {items?: unknown[]})?.items ?? [];
344
+ this.send({jsonrpc: '2.0', id: msg.id, result: items.map(() => null)});
345
+ } else {
346
+ this.send({jsonrpc: '2.0', id: msg.id, result: null});
347
+ }
348
+ }
349
+ }
350
+ }
351
+
352
+ /** `C:\x\y.ts` → `file:///C:/x/y.ts`, POSIX → `file:///x/y.ts`. */
353
+ export function pathToUri(abs: string): string {
354
+ const slashed = abs.replace(/\\/g, '/');
355
+ const prefixed = slashed.startsWith('/') ? slashed : `/${slashed}`;
356
+ return `file://${encodeURI(prefixed).replace(/#/g, '%23').replace(/\?/g, '%3F')}`;
357
+ }
358
+
359
+ function sleep(ms: number): Promise<boolean> {
360
+ return new Promise((resolve) => setTimeout(() => resolve(true), Math.max(0, ms)));
361
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Turning LSP diagnostics into the one line pal feeds back to the model.
3
+ *
4
+ * Pure — the client owns processes and timers; this owns the meaning. Two rules
5
+ * matter more than they look:
6
+ *
7
+ * 1. **Only errors.** A language server reports hints, information, warnings and
8
+ * errors. pal injects the result into the model's next context, so a warning
9
+ * about an unused variable would be noise the model then tries to "fix".
10
+ * 2. **Only the edited files.** A server happily reports pre-existing errors
11
+ * across the whole workspace. Those were not caused by this edit, and telling
12
+ * the model about them sends it chasing someone else's bug.
13
+ */
14
+
15
+ import {isAbsolute, relative, resolve, sep} from 'path';
16
+
17
+ /** The subset of LSP's `Diagnostic` this module reads. */
18
+ export interface LspDiagnostic {
19
+ range?: {start?: {line?: number; character?: number}};
20
+ severity?: number;
21
+ message?: string;
22
+ source?: string;
23
+ }
24
+
25
+ /** LSP severity numbers. 1 = Error is the only one that means "broken". */
26
+ export const SEVERITY_ERROR = 1;
27
+
28
+ export interface MappedDiagnostic {
29
+ path: string;
30
+ /** 1-based, because every editor and compiler pal already speaks to is 1-based. */
31
+ line: number;
32
+ message: string;
33
+ }
34
+
35
+ /**
36
+ * Normalise a server-reported URI to a project-relative path.
37
+ *
38
+ * Servers send `file:///C:/x/y.ts` (Windows), `file:///home/x/y.ts` (POSIX), and
39
+ * sometimes percent-escaped (`%20` for a space). `fileURLToPath` handles all
40
+ * three; the manual fallback exists only for servers that send a bare path,
41
+ * which is out of spec but not unheard of.
42
+ */
43
+ export function uriToRelPath(uri: string, cwd: string): string | null {
44
+ let filePath: string;
45
+ try {
46
+ if (uri.startsWith('file:')) {
47
+ filePath = decodeURIComponent(new URL(uri).pathname);
48
+ // Windows: `file:///C:/x` yields `/C:/x`; drop the leading slash.
49
+ if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
50
+ } else {
51
+ filePath = uri;
52
+ }
53
+ } catch {
54
+ return null;
55
+ }
56
+
57
+ const abs = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);
58
+ const rel = relative(cwd, abs);
59
+ // Outside the project: report the absolute path rather than `../../..`.
60
+ if (rel.startsWith('..') || rel === '') return abs.split(sep).join('/');
61
+ return rel.split(sep).join('/');
62
+ }
63
+
64
+ /**
65
+ * Keep only error-severity diagnostics that belong to `changedFiles`.
66
+ *
67
+ * @param byUri `textDocument/publishDiagnostics` payloads, already keyed by URI.
68
+ */
69
+ export function mapDiagnostics(
70
+ byUri: ReadonlyMap<string, readonly LspDiagnostic[]>,
71
+ changedFiles: readonly string[],
72
+ cwd: string,
73
+ ): MappedDiagnostic[] {
74
+ // Compare on normalised relative paths: the server may report `src/a.ts` while
75
+ // the caller passed `/abs/project/src/a.ts`, and those must be the same file.
76
+ const wanted = new Set(changedFiles.map((f) => normalise(f, cwd)));
77
+ const out: MappedDiagnostic[] = [];
78
+
79
+ for (const [uri, diagnostics] of byUri) {
80
+ const rel = uriToRelPath(uri, cwd);
81
+ if (rel === null) continue;
82
+ if (!wanted.has(normalise(rel, cwd))) continue;
83
+
84
+ for (const d of diagnostics) {
85
+ if (d.severity !== undefined && d.severity !== SEVERITY_ERROR) continue;
86
+ const message = (d.message ?? '').replace(/\s+/g, ' ').trim();
87
+ if (message === '') continue;
88
+ out.push({
89
+ path: rel,
90
+ // LSP lines are 0-based; every other tool pal reports from is 1-based.
91
+ line: (d.range?.start?.line ?? 0) + 1,
92
+ message: d.source ? `${message} (${d.source})` : message,
93
+ });
94
+ }
95
+ }
96
+
97
+ return out;
98
+ }
99
+
100
+ function normalise(p: string, cwd: string): string {
101
+ const abs = isAbsolute(p) ? p : resolve(cwd, p);
102
+ return abs.split(sep).join('/').toLowerCase();
103
+ }
104
+
105
+ /**
106
+ * A configuration a language server can actually start from.
107
+ *
108
+ * The single most likely failure is "spawned a real server against a workspace
109
+ * with no config and got a wall of setup errors", which would then be injected
110
+ * into the model as if the edit broke something. So this generates a minimal
111
+ * in-memory config for the two cases where such errors are guaranteed:
112
+ *
113
+ * - **pyright** reports every import as unresolved without a `venvPath`, which is
114
+ * not a real error and is the classic false-positive wall.
115
+ * - **`tsc` LSP** (typescript-language-server) needs *some* compiler options; an
116
+ * empty object means it falls back to defaults that may not match the project,
117
+ * but importantly it does not report "no config found" as a diagnostic.
118
+ *
119
+ * Deliberately minimal: a real project config on disk always wins, because the
120
+ * server only uses this when nothing else is available.
121
+ */
122
+ export function fallbackWorkspaceConfig(languageId: string): {settings: unknown} | null {
123
+ if (languageId === 'python') {
124
+ return {
125
+ settings: {
126
+ python: {
127
+ analysis: {
128
+ // Do not flag every third-party import as unresolved. This is the
129
+ // difference between a useful signal and 40 lines of noise.
130
+ diagnosticSeverityOverrides: {reportMissingImports: 'none'},
131
+ useLibraryCodeForTypes: true,
132
+ },
133
+ },
134
+ },
135
+ };
136
+ }
137
+ return null;
138
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * A fake LSP server for testing `runLspChecks` against real process I/O.
3
+ *
4
+ * Reads `Content-Length` frames on stdin, answers `initialize` and `shutdown`,
5
+ * and on `didOpen` publishes a configurable set of diagnostics. Behaviour comes
6
+ * from `argv[2]` (not an env var: `Bun.spawn` does not reliably inherit a
7
+ * `process.env` mutation made after the test process started):
8
+ *
9
+ * - `clean` — publishes nothing at all (the "no opinion" case that must fall
10
+ * back rather than claim the file is fine)
11
+ * - `errors` — publishes one error + one warning per opened file, in two
12
+ * separate frames so the client's quiet-period logic is exercised
13
+ * - `slow` — never answers `initialize` (must time out, not hang)
14
+ * - `die` — exits immediately after spawn
15
+ */
16
+
17
+ const mode = process.argv[2] ?? 'errors';
18
+
19
+ function send(payload: unknown): void {
20
+ const json = JSON.stringify(payload);
21
+ process.stdout.write(`Content-Length: ${Buffer.byteLength(json, 'utf8')}\r\n\r\n${json}`);
22
+ }
23
+
24
+ if (mode === 'die') process.exit(0);
25
+
26
+ let buffer = Buffer.alloc(0);
27
+
28
+ process.stdin.on('data', (chunk: Buffer) => {
29
+ buffer = Buffer.concat([buffer, chunk]);
30
+
31
+ for (;;) {
32
+ const headerEnd = buffer.indexOf('\r\n\r\n');
33
+ if (headerEnd === -1) return;
34
+ const header = buffer.subarray(0, headerEnd).toString('ascii');
35
+ const len = Number(/content-length:\s*(\d+)/i.exec(header)?.[1] ?? -1);
36
+ if (len < 0) {
37
+ buffer = buffer.subarray(headerEnd + 4);
38
+ continue;
39
+ }
40
+ const start = headerEnd + 4;
41
+ if (buffer.length < start + len) return;
42
+
43
+ const msg = JSON.parse(buffer.subarray(start, start + len).toString('utf8'));
44
+ buffer = buffer.subarray(start + len);
45
+ handle(msg);
46
+ }
47
+ });
48
+
49
+ function handle(msg: {id?: number; method?: string; params?: Record<string, unknown>}): void {
50
+ switch (msg.method) {
51
+ case 'initialize': {
52
+ if (mode === 'slow') return; // never answer → caller must time out
53
+ send({jsonrpc: '2.0', id: msg.id, result: {capabilities: {}}});
54
+ return;
55
+ }
56
+ case 'shutdown': {
57
+ send({jsonrpc: '2.0', id: msg.id, result: null});
58
+ return;
59
+ }
60
+ case 'exit': {
61
+ process.exit(0);
62
+ return;
63
+ }
64
+ case 'textDocument/didOpen': {
65
+ const td = msg.params?.textDocument as {uri: string} | undefined;
66
+ if (!td || mode === 'clean') return;
67
+
68
+ // Two publishes, like a real server: errors first, then the full set.
69
+ send({
70
+ jsonrpc: '2.0',
71
+ method: 'textDocument/publishDiagnostics',
72
+ params: {
73
+ uri: td.uri,
74
+ diagnostics: [
75
+ {
76
+ range: {start: {line: 4, character: 0}},
77
+ severity: 1,
78
+ source: 'fake',
79
+ message: 'undefined name: x',
80
+ },
81
+ ],
82
+ },
83
+ });
84
+ if (mode !== 'errors') return;
85
+
86
+ setTimeout(() => {
87
+ send({
88
+ jsonrpc: '2.0',
89
+ method: 'textDocument/publishDiagnostics',
90
+ params: {
91
+ uri: td.uri,
92
+ diagnostics: [
93
+ {
94
+ range: {start: {line: 4, character: 0}},
95
+ severity: 1,
96
+ source: 'fake',
97
+ message: 'undefined name: x',
98
+ },
99
+ // Must be filtered out: warnings never reach the model.
100
+ {range: {start: {line: 6}}, severity: 2, message: 'unused import'},
101
+ ],
102
+ },
103
+ });
104
+ }, 40);
105
+ return;
106
+ }
107
+ default:
108
+ return;
109
+ }
110
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * LSP wire framing: `Content-Length: N\r\n\r\n<json>`.
3
+ *
4
+ * Pure on purpose — no process, no I/O, no timers. Framing bugs (a split header,
5
+ * a body arriving in three chunks, a stray `\r\n` after the JSON) are the kind
6
+ * of thing that looks fine until a large diagnostic payload lands, so they get
7
+ * their own testable unit rather than hiding inside the client.
8
+ */
9
+
10
+ /** A single LSP message on the wire, once framed. */
11
+ export interface Frame {
12
+ /** The decoded JSON body. Malformed bodies are surfaced, never silently dropped. */
13
+ body: unknown;
14
+ /** Set when the body could not be parsed, with the raw text for the log. */
15
+ parseError?: string;
16
+ }
17
+
18
+ /**
19
+ * Encode one message for a server's stdin.
20
+ *
21
+ * `JSON.stringify` output is byte-length-safe here: LSP bodies are JSON, and
22
+ * `Content-Length` is defined in **bytes**, so the UTF-8 length is what must be
23
+ * sent — `Buffer.byteLength` rather than `String.length`, or a message containing
24
+ * an em-dash or a non-ASCII path desynchronises the stream permanently.
25
+ */
26
+ export function encodeMessage(payload: unknown): string {
27
+ const json = JSON.stringify(payload);
28
+ const bytes = Buffer.byteLength(json, 'utf8');
29
+ return `Content-Length: ${bytes}\r\n\r\n${json}`;
30
+ }
31
+
32
+ /**
33
+ * Incremental decoder for a byte stream of LSP frames.
34
+ *
35
+ * Feed it whatever `stdout` hands over — headers split mid-line, two messages in
36
+ * one chunk, a body split across three — and it yields whole frames in order.
37
+ * Anything it cannot parse is yielded as a `parseError` frame so the client can
38
+ * log and continue instead of wedging.
39
+ */
40
+ export class FrameDecoder {
41
+ private buffer = Buffer.alloc(0);
42
+
43
+ /** Append a chunk and return every frame that is now complete. */
44
+ push(chunk: Buffer | Uint8Array): Frame[] {
45
+ this.buffer = Buffer.concat([this.buffer, Buffer.from(chunk)]);
46
+ const frames: Frame[] = [];
47
+
48
+ for (;;) {
49
+ const headerEnd = this.buffer.indexOf('\r\n\r\n');
50
+ if (headerEnd === -1) break;
51
+
52
+ const header = this.buffer.subarray(0, headerEnd).toString('ascii');
53
+ const length = parseContentLength(header);
54
+ if (length === null) {
55
+ // A header with no usable Content-Length cannot be framed. Drop the
56
+ // header and report it, rather than waiting forever for a body.
57
+ this.buffer = this.buffer.subarray(headerEnd + 4);
58
+ frames.push({body: null, parseError: `bad header: ${header.slice(0, 120)}`});
59
+ continue;
60
+ }
61
+
62
+ const bodyStart = headerEnd + 4;
63
+ const bodyEnd = bodyStart + length;
64
+ if (this.buffer.length < bodyEnd) break; // body not fully arrived yet
65
+
66
+ const bodyText = this.buffer.subarray(bodyStart, bodyEnd).toString('utf8');
67
+ this.buffer = this.buffer.subarray(bodyEnd);
68
+
69
+ try {
70
+ frames.push({body: JSON.parse(bodyText)});
71
+ } catch (err) {
72
+ frames.push({
73
+ body: null,
74
+ parseError: `bad body: ${err instanceof Error ? err.message : String(err)}`,
75
+ });
76
+ }
77
+ }
78
+
79
+ return frames;
80
+ }
81
+ }
82
+
83
+ /** `Content-Length: 123` → 123, or null when absent/not a non-negative integer. */
84
+ export function parseContentLength(header: string): number | null {
85
+ for (const line of header.split('\r\n')) {
86
+ const match = /^content-length:\s*(\d+)\s*$/i.exec(line.trim());
87
+ if (!match) continue;
88
+ const n = Number(match[1]);
89
+ if (!Number.isSafeInteger(n) || n < 0) return null;
90
+ return n;
91
+ }
92
+ return null;
93
+ }