Skip to content

Commit

Permalink
Merge branch 'main' into riskymh/console.log
Browse files Browse the repository at this point in the history
  • Loading branch information
RiskyMH authored Nov 26, 2024
2 parents 8b059ab + c3d9e8c commit 14edbdd
Show file tree
Hide file tree
Showing 97 changed files with 6,131 additions and 3,112 deletions.
3 changes: 3 additions & 0 deletions .vscode/launch.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

93 changes: 50 additions & 43 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,57 @@
"version": "2.0.0",
"tasks": [
{
"type": "process",
"label": "Install Dependencies",
"command": "scripts/all-dependencies.sh",
"windows": {
"command": "scripts/all-dependencies.ps1",
},
"icon": {
"id": "arrow-down",
},
"options": {
"cwd": "${workspaceFolder}",
},
},
{
"type": "process",
"label": "Setup Environment",
"dependsOn": ["Install Dependencies"],
"command": "scripts/setup.sh",
"windows": {
"command": "scripts/setup.ps1",
},
"icon": {
"id": "check",
},
"options": {
"cwd": "${workspaceFolder}",
},
},
{
"type": "process",
"label": "Build Bun",
"dependsOn": ["Setup Environment"],
"command": "bun",
"args": ["run", "build"],
"icon": {
"id": "gear",
},
"options": {
"cwd": "${workspaceFolder}",
},
"isBuildCommand": true,
"runOptions": {
"instanceLimit": 1,
"reevaluateOnRerun": true,
"type": "shell",
"command": "bun run build",
"group": {
"kind": "build",
"isDefault": true,
},
"problemMatcher": [
{
"owner": "zig",
"fileLocation": ["relative", "${workspaceFolder}"],
"pattern": [
{
"regexp": "^(.+?):(\\d+):(\\d+): (error|warning|note): (.+)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5,
},
{
"regexp": "^\\s+(.+)$",
"message": 1,
"loop": true,
},
],
},
{
"owner": "clang",
"fileLocation": ["relative", "${workspaceFolder}"],
"pattern": [
{
"regexp": "^([^:]+):(\\d+):(\\d+):\\s+(warning|error|note|remark):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5,
},
{
"regexp": "^\\s*(.*)$",
"message": 1,
"loop": true,
},
],
},
],
"presentation": {
"reveal": "always",
"panel": "shared",
"clear": true,
},
},
],
Expand Down
10 changes: 8 additions & 2 deletions packages/bun-debug-adapter-protocol/src/debugger/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ export abstract class BaseDebugAdapter<T extends Inspector = Inspector>

/**
* Gets the inspector url. This is deprecated and exists for compat.
* @deprecated You should get the inspector directly, and if it's a WebSocketInspector you can access `.url` direclty.
* @deprecated You should get the inspector directly (with .getInspector()), and if it's a WebSocketInspector you can access `.url` direclty.
*/
get url(): string {
// This code has been migrated from a time when the inspector was always a WebSocketInspector.
Expand All @@ -305,6 +305,10 @@ export abstract class BaseDebugAdapter<T extends Inspector = Inspector>
throw new Error("Inspector does not offer a URL");
}

public getInspector() {
return this.inspector;
}

abstract start(...args: unknown[]): Promise<boolean>;

/**
Expand Down Expand Up @@ -2064,7 +2068,7 @@ export class NodeSocketDebugAdapter extends BaseDebugAdapter<NodeSocketInspector
/**
* The default debug adapter. Connects via WebSocket
*/
export class DebugAdapter extends BaseDebugAdapter<WebSocketInspector> {
export class WebSocketDebugAdapter extends BaseDebugAdapter<WebSocketInspector> {
#process?: ChildProcess;

public constructor(url?: string | URL, untitledDocPath?: string, bunEvalPath?: string) {
Expand Down Expand Up @@ -2331,6 +2335,8 @@ export class DebugAdapter extends BaseDebugAdapter<WebSocketInspector> {
}
}

export const DebugAdapter = WebSocketDebugAdapter;

function stoppedReason(reason: JSC.Debugger.PausedEvent["reason"]): DAP.StoppedEvent["reason"] {
switch (reason) {
case "Breakpoint":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ export class NodeSocketInspector extends EventEmitter<InspectorEventMap> impleme
this.#pendingResponses = new Map();

this.#framer = new SocketFramer(socket, message => {
// console.log(message);
if (Array.isArray(message)) {
for (const m of message) {
this.#accept(m);
Expand Down
3 changes: 2 additions & 1 deletion packages/bun-inspector-protocol/src/inspector/websocket.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { EventEmitter } from "node:events";
import { WebSocket } from "ws";
import type { Inspector, InspectorEventMap } from "./index";
import type { JSC } from "../protocol";
import type { Inspector, InspectorEventMap } from "./index";

/**
* An inspector that communicates with a debugger over a WebSocket.
Expand Down Expand Up @@ -170,6 +170,7 @@ export class WebSocketInspector extends EventEmitter<InspectorEventMap> implemen

#accept(message: string): void {
let data: JSC.Event | JSC.Response;

try {
data = JSON.parse(message);
} catch (cause) {
Expand Down
2 changes: 1 addition & 1 deletion packages/bun-vscode/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "bun-vscode",
"version": "0.0.15",
"version": "0.0.19",
"author": "oven",
"repository": {
"type": "git",
Expand Down
6 changes: 3 additions & 3 deletions packages/bun-vscode/src/features/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { join } from "node:path";
import * as vscode from "vscode";
import {
type DAP,
DebugAdapter,
getAvailablePort,
getRandomId,
TCPSocketSignal,
UnixSignal,
WebSocketDebugAdapter,
} from "../../../bun-debug-adapter-protocol";

export const DEBUG_CONFIGURATION: vscode.DebugConfiguration = {
Expand Down Expand Up @@ -239,7 +239,7 @@ class FileDebugSession extends DebugSession {
// If these classes are moved/published, we should make sure
// we remove these non-null assertions so consumers of
// this lib are not running into these hard
adapter!: DebugAdapter;
adapter!: WebSocketDebugAdapter;
sessionId?: string;
untitledDocPath?: string;
bunEvalPath?: string;
Expand All @@ -263,7 +263,7 @@ class FileDebugSession extends DebugSession {
: `ws+unix://${tmpdir()}/${uniqueId}.sock`;

const { untitledDocPath, bunEvalPath } = this;
this.adapter = new DebugAdapter(url, untitledDocPath, bunEvalPath);
this.adapter = new WebSocketDebugAdapter(url, untitledDocPath, bunEvalPath);

if (untitledDocPath) {
this.adapter.on("Adapter.response", (response: DebugProtocolResponse) => {
Expand Down
54 changes: 39 additions & 15 deletions packages/bun-vscode/src/features/diagnostics/diagnostics.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import * as fs from "node:fs/promises";
import { Socket } from "node:net";
import * as os from "node:os";
import { inspect } from "node:util";
import * as vscode from "vscode";
import {
getAvailablePort,
NodeSocketDebugAdapter,
getRandomId,
TCPSocketSignal,
UnixSignal,
WebSocketDebugAdapter,
} from "../../../../bun-debug-adapter-protocol";
import type { JSC } from "../../../../bun-inspector-protocol";
import { typedGlobalState } from "../../global-state";
import { createGlobalStateGenerationFn, typedGlobalState } from "../../global-state";

const output = vscode.window.createOutputChannel("Bun - Diagnostics");

Expand Down Expand Up @@ -69,8 +70,9 @@ class BunDiagnosticsManager {
private readonly editorState: EditorStateManager;
private readonly signal: UnixSignal | TCPSocketSignal;
private readonly context: vscode.ExtensionContext;
public readonly inspectUrl: string;

public get signalUrl() {
public get notifyUrl() {
return this.signal.url;
}

Expand Down Expand Up @@ -122,19 +124,30 @@ class BunDiagnosticsManager {
}
}

private static getOrCreateOldVersionInspectURL = createGlobalStateGenerationFn(
"DIAGNOSTICS_BUN_INSPECT",
async () => {
const url =
process.platform === "win32"
? `ws://127.0.0.1:${await getAvailablePort()}/${getRandomId()}`
: `ws+unix://${os.tmpdir()}/${getRandomId()}.sock`;

return url;
},
);

public static async initialize(context: vscode.ExtensionContext) {
const signal = await BunDiagnosticsManager.getOrRecreateSignal(context);
const oldVersionInspectURL = await BunDiagnosticsManager.getOrCreateOldVersionInspectURL(context.globalState);

await signal.ready;

return new BunDiagnosticsManager(context, signal);
return new BunDiagnosticsManager(context, signal, oldVersionInspectURL);
}

/**
* Called when Bun pings BUN_INSPECT_NOTIFY (indicating a program has started).
*/
private async handleSocketConnection(socket: Socket) {
const debugAdapter = new NodeSocketDebugAdapter(socket);
private async handleSocketConnection() {
const debugAdapter = new WebSocketDebugAdapter(this.inspectUrl);

this.editorState.clearAll("A new socket connected");

Expand All @@ -146,6 +159,10 @@ class BunDiagnosticsManager {
output.appendLine(`Received inspector event: ${e.method}`);
});

debugAdapter.on("Inspector.error", e => {
output.appendLine(inspect(e, true, null));
});

debugAdapter.on("LifecycleReporter.error", event => this.handleLifecycleError(event));

const ok = await debugAdapter.start();
Expand All @@ -159,7 +176,7 @@ class BunDiagnosticsManager {

debugAdapter.initialize({
adapterID: "bun-vsc-terminal-debug-adapter",
enableControlFlowProfiler: true,
enableControlFlowProfiler: false,
enableLifecycleAgentReporter: true,
sendImmediatePreventExit: false,
enableDebugger: false, // Performance overhead when debugger is enabled
Expand Down Expand Up @@ -203,8 +220,6 @@ class BunDiagnosticsManager {

const [line = null, col = null] = event.lineColumns.slice(i * 2, i * 2 + 2);

output.appendLine(`Adding related information for ${url} at ${line}:${col}`);

if (line === null || col === null) {
return [];
}
Expand All @@ -231,10 +246,15 @@ class BunDiagnosticsManager {
});
}

private constructor(context: vscode.ExtensionContext, signal: UnixSignal | TCPSocketSignal) {
private constructor(
context: vscode.ExtensionContext,
signal: UnixSignal | TCPSocketSignal,
oldVersionInspectURL: string,
) {
this.editorState = new EditorStateManager();
this.signal = signal;
this.context = context;
this.inspectUrl = oldVersionInspectURL;

this.context.subscriptions.push(
// on did type
Expand All @@ -243,7 +263,9 @@ class BunDiagnosticsManager {
}),
);

this.signal.on("Signal.Socket.connect", this.handleSocketConnection.bind(this));
this.signal.on("Signal.received", () => {
this.handleSocketConnection();
});
}
}

Expand All @@ -255,7 +277,9 @@ export async function registerDiagnosticsSocket(context: vscode.ExtensionContext
context.environmentVariableCollection.description = description;

const manager = await BunDiagnosticsManager.initialize(context);
context.environmentVariableCollection.replace("BUN_INSPECT_NOTIFY", manager.signalUrl);

context.environmentVariableCollection.replace("BUN_INSPECT_NOTIFY", manager.notifyUrl);
context.environmentVariableCollection.replace("BUN_INSPECT", `${manager.inspectUrl}?report=1?wait=1`); // Intentionally invalid query params

context.subscriptions.push(manager);
}
25 changes: 25 additions & 0 deletions packages/bun-vscode/src/global-state.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { ExtensionContext } from "vscode";

export const GLOBAL_STATE_VERSION = 1;

export type GlobalStateTypes = {
BUN_INSPECT_NOTIFY:
| {
Expand All @@ -10,8 +12,16 @@ export type GlobalStateTypes = {
type: "unix";
url: string;
};

DIAGNOSTICS_BUN_INSPECT: string;
};

export async function clearGlobalState(gs: ExtensionContext["globalState"]) {
const tgs = typedGlobalState(gs);

await Promise.all(tgs.keys().map(key => tgs.update(key, undefined as never)));
}

export function typedGlobalState(state: ExtensionContext["globalState"]) {
return state as {
get<K extends keyof GlobalStateTypes>(key: K): GlobalStateTypes[K] | undefined;
Expand All @@ -37,4 +47,19 @@ export function typedGlobalState(state: ExtensionContext["globalState"]) {
};
}

export function createGlobalStateGenerationFn<T extends keyof GlobalStateTypes>(
key: T,
resolve: () => Promise<GlobalStateTypes[T]>,
) {
return async (gs: ExtensionContext["globalState"]) => {
const value = (gs as TypedGlobalState).get(key);
if (value) return value;

const next = await resolve();
await (gs as TypedGlobalState).update(key, next);

return next;
};
}

export type TypedGlobalState = ReturnType<typeof typedGlobalState>;
Loading

0 comments on commit 14edbdd

Please sign in to comment.