zidane-gui 7.1.10 → 7.2.3

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,598 @@
1
+ import { spawn } from "node:child_process";
2
+ import { join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { m as makeToolContext } from "./chunks/context-77_UZfgL.js";
5
+ import { createRequire } from "node:module";
6
+ import "node:fs/promises";
7
+ class JsonRpcConnection {
8
+ #child;
9
+ /** Unparsed chunks; concatenated only when a frame boundary needs it (no O(n²) concat per chunk). */
10
+ #chunks = [];
11
+ #buffered = 0;
12
+ #nextId = 1;
13
+ #pending = /* @__PURE__ */ new Map();
14
+ #notifications = /* @__PURE__ */ new Map();
15
+ #requests = /* @__PURE__ */ new Map();
16
+ #closed = false;
17
+ onClose = null;
18
+ constructor(child) {
19
+ this.#child = child;
20
+ child.stdout?.on("data", (chunk) => this.#onData(chunk));
21
+ const close = () => {
22
+ if (this.#closed) return;
23
+ this.#closed = true;
24
+ for (const p of this.#pending.values()) {
25
+ clearTimeout(p.timer);
26
+ p.reject(new Error("connection closed"));
27
+ }
28
+ this.#pending.clear();
29
+ this.onClose?.();
30
+ };
31
+ child.on("exit", close);
32
+ child.on("error", close);
33
+ }
34
+ get closed() {
35
+ return this.#closed;
36
+ }
37
+ onNotification(method, handler) {
38
+ this.#notifications.set(method, handler);
39
+ }
40
+ /** Server → client requests (e.g. `client/registerCapability`); default replies null. */
41
+ onRequest(method, handler) {
42
+ this.#requests.set(method, handler);
43
+ }
44
+ notify(method, params) {
45
+ this.#send({ jsonrpc: "2.0", method, params });
46
+ }
47
+ request(method, params, timeoutMs = 15e3) {
48
+ return this.requestCancellable(method, params, timeoutMs).promise;
49
+ }
50
+ /** A request the caller may abandon: `cancel()` rejects locally and tells the server (`$/cancelRequest`). */
51
+ requestCancellable(method, params, timeoutMs = 15e3) {
52
+ if (this.#closed) return { promise: Promise.reject(new Error("connection closed")), cancel: () => void 0 };
53
+ const id = this.#nextId++;
54
+ let settled = false;
55
+ const promise = new Promise((resolve, reject) => {
56
+ const timer = setTimeout(() => {
57
+ this.#pending.delete(id);
58
+ settled = true;
59
+ reject(new Error(`${method} timed out`));
60
+ }, timeoutMs);
61
+ this.#pending.set(id, {
62
+ resolve: (v) => {
63
+ settled = true;
64
+ resolve(v);
65
+ },
66
+ reject: (e) => {
67
+ settled = true;
68
+ reject(e);
69
+ },
70
+ timer
71
+ });
72
+ this.#send({ jsonrpc: "2.0", id, method, params });
73
+ });
74
+ const cancel = () => {
75
+ const p = this.#pending.get(id);
76
+ if (!p || settled) return;
77
+ this.#pending.delete(id);
78
+ clearTimeout(p.timer);
79
+ p.reject(new Error("cancelled"));
80
+ this.notify("$/cancelRequest", { id });
81
+ };
82
+ return { promise, cancel };
83
+ }
84
+ #send(message) {
85
+ if (this.#closed || !this.#child.stdin?.writable) return;
86
+ const body = Buffer.from(JSON.stringify(message), "utf8");
87
+ this.#child.stdin.write(`Content-Length: ${body.length}\r
88
+ \r
89
+ `);
90
+ this.#child.stdin.write(body);
91
+ }
92
+ #onData(chunk) {
93
+ this.#chunks.push(chunk);
94
+ this.#buffered += chunk.length;
95
+ for (; ; ) {
96
+ const buffer = this.#chunks.length === 1 ? this.#chunks[0] : Buffer.concat(this.#chunks, this.#buffered);
97
+ const headerEnd = buffer.indexOf("\r\n\r\n");
98
+ if (headerEnd === -1) {
99
+ this.#chunks = buffer.length ? [buffer] : [];
100
+ this.#buffered = buffer.length;
101
+ return;
102
+ }
103
+ const header = buffer.subarray(0, headerEnd).toString("ascii");
104
+ const m = /Content-Length:\s*(\d+)/i.exec(header);
105
+ if (!m) {
106
+ this.#setRest(buffer.subarray(headerEnd + 4));
107
+ continue;
108
+ }
109
+ const length = Number(m[1]);
110
+ const start = headerEnd + 4;
111
+ if (buffer.length < start + length) {
112
+ this.#setRest(buffer);
113
+ return;
114
+ }
115
+ const body = buffer.subarray(start, start + length).toString("utf8");
116
+ this.#setRest(buffer.subarray(start + length));
117
+ this.#dispatch(body);
118
+ }
119
+ }
120
+ #setRest(rest) {
121
+ this.#chunks = rest.length ? [rest] : [];
122
+ this.#buffered = rest.length;
123
+ }
124
+ #dispatch(body) {
125
+ let msg;
126
+ try {
127
+ msg = JSON.parse(body);
128
+ } catch {
129
+ return;
130
+ }
131
+ if (msg.method !== void 0) {
132
+ if (msg.id !== void 0) {
133
+ const handler = this.#requests.get(msg.method);
134
+ let result = null;
135
+ try {
136
+ result = handler ? handler(msg.params) : null;
137
+ } catch {
138
+ result = null;
139
+ }
140
+ this.#send({ jsonrpc: "2.0", id: msg.id, result });
141
+ } else {
142
+ this.#notifications.get(msg.method)?.(msg.params);
143
+ }
144
+ return;
145
+ }
146
+ if (typeof msg.id === "number") {
147
+ const p = this.#pending.get(msg.id);
148
+ if (!p) return;
149
+ this.#pending.delete(msg.id);
150
+ clearTimeout(p.timer);
151
+ if (msg.error) p.reject(new Error(msg.error.message ?? "request failed"));
152
+ else p.resolve(msg.result);
153
+ }
154
+ }
155
+ }
156
+ const require$1 = createRequire(import.meta.url);
157
+ function resolveBundled(specifier) {
158
+ try {
159
+ return require$1.resolve(specifier).replace("app.asar/", "app.asar.unpacked/");
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+ const LANGUAGE_SERVERS = [
165
+ {
166
+ id: "typescript",
167
+ label: "TypeScript (typescript-language-server)",
168
+ extensions: ["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"],
169
+ languageIds: {
170
+ ts: "typescript",
171
+ mts: "typescript",
172
+ cts: "typescript",
173
+ tsx: "typescriptreact",
174
+ js: "javascript",
175
+ mjs: "javascript",
176
+ cjs: "javascript",
177
+ jsx: "javascriptreact"
178
+ },
179
+ signals: ["tsconfig.json", "jsconfig.json", "package.json"],
180
+ binary: "typescript-language-server",
181
+ args: ["--stdio"],
182
+ install: "npm i -D typescript-language-server typescript",
183
+ // Only what the viewer uses: no typings acquisition (network), no inlay
184
+ // hints, no completion detail, quiet logs. Keeps tsserver's idle work down.
185
+ initializationOptions: {
186
+ hostInfo: "zidane",
187
+ disableAutomaticTypingAcquisition: true,
188
+ tsserver: { logVerbosity: "off" },
189
+ preferences: {
190
+ includeInlayParameterNameHints: "none",
191
+ includeCompletionsForModuleExports: false,
192
+ includeCompletionsWithInsertText: false,
193
+ providePrefixAndSuffixTextForRename: false
194
+ }
195
+ },
196
+ // We ship typescript-language-server; run it with Electron as node and
197
+ // point it at the project's TypeScript when there is one (its version
198
+ // decides the diagnostics), else at ours.
199
+ bundled: async (ctx) => {
200
+ const cli = resolveBundled("typescript-language-server/lib/cli.mjs");
201
+ if (!cli) return null;
202
+ const projectTs = join(ctx.cwd, "node_modules", "typescript", "lib", "tsserver.js");
203
+ const tsserver = await ctx.hasFile("node_modules/typescript/lib/tsserver.js") ? projectTs : resolveBundled("typescript/lib/tsserver.js");
204
+ return {
205
+ bin: process.execPath,
206
+ args: [cli, "--stdio"],
207
+ env: { ELECTRON_RUN_AS_NODE: "1" },
208
+ // v6 dropped `--tsserver-path`; the path goes through initializationOptions.
209
+ ...tsserver ? { initializationOptions: { tsserver: { path: tsserver, logVerbosity: "off" } } } : {}
210
+ };
211
+ }
212
+ },
213
+ {
214
+ id: "pyright",
215
+ label: "Python (pyright)",
216
+ extensions: ["py", "pyi"],
217
+ languageIds: { py: "python", pyi: "python" },
218
+ signals: ["pyproject.toml", "setup.py", "requirements.txt", "pyrightconfig.json"],
219
+ binary: "pyright-langserver",
220
+ args: ["--stdio"],
221
+ install: "npm i -g pyright (or pip install pyright)"
222
+ },
223
+ {
224
+ id: "rust-analyzer",
225
+ label: "Rust (rust-analyzer)",
226
+ extensions: ["rs"],
227
+ languageIds: { rs: "rust" },
228
+ signals: ["Cargo.toml"],
229
+ binary: "rust-analyzer",
230
+ args: [],
231
+ install: "rustup component add rust-analyzer"
232
+ },
233
+ {
234
+ id: "gopls",
235
+ label: "Go (gopls)",
236
+ extensions: ["go"],
237
+ languageIds: { go: "go" },
238
+ signals: ["go.mod"],
239
+ binary: "gopls",
240
+ args: ["serve"],
241
+ install: "go install golang.org/x/tools/gopls@latest"
242
+ }
243
+ ];
244
+ function serverFor(path, servers = LANGUAGE_SERVERS) {
245
+ const ext = path.split(".").pop()?.toLowerCase() ?? "";
246
+ return servers.find((s) => s.extensions.includes(ext)) ?? null;
247
+ }
248
+ function languageIdFor(server, path) {
249
+ const ext = path.split(".").pop()?.toLowerCase() ?? "";
250
+ return server.languageIds?.[ext] ?? ext;
251
+ }
252
+ async function detectServer(ctx, server, override) {
253
+ if (!await ctx.hasFile(...server.signals)) return null;
254
+ if (override?.trim()) {
255
+ const [bin2, ...args] = override.trim().split(/\s+/);
256
+ return { bin: bin2, args };
257
+ }
258
+ const bin = await ctx.resolveBin(server.binary);
259
+ if (bin) return { bin, args: server.args };
260
+ const bundled = await server.bundled?.(ctx).catch(() => null);
261
+ return bundled ?? { missing: `${server.binary} not found. ${server.install}` };
262
+ }
263
+ const SEVERITY = { 1: "error", 2: "warning", 3: "info", 4: "hint" };
264
+ const MAX_RESTARTS = 3;
265
+ const START_COOLDOWN_MS = 6e4;
266
+ const MAX_INCREMENTAL_CHANGES = 64;
267
+ class ServerClient {
268
+ cwd;
269
+ server;
270
+ #conn = null;
271
+ #ready = null;
272
+ #docs = /* @__PURE__ */ new Map();
273
+ #diagnostics = /* @__PURE__ */ new Map();
274
+ #idleTimer = null;
275
+ /** One in-flight hover / definition at a time: a newer one cancels the older on the server. */
276
+ #inflight = /* @__PURE__ */ new Map();
277
+ /** Server accepts incremental `didChange` (textDocumentSync 2). */
278
+ #incremental = false;
279
+ #restarts = 0;
280
+ /** After a failed spawn/initialize, do not retry before this time. */
281
+ #retryAfter = 0;
282
+ #command;
283
+ #onDown;
284
+ #idleMs;
285
+ #emit;
286
+ lastError = null;
287
+ constructor(cwd, server, command, idleMs, onDown, emit) {
288
+ this.#emit = emit;
289
+ this.cwd = cwd;
290
+ this.server = server;
291
+ this.#command = command;
292
+ this.#idleMs = idleMs;
293
+ this.#onDown = onDown;
294
+ }
295
+ get running() {
296
+ return this.#conn !== null && !this.#conn.closed;
297
+ }
298
+ get openCount() {
299
+ return this.#docs.size;
300
+ }
301
+ diagnosticsFor(path) {
302
+ return this.#diagnostics.get(path) ?? [];
303
+ }
304
+ #uri(path) {
305
+ return pathToFileURL(join(this.cwd, path)).href;
306
+ }
307
+ #pathOf(uri) {
308
+ const root = pathToFileURL(this.cwd).href.replace(/\/$/, "") + "/";
309
+ if (!uri.startsWith(root)) return null;
310
+ return decodeURIComponent(uri.slice(root.length));
311
+ }
312
+ #start() {
313
+ if (this.#ready) return this.#ready;
314
+ this.#ready = (async () => {
315
+ const child = spawn(this.#command.bin, [...this.#command.args], {
316
+ cwd: this.cwd,
317
+ stdio: ["pipe", "pipe", "pipe"],
318
+ env: { ...process.env, ...this.#command.env }
319
+ });
320
+ const conn = new JsonRpcConnection(child);
321
+ this.#conn = conn;
322
+ child.stderr?.on("data", (d) => {
323
+ this.lastError = d.toString("utf8").trim().slice(-500) || this.lastError;
324
+ });
325
+ conn.onNotification("textDocument/publishDiagnostics", (params) => this.#onPublish(params));
326
+ conn.onRequest("window/workDoneProgress/create", () => null);
327
+ conn.onRequest("client/registerCapability", () => null);
328
+ conn.onRequest("workspace/configuration", (params) => {
329
+ const items = params?.items ?? [];
330
+ return items.map(() => null);
331
+ });
332
+ conn.onClose = () => {
333
+ this.#conn = null;
334
+ this.#ready = null;
335
+ this.#diagnostics.clear();
336
+ const hadDocs = this.#docs.size > 0;
337
+ this.#docs.clear();
338
+ if (hadDocs && this.#restarts < MAX_RESTARTS) {
339
+ this.#restarts++;
340
+ } else if (hadDocs) {
341
+ this.lastError = `stopped after ${MAX_RESTARTS} crashes${this.lastError ? `: ${this.lastError}` : ""}`;
342
+ }
343
+ this.#onDown();
344
+ };
345
+ const rootUri = pathToFileURL(this.cwd).href;
346
+ const init = await conn.request(
347
+ "initialize",
348
+ {
349
+ processId: process.pid,
350
+ rootUri,
351
+ workspaceFolders: [{ uri: rootUri, name: this.cwd.split("/").pop() ?? "workspace" }],
352
+ capabilities: {
353
+ textDocument: {
354
+ publishDiagnostics: { relatedInformation: false },
355
+ hover: { contentFormat: ["markdown", "plaintext"] },
356
+ definition: { linkSupport: true },
357
+ synchronization: { didSave: false, willSave: false }
358
+ },
359
+ workspace: { configuration: true, workspaceFolders: true }
360
+ },
361
+ initializationOptions: mergeInit(this.server.initializationOptions, this.#command.initializationOptions)
362
+ },
363
+ 3e4
364
+ );
365
+ const sync = init?.capabilities?.textDocumentSync;
366
+ this.#incremental = sync === 2 || typeof sync === "object" && sync?.change === 2;
367
+ conn.notify("initialized", {});
368
+ })();
369
+ this.#ready.catch((err) => {
370
+ this.#ready = null;
371
+ this.#retryAfter = Date.now() + START_COOLDOWN_MS;
372
+ this.lastError = err instanceof Error ? err.message : String(err);
373
+ });
374
+ return this.#ready;
375
+ }
376
+ #onPublish(params) {
377
+ const p = params;
378
+ const path = this.#pathOf(p.uri);
379
+ if (!path) return;
380
+ const items = p.diagnostics.map((d) => ({
381
+ path,
382
+ line: d.range.start.line + 1,
383
+ column: d.range.start.character + 1,
384
+ endLine: d.range.end.line + 1,
385
+ endColumn: d.range.end.character + 1,
386
+ severity: SEVERITY[d.severity ?? 1] ?? "error",
387
+ message: d.message,
388
+ source: d.source ?? this.server.id,
389
+ ...d.code !== void 0 ? { code: String(d.code) } : {}
390
+ }));
391
+ this.#diagnostics.set(path, items);
392
+ this.#emit({ kind: "diagnostics", cwd: this.cwd, path, diagnostics: items });
393
+ }
394
+ #touch() {
395
+ if (this.#idleTimer) clearTimeout(this.#idleTimer);
396
+ if (this.#docs.size > 0) return;
397
+ this.#idleTimer = setTimeout(() => void this.stop(), this.#idleMs);
398
+ }
399
+ async open(path, text, changes) {
400
+ if (this.#restarts >= MAX_RESTARTS && !this.running) return;
401
+ if (!this.running && Date.now() < this.#retryAfter) return;
402
+ await this.#start().catch(() => void 0);
403
+ const conn = this.#conn;
404
+ if (!conn) return;
405
+ const existing = this.#docs.get(path);
406
+ if (existing) {
407
+ if (existing.text === text) return;
408
+ existing.version++;
409
+ existing.text = text;
410
+ const incremental = this.#incremental && changes && changes.length > 0 && changes.length <= MAX_INCREMENTAL_CHANGES;
411
+ conn.notify("textDocument/didChange", {
412
+ textDocument: { uri: this.#uri(path), version: existing.version },
413
+ contentChanges: incremental ? changes : [{ text }]
414
+ });
415
+ } else {
416
+ this.#docs.set(path, { version: 1, text });
417
+ conn.notify("textDocument/didOpen", {
418
+ textDocument: { uri: this.#uri(path), languageId: languageIdFor(this.server, path), version: 1, text }
419
+ });
420
+ }
421
+ this.#touch();
422
+ }
423
+ close(path) {
424
+ if (!this.#docs.delete(path)) return;
425
+ this.#conn?.notify("textDocument/didClose", { textDocument: { uri: this.#uri(path) } });
426
+ this.#diagnostics.delete(path);
427
+ this.#touch();
428
+ }
429
+ #positional(kind, path, line, character) {
430
+ if (!this.#conn || !this.#docs.has(path)) return Promise.resolve(null);
431
+ this.#inflight.get(kind)?.();
432
+ const { promise, cancel } = this.#conn.requestCancellable(
433
+ `textDocument/${kind}`,
434
+ { textDocument: { uri: this.#uri(path) }, position: { line: line - 1, character: character - 1 } },
435
+ 5e3
436
+ );
437
+ this.#inflight.set(kind, cancel);
438
+ return promise.catch(() => null).finally(() => {
439
+ if (this.#inflight.get(kind) === cancel) this.#inflight.delete(kind);
440
+ });
441
+ }
442
+ async definition(path, line, character) {
443
+ return locationsIn(this.cwd, await this.#positional("definition", path, line, character));
444
+ }
445
+ async hover(path, line, character) {
446
+ const res = await this.#positional("hover", path, line, character);
447
+ return res ? hoverText(res.contents) : null;
448
+ }
449
+ async stop() {
450
+ if (this.#idleTimer) clearTimeout(this.#idleTimer);
451
+ const conn = this.#conn;
452
+ if (!conn) return;
453
+ this.#docs.clear();
454
+ this.#diagnostics.clear();
455
+ this.#conn = null;
456
+ this.#ready = null;
457
+ await conn.request("shutdown", null, 3e3).catch(() => void 0);
458
+ conn.notify("exit");
459
+ }
460
+ }
461
+ function mergeInit(base, extra) {
462
+ const out = { ...base ?? {} };
463
+ for (const [k, v] of Object.entries(extra ?? {})) {
464
+ const prev = out[k];
465
+ out[k] = v && typeof v === "object" && !Array.isArray(v) && prev && typeof prev === "object" && !Array.isArray(prev) ? { ...prev, ...v } : v;
466
+ }
467
+ return out;
468
+ }
469
+ function locationsIn(cwd, res) {
470
+ const root = pathToFileURL(cwd).href.replace(/\/$/, "") + "/";
471
+ const list = Array.isArray(res) ? res : res ? [res] : [];
472
+ const out = [];
473
+ for (const item of list) {
474
+ const uri = item.targetUri ?? item.uri;
475
+ const range = item.targetSelectionRange ?? item.targetRange ?? item.range;
476
+ if (!uri || !range || !uri.startsWith(root)) continue;
477
+ out.push({
478
+ path: decodeURIComponent(uri.slice(root.length)),
479
+ line: range.start.line + 1,
480
+ column: range.start.character + 1
481
+ });
482
+ }
483
+ return out;
484
+ }
485
+ function hoverText(contents) {
486
+ if (!contents) return null;
487
+ if (typeof contents === "string") return contents.trim() || null;
488
+ if (Array.isArray(contents)) {
489
+ const parts = contents.map((c) => hoverText(c)).filter((c) => c !== null);
490
+ return parts.length ? parts.join("\n\n") : null;
491
+ }
492
+ const o = contents;
493
+ if (typeof o.value === "string") {
494
+ const v = o.value.trim();
495
+ if (!v) return null;
496
+ return o.language ? `\`\`\`${o.language}
497
+ ${v}
498
+ \`\`\`` : v;
499
+ }
500
+ return null;
501
+ }
502
+ class LspManager {
503
+ #clients = /* @__PURE__ */ new Map();
504
+ #options = { idleMs: 5 * 6e4, overrides: {} };
505
+ #emit;
506
+ constructor(emit) {
507
+ this.#emit = emit;
508
+ }
509
+ configure(options) {
510
+ this.#options = { ...this.#options, ...options };
511
+ }
512
+ async #clientFor(cwd, path) {
513
+ const server = serverFor(path);
514
+ if (!server) return null;
515
+ const key = `${cwd}\0${server.id}`;
516
+ const existing = this.#clients.get(key);
517
+ if (existing) return existing;
518
+ const ctx = makeToolContext(cwd, 1e4);
519
+ const detected = await detectServer(ctx, server, this.#options.overrides[server.id]);
520
+ if (!detected || "missing" in detected) return null;
521
+ const client = new ServerClient(
522
+ cwd,
523
+ server,
524
+ detected,
525
+ this.#options.idleMs,
526
+ () => {
527
+ },
528
+ this.#emit
529
+ );
530
+ this.#clients.set(key, client);
531
+ return client;
532
+ }
533
+ async open(cwd, path, text, changes) {
534
+ const client = await this.#clientFor(cwd, path);
535
+ if (!client) return [];
536
+ await client.open(path, text, changes).catch(() => void 0);
537
+ return client.diagnosticsFor(path);
538
+ }
539
+ close(cwd, path) {
540
+ const server = serverFor(path);
541
+ if (!server) return;
542
+ this.#clients.get(`${cwd}\0${server.id}`)?.close(path);
543
+ }
544
+ async definition(cwd, path, line, character) {
545
+ const server = serverFor(path);
546
+ if (!server) return [];
547
+ const client = this.#clients.get(`${cwd}\0${server.id}`);
548
+ return client ? client.definition(path, line, character) : [];
549
+ }
550
+ async hover(cwd, path, line, character) {
551
+ const server = serverFor(path);
552
+ if (!server) return null;
553
+ const client = this.#clients.get(`${cwd}\0${server.id}`);
554
+ return client ? client.hover(path, line, character) : null;
555
+ }
556
+ async list(cwd) {
557
+ const ctx = makeToolContext(cwd, 1e4);
558
+ return Promise.all(
559
+ LANGUAGE_SERVERS.map(async (server) => {
560
+ const d = await detectServer(ctx, server, this.#options.overrides[server.id]);
561
+ const client = this.#clients.get(`${cwd}\0${server.id}`);
562
+ const base = { id: server.id, label: server.label, install: server.install };
563
+ if (!d) return { ...base, status: "absent" };
564
+ if ("missing" in d) return { ...base, status: "missing", detail: d.missing };
565
+ return {
566
+ ...base,
567
+ status: client?.running ? "running" : client?.lastError ? "failed" : "ready",
568
+ detail: [d.bin, ...d.args].join(" "),
569
+ ...client?.openCount ? { openDocuments: client.openCount } : {},
570
+ ...client?.lastError ? { lastError: client.lastError } : {}
571
+ };
572
+ })
573
+ );
574
+ }
575
+ async stopAll() {
576
+ await Promise.all([...this.#clients.values()].map((c) => c.stop()));
577
+ this.#clients.clear();
578
+ }
579
+ }
580
+ const port = process.parentPort;
581
+ const manager = new LspManager((event) => port.postMessage({ event }));
582
+ port.on("message", (message) => {
583
+ const req = message.data;
584
+ if (!req || typeof req.id !== "number") return;
585
+ const fn = manager[req.method];
586
+ Promise.resolve().then(
587
+ () => typeof fn === "function" ? fn.apply(manager, req.args) : Promise.reject(new Error(`unknown method ${String(req.method)}`))
588
+ ).then(
589
+ (result) => port.postMessage({ id: req.id, ok: true, result }),
590
+ (err) => port.postMessage({ id: req.id, ok: false, error: err instanceof Error ? err.message : String(err) })
591
+ );
592
+ });
593
+ process.on("uncaughtException", (err) => {
594
+ port.postMessage({ event: { kind: "log", level: "error", message: `lsp host: ${err.message}` } });
595
+ });
596
+ process.on("unhandledRejection", (reason) => {
597
+ port.postMessage({ event: { kind: "log", level: "error", message: `lsp host: ${String(reason)}` } });
598
+ });
@@ -151,6 +151,24 @@ const api = {
151
151
  inline: (cwd, text, cursor, sessionId) => ipcRenderer.invoke("autocomplete:inline", cwd, text, cursor, sessionId),
152
152
  onSuggestChanged: (cb) => subscribe("suggest:changed", cb)
153
153
  },
154
+ workspace: {
155
+ list: (cwd, options) => ipcRenderer.invoke("workspace:list", cwd, options),
156
+ read: (cwd, path) => ipcRenderer.invoke("workspace:read", cwd, path),
157
+ write: (cwd, path, contents, expectedMtimeMs) => ipcRenderer.invoke("workspace:write", cwd, path, contents, expectedMtimeMs),
158
+ diagnosticsTools: (cwd) => ipcRenderer.invoke("workspace:diagnosticsTools", cwd),
159
+ diagnosticsInvalidate: (cwd) => ipcRenderer.invoke("workspace:diagnosticsInvalidate", cwd),
160
+ lspConfigure: (opts) => ipcRenderer.invoke("workspace:lspConfigure", opts),
161
+ lspServers: (cwd) => ipcRenderer.invoke("workspace:lspServers", cwd),
162
+ lspOpen: (cwd, path, text, changes) => ipcRenderer.invoke("workspace:lspOpen", cwd, path, text, changes),
163
+ lspClose: (cwd, path) => ipcRenderer.invoke("workspace:lspClose", cwd, path),
164
+ lspDefinition: (cwd, path, line, column) => ipcRenderer.invoke("workspace:lspDefinition", cwd, path, line, column),
165
+ lspHover: (cwd, path, line, column) => ipcRenderer.invoke("workspace:lspHover", cwd, path, line, column),
166
+ diagnostics: (cwd, paths, opts) => ipcRenderer.invoke("workspace:diagnostics", cwd, paths, opts),
167
+ gitStatus: (cwd) => ipcRenderer.invoke("workspace:gitStatus", cwd),
168
+ // Infinity does not survive structured clone; null stands for it.
169
+ gitDiff: (cwd, path, context) => ipcRenderer.invoke("workspace:gitDiff", cwd, path, context === Infinity ? null : context),
170
+ gitShowHead: (cwd, path) => ipcRenderer.invoke("workspace:gitShowHead", cwd, path)
171
+ },
154
172
  panels: {
155
173
  list: (cwd) => ipcRenderer.invoke("panels:list", cwd),
156
174
  load: (cwd, panelId, ctx) => ipcRenderer.invoke("panels:load", cwd, panelId, ctx),
@@ -158,6 +176,12 @@ const api = {
158
176
  watch: (cwd, panelId) => ipcRenderer.invoke("panels:watch", cwd, panelId),
159
177
  unwatch: (cwd, panelId) => ipcRenderer.invoke("panels:unwatch", cwd, panelId)
160
178
  },
179
+ palette: {
180
+ list: (cwd, ctx) => ipcRenderer.invoke("palette:list", cwd, ctx),
181
+ run: (cwd, source, itemId, ctx) => ipcRenderer.invoke("palette:run", cwd, source, itemId, ctx),
182
+ watch: (cwd) => ipcRenderer.invoke("palette:watch", cwd),
183
+ unwatch: (cwd) => ipcRenderer.invoke("palette:unwatch", cwd)
184
+ },
161
185
  extensions: {
162
186
  list: (cwd) => ipcRenderer.invoke("extensions:list", cwd),
163
187
  completionProviders: (cwd) => ipcRenderer.invoke("extensions:completionProviders", cwd),