-
-
Notifications
You must be signed in to change notification settings - Fork 523
/
Copy pathmain.ts
451 lines (389 loc) · 11.4 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
import { type ChildProcess, spawn } from "child_process";
import { type Socket, connect } from "net";
import { dirname, isAbsolute } from "path";
import { TextDecoder, promisify } from "util";
import {
ExtensionContext,
OutputChannel,
TextEditor,
Uri,
languages,
window,
workspace,
} from "vscode";
import {
DocumentFilter,
LanguageClient,
LanguageClientOptions,
ServerOptions,
StreamInfo,
} from "vscode-languageclient/node";
import { Commands } from "./commands";
import { syntaxTree } from "./commands/syntaxTree";
import { Session } from "./session";
import { StatusBar } from "./statusBar";
import { setContextValue } from "./utils";
import resolveImpl = require("resolve/async");
import { createRequire } from "module";
import type * as resolve from "resolve";
const resolveAsync = promisify<string, resolve.AsyncOpts, string | undefined>(
resolveImpl,
);
let client: LanguageClient;
const IN_BIOME_PROJECT = "inBiomeProject";
export async function activate(context: ExtensionContext) {
const outputChannel = window.createOutputChannel("Biome");
const traceOutputChannel = window.createOutputChannel("Biome Trace");
const requiresConfiguration = workspace
.getConfiguration("biome")
.get<boolean>("requireConfiguration");
// If the extension requires a configuration file to be present, we attempt to
// locate it. If a config file cannot be found, we do not go any further.
if (requiresConfiguration) {
outputChannel.appendLine("Configuration file required, looking for one.");
// TODO: Stop looking for rome.json when we reach biome v2.0
const configFiles = await workspace.findFiles("**/{biome,rome}.json");
if (configFiles.length === 0) {
outputChannel.appendLine(
"No config file found, disabling Biome extension",
);
return;
}
outputChannel.appendLine(
`Config file found at ${configFiles[0].fsPath}, enabling Biome extension`,
);
}
const command = await getServerPath(context, outputChannel);
if (!command) {
await window.showErrorMessage(
"The Biome extensions doesn't ship with prebuilt binaries for your platform yet. " +
"You can still use it by cloning the biomejs/biome repo from GitHub to build the LSP " +
"yourself and use it with this extension with the biome.lspBin setting",
);
return;
}
outputChannel.appendLine(`Using Biome from ${command}`);
const statusBar = new StatusBar();
const serverOptions: ServerOptions = createMessageTransports.bind(
undefined,
outputChannel,
command,
);
const documentSelector: DocumentFilter[] = [
{ language: "javascript", scheme: "file" },
{ language: "typescript", scheme: "file" },
{ language: "javascriptreact", scheme: "file" },
{ language: "typescriptreact", scheme: "file" },
{ language: "json", scheme: "file" },
{ language: "jsonc", scheme: "file" },
];
const clientOptions: LanguageClientOptions = {
documentSelector,
outputChannel,
traceOutputChannel,
};
client = new LanguageClient(
"biome_lsp",
"Biome",
serverOptions,
clientOptions,
);
const session = new Session(context, client);
const codeDocumentSelector =
client.protocol2CodeConverter.asDocumentSelector(documentSelector);
// we are now in a biome project
setContextValue(IN_BIOME_PROJECT, true);
session.registerCommand(Commands.SyntaxTree, syntaxTree(session));
session.registerCommand(Commands.ServerStatus, () => {
traceOutputChannel.show();
});
session.registerCommand(Commands.RestartLspServer, async () => {
try {
if (client.isRunning()) {
await client.restart();
} else {
await client.start();
}
} catch (error) {
client.error("Restarting client failed", error, "force");
}
});
context.subscriptions.push(
client.onDidChangeState((evt) => {
statusBar.setServerState(client, evt.newState);
}),
);
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<string | undefined> {
// Only allow the bundled Biome binary in untrusted workspaces
if (!workspace.isTrusted) {
return getBundledBinary(context, outputChannel);
}
if (process.env.DEBUG_SERVER_PATH) {
outputChannel.appendLine(
`Biome DEBUG_SERVER_PATH detected: ${process.env.DEBUG_SERVER_PATH}`,
);
return process.env.DEBUG_SERVER_PATH;
}
const config = workspace.getConfiguration();
const explicitPath = config.get("biome.lspBin");
if (typeof explicitPath === "string" && explicitPath !== "") {
return getWorkspaceRelativePath(explicitPath);
}
return (
(await getWorkspaceDependency(outputChannel)) ??
(await getBundledBinary(context, outputChannel))
);
}
// Resolve `path` as relative to the workspace root
async function getWorkspaceRelativePath(path: string) {
if (isAbsolute(path)) {
return path;
}
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) {
// 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 {
return undefined;
}
return undefined;
}
window.showWarningMessage(
"Unable to resolve the biome server from your dependencies. Make sure it's correctly installed, or untick the `requireConfiguration` setting to use the bundled binary.",
);
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 triplet = PLATFORMS[process.platform]?.[process.arch]?.triplet;
if (!triplet) {
outputChannel.appendLine(
`Unsupported platform ${process.platform} ${process.arch}`,
);
return undefined;
}
const binaryExt = triplet.includes("windows") ? ".exe" : "";
const binaryName = `biome${binaryExt}`;
const bundlePath = Uri.joinPath(context.extensionUri, "server", binaryName);
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) {
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];
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}`);
resolve(code);
});
process.on("close", (code) => {
outputChannel.appendLine(`[cli] close ${code}`);
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) {
throw wrapConnectionError(err, path);
}
await new Promise((resolve, reject) => {
socket.once("ready", resolve);
socket.once("error", (err) => {
reject(wrapConnectionError(err, path));
});
});
return { writer: socket, reader: socket };
}
export function deactivate(): Thenable<void> | undefined {
if (!client) {
return undefined;
}
return client.stop();
}