-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
main.ts
682 lines (603 loc) · 17.2 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
import { type ChildProcess, spawn } from "node:child_process";
import { createRequire } from "node:module";
import { type Socket, connect } from "node:net";
import { delimiter, dirname, isAbsolute } from "node:path";
import {
type ExtensionContext,
type OutputChannel,
RelativePattern,
type TextEditor,
Uri,
commands,
languages,
window,
workspace,
} from "vscode";
import {
type DocumentFilter,
LanguageClient,
type LanguageClientOptions,
type ServerOptions,
type StreamInfo,
} from "vscode-languageclient/node";
import { Commands } from "./commands";
import { syntaxTree } from "./commands/syntaxTree";
import { selectAndDownload, updateToLatest } from "./downloader";
import { Session } from "./session";
import { StatusBar } from "./statusBar";
import { setContextValue } from "./utils";
let client: LanguageClient;
const IN_BIOME_PROJECT = "inBiomeProject";
export async function activate(context: ExtensionContext) {
// If the extension is disabled, abort the activation.
if (!workspace.getConfiguration("biome").get<boolean>("enabled", true)) {
return;
}
const outputChannel = window.createOutputChannel("Biome");
const traceOutputChannel = window.createOutputChannel("Biome Trace");
commands.registerCommand(Commands.StopServer, async () => {
if (!client) {
return;
}
try {
await client.stop();
} catch (error) {
client.error("Stopping client failed", error, "force");
}
});
commands.registerCommand(Commands.RestartLspServer, async () => {
if (!client) {
return;
}
try {
if (client.isRunning()) {
await client.restart();
} else {
await client.start();
}
} catch (error) {
client.error("Restarting client failed", error, "force");
}
});
commands.registerCommand("biome.clearVersionsCache", async () => {
await context.globalState.update("biome_versions_cache", undefined);
});
let server = await getServerPath(context, outputChannel);
// @ts-expect-error
if (!server.command) {
const action = await window.showWarningMessage(
"Could not find Biome in your dependencies. Either add the @biomejs/biome package to your dependencies, or download the Biome binary.",
"Ok",
"Download Biome",
);
if (action === "Download Biome") {
if (!(await selectAndDownload(context, outputChannel))) {
return;
}
}
server = await getServerPath(context, outputChannel);
// @ts-expect-error
if (!server.command) {
return;
}
}
const statusBar = new StatusBar(context, outputChannel);
// @ts-expect-error
await statusBar.setUsingBundledBiome(server.bundled);
const documentSelector: DocumentFilter[] = [
{ language: "javascript", scheme: "file" },
{ language: "javascript", scheme: "untitled" },
{ language: "typescript", scheme: "file" },
{ language: "typescript", scheme: "untitled" },
{ language: "javascriptreact", scheme: "file" },
{ language: "javascriptreact", scheme: "untitled" },
{ language: "typescriptreact", scheme: "file" },
{ language: "typescriptreact", scheme: "untitled" },
{ language: "json", scheme: "file" },
{ language: "json", scheme: "untitled" },
{ language: "jsonc", scheme: "file" },
{ language: "jsonc", scheme: "untitled" },
{ language: "astro", scheme: "file" },
{ language: "astro", scheme: "untitled" },
{ language: "vue", scheme: "file" },
{ language: "vue", scheme: "untitled" },
{ language: "svelte", scheme: "file" },
{ language: "svelte", scheme: "untitled" },
];
const clientOptions: LanguageClientOptions = {
documentSelector,
outputChannel,
traceOutputChannel,
};
const reloadClient = async () => {
// @ts-expect-error
outputChannel.appendLine(`Biome binary found at ${server.command}`);
let destination: Uri | undefined;
// The context.storageURI is only defined when a workspace is opened.
if (context.storageUri) {
destination = Uri.joinPath(
context.storageUri,
`./biome${process.platform === "win32" ? ".exe" : ""}`,
);
// @ts-expect-error
if (server.workspaceDependency) {
try {
// Create the destination if it does not exist.
await workspace.fs.createDirectory(context.storageUri);
outputChannel.appendLine(
`Copying binary to temporary folder: ${destination}`,
);
// @ts-expect-error
await workspace.fs.copy(Uri.file(server.command), destination, {
overwrite: true,
});
} catch (error) {
outputChannel.appendLine(`Error copying file: ${error}`);
destination = undefined;
}
} else {
destination = undefined;
}
}
outputChannel.appendLine(
// @ts-expect-error
`Executing Biome from: ${destination?.fsPath ?? server.command}`,
);
const serverOptions: ServerOptions = createMessageTransports.bind(
undefined,
outputChannel,
// @ts-expect-error
destination?.fsPath ?? server.command,
);
client = new LanguageClient(
"biome_lsp",
"Biome",
serverOptions,
clientOptions,
);
context.subscriptions.push(
client.onDidChangeState((evt) => {
statusBar.setServerState(client, evt.newState);
}),
);
};
await reloadClient();
if (workspace.workspaceFolders?.[0]) {
// Best way to determine package updates. Will work for npm, yarn, pnpm and bun. (Might work for more files also).
// It is not possible to listen node_modules, because it is usually gitignored.
const watcher = workspace.createFileSystemWatcher(
new RelativePattern(workspace.workspaceFolders[0], "*lock*"),
);
context.subscriptions.push(
watcher.onDidChange(async () => {
try {
// When the lockfile changes, reload the biome executable.
outputChannel.appendLine("Reloading biome executable.");
if (client.isRunning()) {
await client.stop();
}
await reloadClient();
if (client.isRunning()) {
await client.restart();
} else {
await client.start();
}
} catch (error) {
outputChannel.appendLine(`Reloading client failed: ${error}`);
}
}),
);
}
const session = new Session(context, client);
const codeDocumentSelector =
client.protocol2CodeConverter.asDocumentSelector(documentSelector);
// we are now in a biome project
setContextValue(IN_BIOME_PROJECT, true);
commands.registerCommand(Commands.UpdateBiome, async (version: string) => {
const result = await window.showInformationMessage(
`Are you sure you want to update Biome (bundled) to ${version}?`,
{
modal: true,
},
"Update",
"Cancel",
);
if (result === "Update") {
await updateToLatest(context, outputChannel);
statusBar.checkForUpdates(outputChannel);
}
});
commands.registerCommand(Commands.ChangeVersion, async () => {
await selectAndDownload(context);
statusBar.checkForUpdates(outputChannel);
});
session.registerCommand(Commands.SyntaxTree, syntaxTree(session));
session.registerCommand(Commands.ServerStatus, () => {
traceOutputChannel.show();
});
const handleActiveTextEditorChanged = (textEditor?: TextEditor) => {
if (!textEditor) {
statusBar.setActive(false);
return;
}
const { document } = textEditor;
statusBar.setActive(languages.match(codeDocumentSelector, document) > 0);
};
context.subscriptions.push(
window.onDidChangeActiveTextEditor(handleActiveTextEditorChanged),
);
handleActiveTextEditorChanged(window.activeTextEditor);
await client.start();
}
type Architecture = "x64" | "arm64";
type PlatformTriplets = {
[P in NodeJS.Platform]?: {
[A in Architecture]: {
triplet: string;
package: string;
};
};
};
const PLATFORMS: PlatformTriplets = {
win32: {
x64: {
triplet: "x86_64-pc-windows-msvc",
package: "@biomejs/cli-win32-x64",
},
arm64: {
triplet: "aarch64-pc-windows-msvc",
package: "@biomejs/cli-win32-arm64",
},
},
darwin: {
x64: {
triplet: "x86_64-apple-darwin",
package: "@biomejs/cli-darwin-x64",
},
arm64: {
triplet: "aarch64-apple-darwin",
package: "@biomejs/cli-darwin-arm64",
},
},
linux: {
x64: {
triplet: "x86_64-unknown-linux-gnu",
package: "@biomejs/cli-linux-x64",
},
arm64: {
triplet: "aarch64-unknown-linux-gnu",
package: "@biomejs/cli-linux-arm64",
},
},
};
async function getServerPath(
context: ExtensionContext,
outputChannel: OutputChannel,
): Promise<
| {
bundled: boolean;
workspaceDependency: boolean | undefined;
command: string | undefined;
}
| undefined
> {
// Only allow the bundled Biome binary in untrusted workspaces
if (!workspace.isTrusted) {
return {
bundled: true,
workspaceDependency: false,
command: await getBundledBinary(context, outputChannel),
};
}
if (process.env.DEBUG_SERVER_PATH) {
if (await fileExists(Uri.file(process.env.DEBUG_SERVER_PATH))) {
outputChannel.appendLine(
`Biome DEBUG_SERVER_PATH detected: ${process.env.DEBUG_SERVER_PATH}`,
);
return {
bundled: false,
workspaceDependency: false,
command: process.env.DEBUG_SERVER_PATH,
};
}
outputChannel.appendLine(
`The DEBUG_SERVER_PATH environment variable points to a non-existing file: ${process.env.DEBUG_SERVER_PATH}`,
);
}
const config = workspace.getConfiguration();
const explicitPath = config.get<string>("biome.lspBin");
if (explicitPath) {
const workspaceRelativePath = await getWorkspaceRelativePath(explicitPath);
if (workspaceRelativePath !== undefined) {
return {
bundled: false,
workspaceDependency: false,
command: workspaceRelativePath,
};
}
outputChannel.appendLine(
`The biome.lspBin setting points to a non-existing file: ${explicitPath}`,
);
}
const workspaceDependency = await getWorkspaceDependency(outputChannel);
if (workspaceDependency) {
return {
bundled: false,
workspaceDependency: true,
command: workspaceDependency,
};
}
if (config.get<boolean | undefined>("biome.searchInPath", true) === true) {
outputChannel.appendLine("Searching for Biome in PATH");
const biomeInPATH = await findBiomeInPath();
if (biomeInPATH) {
outputChannel.appendLine(`Biome found in PATH: ${biomeInPATH.fsPath}`);
return {
bundled: false,
workspaceDependency: false,
command: biomeInPATH.fsPath,
};
}
}
// Last resort
return {
bundled: true,
workspaceDependency: undefined,
command: await getBundledBinary(context, outputChannel),
};
}
/**
* Attempts top resolve the path to the biome binary from the PATH environment variable.
*
* We manually scan all the folders in the path because we may not always have access to
* `which` or `where` on the system, or in the PATH.
*/
async function findBiomeInPath(): Promise<Uri | undefined> {
const path = process.env.PATH;
if (!path) {
return;
}
for (const dir of path.split(delimiter)) {
const biome = Uri.joinPath(
Uri.file(dir),
`biome${process.platform === "win32" ? ".exe" : ""}`,
);
if (await fileExists(biome)) {
return biome;
}
}
}
// Resolve `path` as relative to the workspace root
async function getWorkspaceRelativePath(path: string) {
if (isAbsolute(path)) {
return path;
}
if (!workspace.workspaceFolders) {
return undefined;
}
for (let i = 0; i < workspace.workspaceFolders.length; i++) {
const workspaceFolder = workspace.workspaceFolders[i];
const possiblePath = Uri.joinPath(workspaceFolder.uri, path);
if (await fileExists(possiblePath)) {
return possiblePath.fsPath;
}
}
return undefined;
}
// Tries to resolve a path to `@biomejs/cli-*` binary package from the root of the workspace
async function getWorkspaceDependency(
outputChannel: OutputChannel,
): Promise<string | undefined> {
for (const workspaceFolder of workspace.workspaceFolders ?? []) {
// Check for Yarn PnP and try resolving the Biome binary without a node_modules
// folder first.
for (const ext of ["cjs", "js"]) {
const pnpFile = Uri.joinPath(workspaceFolder.uri, `.pnp.${ext}`);
if (!(await fileExists(pnpFile))) {
continue;
}
outputChannel.appendLine(
`Looks like a Yarn PnP workspace: ${workspaceFolder.uri.fsPath}`,
);
try {
const pnpApi = require(
Uri.joinPath(workspaceFolder.uri, ".pnp.cjs").fsPath,
);
const pkgPath = pnpApi.resolveRequest(
"@biomejs/biome/package.json",
workspaceFolder.uri.fsPath,
);
if (!pkgPath) {
throw new Error("No @biomejs/biome dependency configured");
}
return pnpApi.resolveRequest(
`@biomejs/cli-${process.platform}-${process.arch}/biome${
process.platform === "win32" ? ".exe" : ""
}`,
pkgPath,
);
} catch (err) {
outputChannel.appendLine(
`Could not resolve Biome using Yarn PnP in ${workspaceFolder.uri.fsPath}: ${err}`,
);
}
}
// To resolve the @biomejs/cli-*, which is a transitive dependency of the
// @biomejs/biome package, we need to create a custom require function that
// is scoped to @biomejs/biome. This allows us to reliably resolve the
// package regardless of the package manager used by the user.
try {
const requireFromBiome = createRequire(
require.resolve("@biomejs/biome/package.json", {
paths: [workspaceFolder.uri.fsPath],
}),
);
const binaryPackage = dirname(
requireFromBiome.resolve(
`@biomejs/cli-${process.platform}-${process.arch}/package.json`,
),
);
const biomePath = Uri.file(
`${binaryPackage}/biome${process.platform === "win32" ? ".exe" : ""}`,
);
if (await fileExists(biomePath)) {
return biomePath.fsPath;
}
} catch {
outputChannel.appendLine(
`Could not resolve Biome in the dependencies of workspace folder: ${workspaceFolder.uri.fsPath}`,
);
}
}
return undefined;
}
// Returns the path of the binary distribution of Biome included in the bundle of the extension
async function getBundledBinary(
context: ExtensionContext,
outputChannel: OutputChannel,
) {
const bundlePath = Uri.joinPath(
context.globalStorageUri,
"server",
`biome${process.platform === "win32" ? ".exe" : ""}`,
);
const bundleExists = await fileExists(bundlePath);
if (!bundleExists) {
outputChannel.appendLine(
"Extension bundle does not include the prebuilt binary",
);
return undefined;
}
return bundlePath.fsPath;
}
async function fileExists(path: Uri) {
try {
await workspace.fs.stat(path);
return true;
} catch (err) {
// @ts-expect-error
if (err.code === "ENOENT" || err.code === "FileNotFound") {
return false;
}
throw err;
}
}
interface MutableBuffer {
content: string;
}
function collectStream(
outputChannel: OutputChannel,
process: ChildProcess,
key: "stdout" | "stderr",
buffer: MutableBuffer,
) {
return new Promise<void>((resolve, reject) => {
const stream = process[key];
if (stream == null) {
reject(new Error(`Stream ${key} is null`));
return;
}
stream.setEncoding("utf-8");
stream.on("error", (err) => {
outputChannel.appendLine(`[cli-${key}] error`);
reject(err);
});
stream.on("close", () => {
outputChannel.appendLine(`[cli-${key}] close`);
resolve();
});
stream.on("finish", () => {
outputChannel.appendLine(`[cli-${key}] finish`);
resolve();
});
stream.on("end", () => {
outputChannel.appendLine(`[cli-${key}] end`);
resolve();
});
stream.on("data", (data) => {
outputChannel.appendLine(`[cli-${key}] data ${data.length}`);
buffer.content += data;
});
});
}
function withTimeout(promise: Promise<void>, duration: number) {
return Promise.race([
promise,
new Promise<void>((resolve) => setTimeout(resolve, duration)),
]);
}
async function getSocket(
outputChannel: OutputChannel,
command: string,
): Promise<string> {
const process = spawn(command, ["__print_socket"], {
stdio: [null, "pipe", "pipe"],
});
const stdout = { content: "" };
const stderr = { content: "" };
const stdoutPromise = collectStream(outputChannel, process, "stdout", stdout);
const stderrPromise = collectStream(outputChannel, process, "stderr", stderr);
const exitCode = await new Promise<number>((resolve, reject) => {
process.on("error", reject);
process.on("exit", (code) => {
outputChannel.appendLine(`[cli] exit ${code}`);
// @ts-expect-error
resolve(code);
});
process.on("close", (code) => {
outputChannel.appendLine(`[cli] close ${code}`);
// @ts-expect-error
resolve(code);
});
});
await Promise.all([
withTimeout(stdoutPromise, 1000),
withTimeout(stderrPromise, 1000),
]);
const pipeName = stdout.content.trimEnd();
if (exitCode !== 0 || pipeName.length === 0) {
let message = `Command "${command} __print_socket" exited with code ${exitCode}`;
if (stderr.content.length > 0) {
message += `\nOutput:\n${stderr.content}`;
}
throw new Error(message);
}
outputChannel.appendLine(`Connecting to "${pipeName}" ...`);
return pipeName;
}
function wrapConnectionError(err: Error, path: string): Error {
return Object.assign(
new Error(
`Could not connect to the Biome server at "${path}": ${err.message}`,
),
{ name: err.name, stack: err.stack },
);
}
async function createMessageTransports(
outputChannel: OutputChannel,
command: string,
): Promise<StreamInfo> {
const path = await getSocket(outputChannel, command);
let socket: Socket;
try {
socket = connect(path);
} catch (err) {
if (err instanceof Error) {
throw wrapConnectionError(err, path);
}
}
await new Promise((resolve, reject) => {
socket.once("ready", resolve);
socket.once("error", (err) => {
reject(wrapConnectionError(err, path));
});
});
// @ts-expect-error
return { writer: socket, reader: socket };
}
export function deactivate(): Thenable<void> | undefined {
if (!client) {
return undefined;
}
return client.stop();
}