diff options
73 files changed, 13542 insertions, 9216 deletions
Binary files differ diff --git a/package.json b/package.json index c4268a6cc..ab191a389 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "prettier": "^2.4.1", "react": "next", "react-dom": "next", + "source-map-js": "^1.0.2", "typescript": "^5.0.2" }, "private": true, @@ -17,7 +18,7 @@ "build-fallback": "esbuild --target=esnext --bundle src/fallback.ts --format=iife --platform=browser --minify > src/fallback.out.js", "postinstall": "bash .scripts/postinstall.sh", "typecheck": "tsc --noEmit && cd test && bun run typecheck", - "fmt": "prettier --write --cache './{src,test,bench}/**/*.{mjs,ts,tsx,js,jsx}'", + "fmt": "prettier --write --cache './{src,test,bench,packages/{bun-inspector-*,bun-vscode,bun-debug-adapter-protocol}}/**/*.{mjs,ts,tsx,js,jsx}'", "lint": "eslint './**/*.d.ts' --cache", "lint:fix": "eslint './**/*.d.ts' --cache --fix" }, diff --git a/packages/bun-debug-adapter-protocol/.gitattributes b/packages/bun-debug-adapter-protocol/.gitattributes new file mode 100644 index 000000000..f2af6eac2 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/.gitattributes @@ -0,0 +1,2 @@ +protocol/*/protocol.json linguist-generated=true +protocol/*/index.d.ts linguist-generated=true diff --git a/packages/bun-debug-adapter-protocol/.gitignore b/packages/bun-debug-adapter-protocol/.gitignore new file mode 100644 index 000000000..961b095a2 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/.gitignore @@ -0,0 +1 @@ +protocol/*.json diff --git a/packages/bun-debug-adapter-protocol/README.md b/packages/bun-debug-adapter-protocol/README.md new file mode 100644 index 000000000..909b88ea1 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/README.md @@ -0,0 +1,3 @@ +# bun-debug-adapter-protocol + +https://microsoft.github.io/debug-adapter-protocol/overview diff --git a/packages/bun-debug-adapter-protocol/bun.lockb b/packages/bun-debug-adapter-protocol/bun.lockb Binary files differnew file mode 100755 index 000000000..ccae05ab8 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/bun.lockb diff --git a/packages/bun-debug-adapter-protocol/debugger/__snapshots__/preview.test.ts.snap b/packages/bun-debug-adapter-protocol/debugger/__snapshots__/preview.test.ts.snap new file mode 100644 index 000000000..0acc17575 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/__snapshots__/preview.test.ts.snap @@ -0,0 +1,143 @@ +// Bun Snapshot v1, https://goo.gl/fbAQLP + +exports[`remoteObjectToString 1`] = `"undefined"`; + +exports[`remoteObjectToString 2`] = `"null"`; + +exports[`remoteObjectToString 3`] = `"true"`; + +exports[`remoteObjectToString 4`] = `"false"`; + +exports[`remoteObjectToString 5`] = `"0"`; + +exports[`remoteObjectToString 6`] = `"1"`; + +exports[`remoteObjectToString 7`] = `"3.141592653589793"`; + +exports[`remoteObjectToString 8`] = `"-2.718281828459045"`; + +exports[`remoteObjectToString 9`] = `"NaN"`; + +exports[`remoteObjectToString 10`] = `"Infinity"`; + +exports[`remoteObjectToString 11`] = `"-Infinity"`; + +exports[`remoteObjectToString 12`] = `"0n"`; + +exports[`remoteObjectToString 13`] = `"1n"`; + +exports[`remoteObjectToString 14`] = `"10000000000000n"`; + +exports[`remoteObjectToString 15`] = `"-10000000000000n"`; + +exports[`remoteObjectToString 16`] = `""""`; + +exports[`remoteObjectToString 17`] = `"" ""`; + +exports[`remoteObjectToString 18`] = `""Hello""`; + +exports[`remoteObjectToString 19`] = `""Hello World""`; + +exports[`remoteObjectToString 20`] = `"Array(0)"`; + +exports[`remoteObjectToString 21`] = `"Array(3) [1, 2, 3]"`; + +exports[`remoteObjectToString 22`] = `"Array(4) ["a", 1, null, undefined]"`; + +exports[`remoteObjectToString 23`] = `"Array(2) [1, Array]"`; + +exports[`remoteObjectToString 24`] = `"Array(1) [Array]"`; + +exports[`remoteObjectToString 25`] = `"{}"`; + +exports[`remoteObjectToString 26`] = `"{a: 1}"`; + +exports[`remoteObjectToString 27`] = `"{a: 1, b: 2, c: 3}"`; + +exports[`remoteObjectToString 28`] = `"{a: Object}"`; + +exports[`remoteObjectToString 29`] = ` +"ƒ() { +}" +`; + +exports[`remoteObjectToString 30`] = ` +"ƒ namedFunction() { +}" +`; + +exports[`remoteObjectToString 31`] = ` +"class { +}" +`; + +exports[`remoteObjectToString 32`] = ` +"class namedClass { +}" +`; + +exports[`remoteObjectToString 33`] = ` +"class namedClass { + a() { + } + b = 1; + c = [ + null, + undefined, + "a", + { + a: 1, + b: 2, + c: 3 + } + ]; +}" +`; + +exports[`remoteObjectToString 34`] = `"Wed Dec 31 1969 16:00:00 GMT-0800 (Pacific Standard Time)"`; + +exports[`remoteObjectToString 35`] = `"Invalid Date"`; + +exports[`remoteObjectToString 36`] = `"/(?:)/"`; + +exports[`remoteObjectToString 37`] = `"/abc/"`; + +exports[`remoteObjectToString 38`] = `"/abc/g"`; + +exports[`remoteObjectToString 39`] = `"/abc/"`; + +exports[`remoteObjectToString 40`] = `"Set(0)"`; + +exports[`remoteObjectToString 41`] = `"Set(3) [1, 2, 3]"`; + +exports[`remoteObjectToString 42`] = `"WeakSet(0)"`; + +exports[`remoteObjectToString 43`] = `"WeakSet(3) [{a: 1}, {b: 2}, {c: 3}]"`; + +exports[`remoteObjectToString 44`] = `"Map(0)"`; + +exports[`remoteObjectToString 45`] = `"Map(3) {"a" => 1, "b" => 2, "c" => 3}"`; + +exports[`remoteObjectToString 46`] = `"WeakMap(0)"`; + +exports[`remoteObjectToString 47`] = `"WeakMap(3) {{a: 1} => 1, {b: 2} => 2, {c: 3} => 3}"`; + +exports[`remoteObjectToString 48`] = `"Symbol()"`; + +exports[`remoteObjectToString 49`] = `"Symbol(namedSymbol)"`; + +exports[`remoteObjectToString 50`] = `"Error"`; + +exports[`remoteObjectToString 51`] = `"TypeError: This is a TypeError"`; + +exports[`remoteObjectToString 52`] = `"Headers {append: ƒ, delete: ƒ, get: ƒ, getAll: ƒ, has: ƒ, …}"`; + +exports[`remoteObjectToString 53`] = `"Headers {a: "1", append: ƒ, b: "2", delete: ƒ, get: ƒ, …}"`; + +exports[`remoteObjectToString 54`] = `"Request {arrayBuffer: ƒ, blob: ƒ, body: null, bodyUsed: false, cache: "default", …}"`; + +exports[`remoteObjectToString 55`] = `"Request {arrayBuffer: ƒ, blob: ƒ, body: ReadableStream, bodyUsed: false, cache: "default", …}"`; + +exports[`remoteObjectToString 56`] = `"Response {arrayBuffer: ƒ, blob: ƒ, body: null, bodyUsed: false, clone: ƒ, …}"`; + +exports[`remoteObjectToString 57`] = `"Response {arrayBuffer: ƒ, blob: ƒ, body: ReadableStream, bodyUsed: false, clone: ƒ, …}"`; diff --git a/packages/bun-debug-adapter-protocol/debugger/adapter.ts b/packages/bun-debug-adapter-protocol/debugger/adapter.ts new file mode 100644 index 000000000..9dc55fe38 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/adapter.ts @@ -0,0 +1,1692 @@ +import type { DAP } from ".."; +// @ts-ignore: FIXME - there is something wrong with the types +import type { JSC, InspectorListener } from "../../bun-inspector-protocol"; +import { WebSocketInspector } from "../../bun-inspector-protocol"; +import type { ChildProcess } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; +import capabilities from "./capabilities"; +import { Location, SourceMap } from "./sourcemap"; +import { remoteObjectToString } from "./preview"; +import { compare, parse } from "semver"; + +type InitializeRequest = DAP.InitializeRequest & { + supportsConfigurationDoneRequest?: boolean; +}; + +type LaunchRequest = DAP.LaunchRequest & { + runtime?: string; + program?: string; + cwd?: string; + args?: string[]; + env?: Record<string, string>; + inheritEnv?: boolean; + watch?: boolean | "hot"; +}; + +type AttachRequest = DAP.AttachRequest & { + url?: string; +}; + +type Source = DAP.Source & { + scriptId: string; + sourceMap: SourceMap; +} & ( + | { + sourceId: string; + path: string; + sourceReference?: undefined; + } + | { + sourceId: number; + path?: undefined; + sourceReference: number; + } + ); + +type Breakpoint = DAP.Breakpoint & { + id: number; + breakpointId: string; + source: Source; +}; + +type FunctionBreakpoint = DAP.Breakpoint & { + id: number; + name: string; +}; + +type StackFrame = DAP.StackFrame & { + scriptId: string; + callFrameId: string; + source?: Source; + scopes?: Scope[]; +}; + +type Scope = DAP.Scope & { + source?: Source; +}; + +type Variable = DAP.Variable & { + objectId?: string; + type: JSC.Runtime.RemoteObject["type"] | JSC.Runtime.RemoteObject["subtype"]; +}; + +type IDebugAdapter = { + [E in keyof DAP.EventMap]?: (event: DAP.EventMap[E]) => void; +} & { + [R in keyof DAP.RequestMap]?: ( + request: DAP.RequestMap[R], + ) => void | DAP.ResponseMap[R] | Promise<void | DAP.ResponseMap[R]>; +}; + +export type DebugAdapterOptions = { + sendToAdapter(message: DAP.Request | DAP.Response | DAP.Event): Promise<void>; +}; + +// This adapter only support single-threaded debugging, +// which means that there is only one thread at a time. +const threadId = 1; + +export class DebugAdapter implements IDebugAdapter, InspectorListener { + #sendToAdapter: DebugAdapterOptions["sendToAdapter"]; + #inspector: WebSocketInspector; + #sourceId: number; + #pendingSources: Map<string, ((source: Source) => void)[]>; + #sources: Map<string | number, Source>; + #stackFrames: StackFrame[]; + #stopped?: DAP.StoppedEvent["reason"]; + #breakpointId: number; + #breakpoints: Breakpoint[]; + #functionBreakpoints: Map<string, FunctionBreakpoint>; + #variables: (Variable | Variable[])[]; + #process?: ChildProcess; + #initialized?: InitializeRequest; + #launched?: LaunchRequest; + #connected?: boolean; + #terminated?: boolean; + #url?: URL; + + constructor({ sendToAdapter }: DebugAdapterOptions) { + this.#inspector = new WebSocketInspector({ listener: this }); + this.#sendToAdapter = sendToAdapter; + this.#sourceId = 1; + this.#pendingSources = new Map(); + this.#sources = new Map(); + this.#stackFrames = []; + this.#stopped = undefined; + this.#breakpointId = 1; + this.#breakpoints = []; + this.#functionBreakpoints = new Map(); + this.#variables = [{ name: "", value: "", type: undefined, variablesReference: 0 }]; + } + + async accept(message: DAP.Request | DAP.Response | DAP.Event): Promise<void> { + const { type } = message; + + switch (type) { + case "request": + return this.#acceptRequest(message); + } + + throw new Error(`Not supported: ${type}`); + } + + async #acceptRequest(request: DAP.Request): Promise<void> { + const { seq, command, arguments: args } = request; + + let response; + try { + if (!(command! in this)) { + throw new Error(`Not supported: ${command}`); + } + response = await this[command as keyof this](args); + } catch (error) { + console.error(error); + const { message } = unknownToError(error); + return this.#sendToAdapter({ + type: "response", + success: false, + message, + request_seq: seq, + seq: 0, + command, + }); + } + + return this.#sendToAdapter({ + type: "response", + success: true, + request_seq: seq, + seq: 0, + command, + body: response, + }); + } + + async #send<M extends keyof JSC.RequestMap & keyof JSC.ResponseMap>( + method: M, + params?: JSC.RequestMap[M], + ): Promise<JSC.ResponseMap[M]> { + return this.#inspector.send(method, params); + } + + async #emit<E extends keyof DAP.EventMap>(name: E, body?: DAP.EventMap[E]): Promise<void> { + await this.#sendToAdapter({ + type: "event", + seq: 0, + event: name, + body, + }); + } + + initialize(request: InitializeRequest): DAP.InitializeResponse { + const { clientID, supportsConfigurationDoneRequest } = (this.#initialized = request); + + this.#send("Inspector.enable"); + this.#send("Runtime.enable"); + this.#send("Console.enable"); + this.#send("Debugger.enable"); + this.#send("Debugger.setAsyncStackTraceDepth", { depth: 200 }); + this.#send("Debugger.setPauseOnDebuggerStatements", { enabled: true }); + this.#send("Debugger.setBlackboxBreakpointEvaluations", { blackboxBreakpointEvaluations: true }); + this.#send("Debugger.setBreakpointsActive", { active: true }); + + // If the client will not send a `configurationDone` request, then we need to + // tell the debugger that everything is ready. + if (!supportsConfigurationDoneRequest && clientID !== "vscode") { + this.#send("Inspector.initialized"); + } + + // Tell the client what capabilities this adapter supports. + return capabilities; + } + + configurationDone(): void { + // If the client requested that `noDebug` mode be enabled, + // then we need to disable all breakpoints and pause on statements. + if (this.#launched?.noDebug) { + this.#send("Debugger.setBreakpointsActive", { active: false }); + this.#send("Debugger.setPauseOnExceptions", { state: "none" }); + this.#send("Debugger.setPauseOnDebuggerStatements", { enabled: false }); + this.#send("Debugger.setPauseOnMicrotasks", { enabled: false }); + this.#send("Debugger.setPauseForInternalScripts", { shouldPause: false }); + this.#send("Debugger.setPauseOnAssertions", { enabled: false }); + } + + // Tell the debugger that everything is ready. + this.#send("Inspector.initialized"); + } + + async launch(request: DAP.LaunchRequest): Promise<void> { + this.#launched = request; + + try { + await this.#launch(request); + } catch (error) { + // Some clients, like VSCode, will show a system-level popup when a `launch` request fails. + // Instead, we want to show the error as a sidebar notification. + const { message } = unknownToError(error); + this.#emit("output", { + category: "stderr", + output: `Failed to start debugger.\n${message}`, + }); + this.#emit("terminated"); + } + } + + async #launch(request: LaunchRequest): Promise<void> { + if (this.#process?.exitCode === null) { + throw new Error("Another program is already running. Did you terminate the last session?"); + } + + const { program, runtime = "bun", args = [], cwd, env = {}, inheritEnv = true, watch = true } = request; + if (!program) { + throw new Error("No program specified. Did you set the 'program' property in your launch.json?"); + } + + if (!isJavaScript(program)) { + throw new Error("Program must be a JavaScript or TypeScript file."); + } + + const argz = ["--inspect-wait=0", ...args]; + if (watch) { + argz.push(watch === "hot" ? "--hot" : "--watch"); + } + console.log(argz); + + const subprocess = spawn(runtime, [...argz, program], { + stdio: ["ignore", "pipe", "pipe", "pipe"], + cwd, + env: inheritEnv ? { ...process.env, ...env } : env, + }); + + subprocess.on("spawn", () => { + this.#process = subprocess; + this.#emit("process", { + name: program, + systemProcessId: subprocess.pid, + isLocalProcess: true, + startMethod: "launch", + }); + }); + + subprocess.on("exit", code => { + this.#emit("exited", { + exitCode: code ?? -1, + }); + this.#process = undefined; + }); + + const stdout: string[] = []; + subprocess.stdout!.on("data", data => { + if (!this.#url) { + const text = data.toString(); + stdout.push(text); + const url = (this.#url = parseUrlMaybe(text)); + this.#inspector.start(url); + } else if (stdout.length) { + stdout.length = 0; + } + }); + + const stderr: string[] = []; + subprocess.stderr!.on("data", data => { + if (!this.#url) { + stderr.push(data.toString()); + } else if (stderr.length) { + stderr.length = 0; + } + }); + + const start = new Promise<undefined>(resolve => { + subprocess.on("spawn", () => resolve(undefined)); + }); + + const exitOrError = new Promise<number | string | Error>(resolve => { + subprocess.on("exit", (code, signal) => resolve(code ?? signal ?? -1)); + subprocess.on("error", resolve); + }); + + const reason = await Promise.race([start, exitOrError]); + + if (reason instanceof Error) { + const { message } = reason; + throw new Error(`Program could not be started.\n${message}`); + } + + if (reason !== undefined) { + throw new Error(`Program exited with code ${reason} before the debugger could attached.`); + } + + for (let retries = 0; !this.#url && retries < 10; retries++) { + await new Promise(resolve => setTimeout(resolve, 100 * retries)); + } + + if (this.#url) { + return; + } + + if (subprocess.exitCode === null && !subprocess.kill() && !subprocess.kill("SIGKILL")) { + this.#emit("output", { + category: "debug console", + output: `Failed to kill process ${subprocess.pid}\n`, + }); + } + + const { stdout: version } = spawnSync(runtime, ["--version"], { stdio: "pipe", encoding: "utf-8" }); + + if (parse(version, true) && compare("0.8.0", version, true)) { + throw new Error( + `Bun v${version.trim()} does not have debugger support. Please upgrade to v0.8 or later by running: \`bun upgrade\``, + ); + } + + for (const message of stderr) { + this.#emit("output", { + category: "stderr", + output: message, + source: { + path: program, + }, + }); + } + + for (const message of stdout) { + this.#emit("output", { + category: "stdout", + output: message, + source: { + path: program, + }, + }); + } + + throw new Error("Program started, but the debugger could not be attached."); + } + + attach(request: AttachRequest): void { + const { url } = request; + this.#inspector.start(parseUrl(url)); + } + + terminate(): void { + this.#terminated = true; + this.#process?.kill(); + } + + disconnect(request: DAP.DisconnectRequest): void { + const { terminateDebuggee } = request; + + if (terminateDebuggee) { + this.terminate(); + } + + this.close(); + } + + async source(request: DAP.SourceRequest): Promise<DAP.SourceResponse> { + const { source } = request; + + const { scriptId } = await this.#getSource(sourceToId(source)); + const { scriptSource } = await this.#send("Debugger.getScriptSource", { scriptId }); + + return { + content: scriptSource, + }; + } + + async threads(request: DAP.ThreadsRequest): Promise<DAP.ThreadsResponse> { + return { + threads: [ + { + id: threadId, + name: "Main Thread", + }, + ], + }; + } + + async pause(): Promise<void> { + await this.#send("Debugger.pause"); + this.#stopped = "pause"; + } + + async continue(): Promise<void> { + await this.#send("Debugger.resume"); + this.#stopped = undefined; + } + + async next(): Promise<void> { + await this.#send("Debugger.stepNext"); + this.#stopped = "step"; + } + + async stepIn(): Promise<void> { + await this.#send("Debugger.stepInto"); + this.#stopped = "step"; + } + + async stepOut(): Promise<void> { + await this.#send("Debugger.stepOut"); + this.#stopped = "step"; + } + + async breakpointLocations(request: DAP.BreakpointLocationsRequest): Promise<DAP.BreakpointLocationsResponse> { + const { line, endLine, column, endColumn, source: source0 } = request; + const source = await this.#getSource(sourceToId(source0)); + + const [start, end] = await Promise.all([ + this.#generatedLocation(source, line, column), + this.#generatedLocation(source, endLine ?? line + 1, endColumn), + ]); + + const { locations } = await this.#send("Debugger.getBreakpointLocations", { + start, + end, + }); + + return { + breakpoints: locations.map(location => this.#originalLocation(source, location)), + }; + } + + #generatedLocation(source: Source, line?: number, column?: number): JSC.Debugger.Location { + const { sourceMap, scriptId, path } = source; + const { line: gline, column: gcolumn } = sourceMap.generatedLocation({ + line: this.#lineTo0BasedLine(line), + column: this.#columnTo0BasedColumn(column), + url: path, + }); + + return { + scriptId, + lineNumber: gline, + columnNumber: gcolumn, + }; + } + + #lineTo0BasedLine(line?: number): number { + if (!numberIsValid(line)) { + return 0; + } + if (this.#initialized?.linesStartAt1) { + return line - 1; + } + return line; + } + + #columnTo0BasedColumn(column?: number): number { + if (!numberIsValid(column)) { + return 0; + } + if (this.#initialized?.columnsStartAt1) { + return column - 1; + } + return column; + } + + #originalLocation( + source: Source, + line?: number | JSC.Debugger.Location, + column?: number, + ): { line: number; column: number } { + if (typeof line === "object") { + const { lineNumber, columnNumber } = line; + line = lineNumber; + column = columnNumber; + } + + const { sourceMap } = source; + const { line: oline, column: ocolumn } = sourceMap.originalLocation({ line, column }); + + return { + line: this.#lineFrom0BasedLine(oline), + column: this.#columnFrom0BasedColumn(ocolumn), + }; + } + + #lineFrom0BasedLine(line?: number): number { + if (this.#initialized?.linesStartAt1) { + return numberIsValid(line) ? line + 1 : 1; + } + return numberIsValid(line) ? line : 0; + } + + #columnFrom0BasedColumn(column?: number): number { + if (this.#initialized?.columnsStartAt1) { + return numberIsValid(column) ? column + 1 : 1; + } + return numberIsValid(column) ? column : 0; + } + + async setBreakpoints(request: DAP.SetBreakpointsRequest): Promise<DAP.SetBreakpointsResponse> { + const { source: source0, breakpoints: requests } = request; + const sourceId = sourceToId(source0); + const source = await this.#getSource(sourceId); + + const oldBreakpoints = this.#getBreakpoints(sourceId); + + const breakpoints = await Promise.all( + requests!.map(async ({ line, column, ...options }) => { + const breakpoint = this.#getBreakpoint(sourceId, line, column); + if (breakpoint) { + return breakpoint; + } + + const location = this.#generatedLocation(source, line, column); + try { + const { breakpointId, actualLocation } = await this.#send("Debugger.setBreakpoint", { + location, + options: breakpointOptions(options), + }); + + const originalLocation = this.#originalLocation(source, actualLocation); + return this.#addBreakpoint({ + id: this.#breakpointId++, + breakpointId, + source, + verified: true, + ...originalLocation, + }); + } catch (error) { + const { message } = unknownToError(error); + // If there was an error setting the breakpoint, + // mark it as unverified and add a message. + const breakpointId = this.#breakpointId++; + return this.#addBreakpoint({ + id: breakpointId, + breakpointId: `${breakpointId}`, + line, + column, + source, + verified: false, + message, + }); + } + }), + ); + + await Promise.all( + oldBreakpoints.map(async ({ breakpointId }) => { + const isRemoved = !breakpoints.filter(({ breakpointId: id }) => breakpointId === id).length; + if (isRemoved) { + await this.#send("Debugger.removeBreakpoint", { + breakpointId, + }); + this.#removeBreakpoint(breakpointId); + } + }), + ); + + return { + breakpoints, + }; + } + + #getBreakpoints(sourceId: string | number): Breakpoint[] { + const breakpoints: Breakpoint[] = []; + + for (const breakpoint of this.#breakpoints.values()) { + const { source } = breakpoint; + if (sourceId === sourceToId(source)) { + breakpoints.push(breakpoint); + } + } + + return breakpoints; + } + + #getBreakpoint(sourceId: string | number, line?: number, column?: number): Breakpoint | undefined { + for (const breakpoint of this.#getBreakpoints(sourceId)) { + if (isSameLocation(breakpoint, { line, column })) { + return breakpoint; + } + } + return undefined; + } + + #addBreakpoint(breakpoint: Breakpoint): Breakpoint { + this.#breakpoints.push(breakpoint); + + this.#emit("breakpoint", { + reason: "changed", + breakpoint, + }); + + return breakpoint; + } + + #removeBreakpoint(breakpointId: string): void { + const breakpoint = this.#breakpoints.find(({ breakpointId: id }) => id === breakpointId); + if (!breakpoint) { + return; + } + + this.#breakpoints = this.#breakpoints.filter(({ breakpointId: id }) => id !== breakpointId); + this.#emit("breakpoint", { + reason: "removed", + breakpoint, + }); + } + + async setFunctionBreakpoints( + request: DAP.SetFunctionBreakpointsRequest, + ): Promise<DAP.SetFunctionBreakpointsResponse> { + const { breakpoints: requests } = request; + + const oldBreakpoints = this.#getFunctionBreakpoints(); + + const breakpoints = await Promise.all( + requests.map(async ({ name, ...options }) => { + const breakpoint = this.#getFunctionBreakpoint(name); + if (breakpoint) { + return breakpoint; + } + + try { + await this.#send("Debugger.addSymbolicBreakpoint", { + symbol: name, + caseSensitive: true, + isRegex: false, + options: breakpointOptions(options), + }); + } catch (error) { + const { message } = unknownToError(error); + return this.#addFunctionBreakpoint({ + id: this.#breakpointId++, + name, + verified: false, + message, + }); + } + + return this.#addFunctionBreakpoint({ + id: this.#breakpointId++, + name, + verified: true, + }); + }), + ); + + await Promise.all( + oldBreakpoints.map(async ({ name }) => { + const isRemoved = !breakpoints.filter(({ name: n }) => name === n).length; + if (isRemoved) { + await this.#send("Debugger.removeSymbolicBreakpoint", { + symbol: name, + caseSensitive: true, + isRegex: false, + }); + this.#removeFunctionBreakpoint(name); + } + }), + ); + + return { + breakpoints, + }; + } + + #getFunctionBreakpoints(): FunctionBreakpoint[] { + return [...this.#functionBreakpoints.values()]; + } + + #getFunctionBreakpoint(name: string): FunctionBreakpoint | undefined { + return this.#functionBreakpoints.get(name); + } + + #addFunctionBreakpoint(breakpoint: FunctionBreakpoint): FunctionBreakpoint { + const { name } = breakpoint; + this.#functionBreakpoints.set(name, breakpoint); + this.#emit("breakpoint", { + reason: "changed", + breakpoint, + }); + return breakpoint; + } + + #removeFunctionBreakpoint(name: string): void { + const breakpoint = this.#functionBreakpoints.get(name); + if (!breakpoint || !this.#functionBreakpoints.delete(name)) { + return; + } + this.#emit("breakpoint", { + reason: "removed", + breakpoint, + }); + } + + async setExceptionBreakpoints(request: DAP.SetExceptionBreakpointsRequest): Promise<void> { + const { filters, filterOptions } = request; + + const filterIds = [...filters]; + if (filterOptions) { + filterIds.push(...filterOptions.map(({ filterId }) => filterId)); + } + + await this.#send("Debugger.setPauseOnExceptions", { + state: exceptionFiltersToPauseOnExceptionsState(filterIds), + }); + } + + async evaluate(request: DAP.EvaluateRequest): Promise<DAP.EvaluateResponse> { + const { expression, frameId, context } = request; + const callFrameId = this.#getCallFrameId(frameId); + + const { result, wasThrown } = await this.#evaluate(expression, callFrameId); + const { className } = result; + + if (context === "hover" && wasThrown && (className === "SyntaxError" || className === "ReferenceError")) { + return { + result: "", + variablesReference: 0, + }; + } + + const { name, value, ...variable } = this.#addVariable(result); + return { + ...variable, + result: value, + }; + } + + async #evaluate(expression: string, callFrameId?: string): Promise<JSC.Runtime.EvaluateResponse> { + const method = callFrameId ? "Debugger.evaluateOnCallFrame" : "Runtime.evaluate"; + + return this.#send(method, { + callFrameId, + expression: sanitizeExpression(expression), + generatePreview: true, + emulateUserGesture: true, + doNotPauseOnExceptionsAndMuteConsole: true, + includeCommandLineAPI: true, + }); + } + + restart(): void { + this.initialize(this.#initialized!); + this.configurationDone(); + + this.#emit("output", { + category: "debug console", + output: "Debugger reloaded.\n", + }); + } + + ["Inspector.connected"](): void { + if (this.#connected) { + this.restart(); + return; + } + + this.#connected = true; + + this.#emit("output", { + category: "debug console", + output: "Debugger attached.\n", + }); + + this.#emit("initialized"); + } + + ["Inspector.disconnected"](error?: Error): void { + if (this.#connected && this.#process?.exitCode === null) { + this.#url = undefined; + return; + } + + this.#emit("output", { + category: "debug console", + output: "Debugger detached.\n", + }); + + if (error && !this.#terminated) { + const { message } = error; + this.#emit("output", { + category: "stderr", + output: `${message}\n`, + }); + } + + this.#emit("terminated"); + this.#reset(); + } + + async ["Debugger.scriptParsed"](event: JSC.Debugger.ScriptParsedEvent): Promise<void> { + const { url, scriptId, sourceMapURL } = event; + + // If no url is present, the script is from a `evaluate` request. + if (!url) { + return; + } + + // Sources can be retrieved in two ways: + // 1. If it has a `path`, the client retrieves the source from the file system. + // 2. If it has a `sourceReference`, the client sends a `source` request. + // Moreover, the code is usually shown in a read-only editor. + const isUserCode = url.startsWith("/"); + const sourceMap = SourceMap(sourceMapURL); + const name = sourceName(url); + const presentationHint = sourcePresentationHint(url); + + if (isUserCode) { + this.#addSource({ + sourceId: url, + scriptId, + name, + path: url, + presentationHint, + sourceMap, + }); + return; + } + + const sourceReference = this.#sourceId++; + this.#addSource({ + sourceId: sourceReference, + scriptId, + name, + sourceReference, + presentationHint, + sourceMap, + }); + } + + ["Debugger.scriptFailedToParse"](event: JSC.Debugger.ScriptFailedToParseEvent): void { + const { url, errorMessage, errorLine } = event; + + this.#emit("output", { + category: "stderr", + output: errorMessage, + line: this.#lineFrom0BasedLine(errorLine), + source: { + path: url || undefined, + }, + }); + } + + ["Debugger.paused"](event: JSC.Debugger.PausedEvent): void { + const { reason, callFrames, asyncStackTrace, data } = event; + + if (reason === "PauseOnNextStatement") { + for (const { functionName } of callFrames) { + if (functionName === "module code") { + this.#send("Debugger.resume"); + return; + } + } + } + + this.#stackFrames.length = 0; + this.#stopped ||= stoppedReason(reason); + for (const callFrame of callFrames) { + this.#addStackFrame(callFrame); + } + if (asyncStackTrace) { + this.#addAsyncStackTrace(asyncStackTrace); + } + + let hitBreakpointIds: number[] | undefined; + // Depending on the reason, the `data` property is set to the reason + // why the execution was paused. For example, if the reason is "breakpoint", + // the `data` property is set to the breakpoint ID. + if (data) { + if (reason === "exception") { + const remoteObject = data as JSC.Runtime.RemoteObject; + } + + if (reason === "FunctionCall") { + const { name } = data as { name: string }; + const breakpoint = this.#getFunctionBreakpoint(name); + if (breakpoint) { + const { id } = breakpoint; + hitBreakpointIds = [id]; + } + } + + if (reason === "Breakpoint") { + const { breakpointId: hitBreakpointId } = data as { breakpointId: string }; + for (const { id, breakpointId } of this.#breakpoints.values()) { + if (breakpointId === hitBreakpointId) { + hitBreakpointIds = [id]; + break; + } + } + } + } + + this.#emit("stopped", { + threadId, + reason: this.#stopped, + hitBreakpointIds, + }); + } + + ["Debugger.resumed"](event: JSC.Debugger.ResumedEvent): void { + this.#stackFrames.length = 0; + this.#stopped = undefined; + this.#emit("continued", { + threadId, + }); + } + + ["Console.messageAdded"](event: JSC.Console.MessageAddedEvent): void { + const { message } = event; + const { type, level, text, parameters, line, column, stackTrace } = message; + + let output: string; + let variablesReference: number | undefined; + + if (parameters?.length) { + output = ""; + + const variables = parameters.map((parameter, i) => { + const variable = this.#addVariable(parameter, { name: `${i}` }); + + const { value } = variable; + output += value + " "; + + return variable; + }); + + if (variables.length === 1) { + const [{ variablesReference: reference }] = variables; + variablesReference = reference; + } else { + variablesReference = this.#setVariable(variables); + } + } else { + output = text; + } + + if (!output.endsWith("\n")) { + output += "\n"; + } + + const color = consoleLevelToAnsiColor(level); + if (color) { + output = `${color}${output}`; + } + + if (variablesReference) { + variablesReference = this.#setVariable([ + { + name: "", + value: "", + type: undefined, + variablesReference, + }, + ]); + } + + let source: Source | undefined; + if (stackTrace) { + const { callFrames } = stackTrace; + if (callFrames.length) { + const { scriptId } = callFrames.at(-1)!; + source = this.#getSourceIfPresent(scriptId); + } + } + + let location: Location | {} = {}; + if (source) { + location = this.#originalLocation(source, line, column); + } + + this.#emit("output", { + category: "debug console", + group: consoleMessageGroup(type), + output, + variablesReference, + source, + ...location, + }); + } + + #addSource(source: Source): Source { + const { sourceId, scriptId, path, sourceReference } = source; + + const oldSource = this.#getSourceIfPresent(sourceId); + if (oldSource) { + const { scriptId, path: oldPath } = oldSource; + // For now, the script ID will always change. + // Could that not be the case in the future? + this.#sources.delete(scriptId); + + // If the path changed or the source has a source reference, + // the old source should be marked as removed. + if (path !== oldPath || sourceReference) { + this.#emit("loadedSource", { + reason: "removed", + source: oldSource, + }); + } + } + + this.#sources.set(sourceId, source); + this.#sources.set(scriptId, source); + + this.#emit("loadedSource", { + // If the reason is "changed", the source will be retrieved using + // the `source` command, which is why it cannot be set when `path` is present. + reason: oldSource && !path ? "changed" : "new", + source, + }); + + if (!path) { + return source; + } + + // If there are any pending requests for this source by its path, + // resolve them now that the source has been loaded. + const resolves = this.#pendingSources.get(path); + if (resolves) { + this.#pendingSources.delete(path); + for (const resolve of resolves) { + resolve(source); + } + } + + return source; + } + + loadedSources(): DAP.LoadedSourcesResponse { + const sources = new Map(); + + // Since there are duplicate keys for each source, + // (e.g. scriptId, path, sourceReference, etc.) it needs to be deduped. + for (const source of this.#sources.values()) { + const { sourceId } = source; + sources.set(sourceId, source); + } + + return { + sources: [...sources.values()], + }; + } + + #getSourceIfPresent(sourceId: string | number): Source | undefined { + return this.#sources.get(sourceId); + } + + async #getSource(sourceId: string | number): Promise<Source> { + const source = this.#getSourceIfPresent(sourceId); + + if (source) { + return source; + } + + // If the source does not have a path or is a builtin module, + // it cannot be retrieved from the file system. + if (typeof sourceId === "number" || !sourceId.startsWith("/")) { + throw new Error(`Source not found: ${sourceId}`); + } + + // If the source is not present, it may not have been loaded yet. + // In that case, wait for it to be loaded. + let resolves = this.#pendingSources.get(sourceId); + if (!resolves) { + this.#pendingSources.set(sourceId, (resolves = [])); + } + + return new Promise(resolve => { + resolves!.push(resolve); + }); + } + + async stackTrace(request: DAP.StackTraceRequest): Promise<DAP.StackTraceResponse> { + const { length } = this.#stackFrames; + const { startFrame = 0, levels } = request; + const endFrame = levels ? startFrame + levels : length; + + return { + totalFrames: length, + stackFrames: this.#stackFrames.slice(startFrame, endFrame), + }; + } + + async scopes(request: DAP.ScopesRequest): Promise<DAP.ScopesResponse> { + const { frameId } = request; + + for (const stackFrame of this.#stackFrames) { + const { id, scopes } = stackFrame; + if (id !== frameId || !scopes) { + continue; + } + return { + scopes, + }; + } + + return { + scopes: [], + }; + } + + #getCallFrameId(frameId?: number): string | undefined { + for (const { id, callFrameId } of this.#stackFrames) { + if (id === frameId) { + return callFrameId; + } + } + return undefined; + } + + #addStackFrame(callFrame: JSC.Debugger.CallFrame): StackFrame { + const { callFrameId, functionName, location, scopeChain } = callFrame; + const { scriptId } = location; + const source = this.#getSourceIfPresent(scriptId); + + let originalLocation: Location; + if (source) { + originalLocation = this.#originalLocation(source, location); + } else { + const { lineNumber, columnNumber } = location; + originalLocation = { + line: this.#lineFrom0BasedLine(lineNumber), + column: this.#columnFrom0BasedColumn(columnNumber), + }; + } + + const { line, column } = originalLocation; + const scopes: Scope[] = []; + const stackFrame: StackFrame = { + callFrameId, + scriptId, + id: this.#stackFrames.length, + name: functionName || "<anonymous>", + line, + column, + presentationHint: stackFramePresentationHint(source?.path), + source, + scopes, + }; + this.#stackFrames.push(stackFrame); + + for (const scope of scopeChain) { + const { name, type, location, object, empty } = scope; + if (empty) { + continue; + } + + const { variablesReference } = this.#addVariable(object); + const presentationHint = scopePresentationHint(type); + const title = presentationHint ? titleize(presentationHint) : "Unknown"; + const displayName = name ? `${title}: ${name}` : title; + + let originalLocation: Location | undefined; + if (location) { + const { scriptId } = location; + const source = this.#getSourceIfPresent(scriptId); + + if (source) { + originalLocation = this.#originalLocation(source, location); + } else { + const { lineNumber, columnNumber } = location; + originalLocation = { + line: this.#lineFrom0BasedLine(lineNumber), + column: this.#columnFrom0BasedColumn(columnNumber), + }; + } + } + + const { line, column } = originalLocation ?? {}; + scopes.push({ + name: displayName, + presentationHint, + expensive: presentationHint === "globals", + variablesReference, + line, + column, + source, + }); + } + + return stackFrame; + } + + #addAsyncStackTrace(stackTrace: JSC.Console.StackTrace): void { + const { callFrames, parentStackTrace } = stackTrace; + + for (const callFrame of callFrames) { + this.#addAsyncStackFrame(callFrame); + } + + if (parentStackTrace) { + this.#addAsyncStackTrace(parentStackTrace); + } + } + + #addAsyncStackFrame(callFrame: JSC.Console.CallFrame): StackFrame { + const { scriptId, functionName } = callFrame; + const callFrameId = callFrameToId(callFrame); + const source = this.#getSourceIfPresent(scriptId); + + let originalLocation: Location; + if (source) { + originalLocation = this.#originalLocation(source, callFrame); + } else { + const { lineNumber, columnNumber } = callFrame; + originalLocation = { + line: this.#lineFrom0BasedLine(lineNumber), + column: this.#columnFrom0BasedColumn(columnNumber), + }; + } + + const { line, column } = originalLocation; + const stackFrame: StackFrame = { + callFrameId, + scriptId, + id: this.#stackFrames.length, + name: functionName || "<anonymous>", + line, + column, + source, + presentationHint: stackFramePresentationHint(source?.path), + canRestart: false, + }; + this.#stackFrames.push(stackFrame); + + return stackFrame; + } + + async variables(request: DAP.VariablesRequest): Promise<DAP.VariablesResponse> { + const { variablesReference, start, count } = request; + const variable = this.#variables[variablesReference]; + + let variables: Variable[]; + if (!variable) { + variables = []; + } else if (Array.isArray(variable)) { + variables = variable; + } else { + variables = await this.#getVariables(variable, start, count); + } + + return { + variables: variables.sort(variablesSortBy), + }; + } + + #setVariable(variable: Variable | Variable[]): number { + const variablesReference = this.#variables.length; + + this.#variables.push(variable); + + return variablesReference; + } + + #addVariable(remoteObject: JSC.Runtime.RemoteObject, propertyDescriptor?: JSC.Runtime.PropertyDescriptor): Variable { + const { objectId, type, subtype, size } = remoteObject; + const variablesReference = objectId ? this.#variables.length : 0; + + const variable: Variable = { + objectId, + name: propertyDescriptorToName(propertyDescriptor), + type: subtype || type, + value: remoteObjectToString(remoteObject), + variablesReference, + indexedVariables: isIndexed(subtype) ? size : undefined, + namedVariables: isNamedIndexed(subtype) ? size : undefined, + presentationHint: remoteObjectToVariablePresentationHint(remoteObject, propertyDescriptor), + }; + this.#setVariable(variable); + + return variable; + } + + async #getVariables(variable: Variable, offset?: number, count?: number): Promise<Variable[]> { + const { objectId, type, indexedVariables, namedVariables } = variable; + + if (!objectId || type === "symbol") { + return []; + } + + const { properties, internalProperties } = await this.#send("Runtime.getDisplayableProperties", { + objectId, + generatePreview: true, + }); + + const variables: Variable[] = []; + for (const property of properties) { + variables.push(...this.#getVariable(property)); + } + + if (internalProperties) { + for (const property of internalProperties) { + variables.push(...this.#getVariable({ ...property, configurable: false })); + } + } + + const hasEntries = type !== "array" && (indexedVariables || namedVariables); + if (hasEntries) { + const { entries } = await this.#send("Runtime.getCollectionEntries", { + objectId, + fetchStart: offset, + fetchCount: count, + }); + + let i = 0; + for (const { key, value } of entries) { + let name = String(i++); + if (key) { + const { value, description } = key; + name = String(value ?? description); + } + variables.push(this.#addVariable(value, { name })); + } + } + + return variables; + } + + #getVariable( + propertyDescriptor: JSC.Runtime.PropertyDescriptor | JSC.Runtime.InternalPropertyDescriptor, + ): Variable[] { + const { value, get, set, symbol } = propertyDescriptor as JSC.Runtime.PropertyDescriptor; + const variables: Variable[] = []; + + if (value) { + variables.push(this.#addVariable(value, propertyDescriptor)); + } + + if (get) { + const { type } = get; + if (type !== "undefined") { + variables.push(this.#addVariable(get, propertyDescriptor)); + } + } + + if (set) { + const { type } = set; + if (type !== "undefined") { + variables.push(this.#addVariable(set, propertyDescriptor)); + } + } + + if (symbol) { + variables.push(this.#addVariable(symbol, propertyDescriptor)); + } + + return variables; + } + + close(): void { + this.#terminated = true; + this.#process?.kill(); + this.#inspector.close(); + this.#reset(); + } + + #reset(): void { + this.#pendingSources.clear(); + this.#sources.clear(); + this.#stackFrames.length = 0; + this.#stopped = undefined; + this.#breakpointId = 1; + this.#breakpoints.length = 0; + this.#functionBreakpoints.clear(); + this.#variables.length = 1; + this.#launched = undefined; + this.#initialized = undefined; + this.#connected = undefined; + this.#terminated = undefined; + this.#url = undefined; + } +} + +function stoppedReason(reason: JSC.Debugger.PausedEvent["reason"]): DAP.StoppedEvent["reason"] { + switch (reason) { + case "Breakpoint": + return "breakpoint"; + case "FunctionCall": + return "function breakpoint"; + case "PauseOnNextStatement": + case "DebuggerStatement": + return "pause"; + case "exception": + case "assert": + return "exception"; + default: + return "breakpoint"; + } +} + +function titleize(name: string): string { + return name.charAt(0).toUpperCase() + name.slice(1); +} + +function sourcePresentationHint(url?: string): DAP.Source["presentationHint"] { + if (!url || !url.startsWith("/")) { + return "deemphasize"; + } + if (url.includes("/node_modules/")) { + return "normal"; + } + return "emphasize"; +} + +function sourceName(url?: string): string { + if (!url) { + return "unknown.js"; + } + if (isJavaScript(url)) { + return url.split("/").pop() || url; + } + return `${url}.js`; +} + +function stackFramePresentationHint(path?: string): DAP.StackFrame["presentationHint"] { + if (!path || path.includes("/node_modules/")) { + return "subtle"; + } + return "normal"; +} + +function scopePresentationHint(type: JSC.Debugger.Scope["type"]): DAP.Scope["presentationHint"] { + switch (type) { + case "closure": + case "functionName": + case "with": + case "catch": + case "nestedLexical": + return "locals"; + case "global": + case "globalLexicalEnvironment": + return "globals"; + default: + return undefined; + } +} + +function isIndexed(subtype: JSC.Runtime.RemoteObject["subtype"]): boolean { + return subtype === "array" || subtype === "set" || subtype === "weakset"; +} + +function isNamedIndexed(subtype: JSC.Runtime.RemoteObject["subtype"]): boolean { + return subtype === "map" || subtype === "weakmap"; +} + +function exceptionFiltersToPauseOnExceptionsState( + filters?: string[], +): JSC.Debugger.SetPauseOnExceptionsRequest["state"] { + if (filters?.includes("all")) { + return "all"; + } + if (filters?.includes("uncaught")) { + return "uncaught"; + } + return "none"; +} + +function breakpointOptions(breakpoint?: Partial<DAP.SourceBreakpoint>): JSC.Debugger.BreakpointOptions { + const { condition } = breakpoint ?? {}; + // TODO: hitCondition, logMessage + return { + condition, + }; +} + +function consoleMessageGroup(type: JSC.Console.ConsoleMessage["type"]): DAP.OutputEvent["group"] { + switch (type) { + case "startGroup": + return "start"; + case "startGroupCollapsed": + return "startCollapsed"; + case "endGroup": + return "end"; + } + return undefined; +} + +function sourceToPath(source?: DAP.Source): string { + const { path } = source ?? {}; + if (!path) { + throw new Error("No source found."); + } + return path; +} + +function sourceToId(source?: DAP.Source): string | number { + const { path, sourceReference } = source ?? {}; + if (path) { + return path; + } + if (sourceReference) { + return sourceReference; + } + throw new Error("No source found."); +} + +function callFrameToId(callFrame: JSC.Console.CallFrame): string { + const { url, lineNumber, columnNumber } = callFrame; + return `${url}:${lineNumber}:${columnNumber}`; +} + +function sanitizeExpression(expression: string): string { + expression = expression.trim(); + if (expression.startsWith("{")) { + expression = `(${expression})`; + } + if (expression.startsWith("return ")) { + expression = expression.slice(7); + } + if (expression.startsWith("await ")) { + expression = expression.slice(6); + } + return expression; +} + +function remoteObjectToVariablePresentationHint( + remoteObject: JSC.Runtime.RemoteObject, + propertyDescriptor?: JSC.Runtime.PropertyDescriptor, +): DAP.VariablePresentationHint { + const { type, subtype } = remoteObject; + const { name, configurable, writable, isPrivate, symbol, get, set, wasThrown } = propertyDescriptor ?? {}; + const hasGetter = get?.type === "function"; + const hasSetter = set?.type === "function"; + const hasSymbol = symbol?.type === "symbol"; + let kind: string | undefined; + let visibility: string | undefined; + let lazy: boolean | undefined; + let attributes: string[] = []; + if (type === "function") { + kind = "method"; + } + if (subtype === "class") { + kind = "class"; + } + if (isPrivate || configurable === false || hasSymbol || name === "__proto__") { + visibility = "internal"; + } + if (type === "string") { + attributes.push("rawString"); + } + if (writable === false || (hasGetter && !hasSetter)) { + attributes.push("readOnly"); + } + if (wasThrown || hasGetter) { + lazy = true; + attributes.push("hasSideEffects"); + } + return { + kind, + visibility, + lazy, + attributes, + }; +} + +function propertyDescriptorToName(propertyDescriptor?: JSC.Runtime.PropertyDescriptor): string { + if (!propertyDescriptor) { + return ""; + } + const { name } = propertyDescriptor; + if (name === "__proto__") { + return "[[Prototype]]"; + } + return name; +} + +function unknownToError(input: unknown): Error { + if (input instanceof Error) { + return input; + } + return new Error(String(input)); +} + +function isJavaScript(path: string): boolean { + return /\.(c|m)?(j|t)sx?$/.test(path); +} + +function parseUrl(hostname?: string, port?: number): URL { + hostname ||= "localhost"; + port ||= 6499; + let url: URL; + try { + if (hostname.includes("://")) { + url = new URL(hostname); + } else if (hostname.includes(":") && !hostname.startsWith("[")) { + url = new URL(`ws://[${hostname}]:${port}/`); + } else { + url = new URL(`ws://${hostname}:${port}/`); + } + } catch { + throw new Error(`Invalid URL or hostname/port: ${hostname}`); + } + // HACK: Bun sometimes has issues connecting through "127.0.0.1" + if (url.hostname === "localhost" || url.hostname === "127.0.0.1") { + url.hostname = "[::1]"; + } + return url; +} + +function parseUrlMaybe(string: string): URL | undefined { + const match = /(wss?:\/\/.*)/im.exec(string); + if (!match) { + return undefined; + } + const [_, href] = match; + try { + return parseUrl(href); + } catch { + return undefined; + } +} + +function variablesSortBy(a: DAP.Variable, b: DAP.Variable): number { + const visibility = (variable: DAP.Variable): number => { + const { presentationHint } = variable; + switch (presentationHint?.visibility) { + case "protected": + return 1; + case "private": + return 2; + case "internal": + return 3; + } + return 0; + }; + const index = (variable: DAP.Variable): number => { + const { name } = variable; + switch (name) { + case "[[Prototype]]": + case "prototype": + case "__proto__": + return Number.MAX_VALUE; + } + const index = parseInt(name); + if (isFinite(index)) { + return index; + } + return 0; + }; + const av = visibility(a); + const bv = visibility(b); + if (av > bv) return 1; + if (av < bv) return -1; + const ai = index(a); + const bi = index(b); + if (ai > bi) return 1; + if (ai < bi) return -1; + return 0; +} + +function isSameLocation(a: { line?: number; column?: number }, b: { line?: number; column?: number }): boolean { + return (a.line === b.line || (!a.line && !b.line)) && (a.column === b.column || (!a.column && !b.column)); +} + +function consoleLevelToAnsiColor(level: JSC.Console.ConsoleMessage["level"]): string | undefined { + switch (level) { + case "warning": + return "\u001b[33m"; + case "error": + return "\u001b[31m"; + case "debug": + return "\u001b[36m"; + } + return undefined; +} + +function numberIsValid(number?: number): number is number { + return typeof number === "number" && isFinite(number) && number >= 0; +} diff --git a/packages/bun-debug-adapter-protocol/debugger/capabilities.ts b/packages/bun-debug-adapter-protocol/debugger/capabilities.ts new file mode 100644 index 000000000..3ba968e86 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/capabilities.ts @@ -0,0 +1,271 @@ +import type { DAP } from ".."; + +const capabilities: DAP.Capabilities = { + /** + * The debug adapter supports the `configurationDone` request. + * @see configurationDone + */ + supportsConfigurationDoneRequest: true, + + /** + * The debug adapter supports function breakpoints using the `setFunctionBreakpoints` request. + * @see setFunctionBreakpoints + */ + supportsFunctionBreakpoints: true, + + /** + * The debug adapter supports conditional breakpoints. + * @see setBreakpoints + * @see setInstructionBreakpoints + * @see setFunctionBreakpoints + * @see setExceptionBreakpoints + * @see setDataBreakpoints + */ + supportsConditionalBreakpoints: true, + + /** + * The debug adapter supports breakpoints that break execution after a specified number of hits. + * @see setBreakpoints + * @see setInstructionBreakpoints + * @see setFunctionBreakpoints + * @see setExceptionBreakpoints + * @see setDataBreakpoints + */ + supportsHitConditionalBreakpoints: true, + + /** + * The debug adapter supports a (side effect free) `evaluate` request for data hovers. + * @see evaluate + */ + supportsEvaluateForHovers: true, + + /** + * Available exception filter options for the `setExceptionBreakpoints` request. + * @see setExceptionBreakpoints + */ + exceptionBreakpointFilters: [ + { + filter: "all", + label: "Caught Exceptions", + default: false, + supportsCondition: true, + description: "Breaks on all throw errors, even if they're caught later.", + conditionDescription: `error.name == "CustomError"`, + }, + { + filter: "uncaught", + label: "Uncaught Exceptions", + default: false, + supportsCondition: true, + description: "Breaks only on errors or promise rejections that are not handled.", + conditionDescription: `error.name == "CustomError"`, + }, + ], + + /** + * The debug adapter supports stepping back via the `stepBack` and `reverseContinue` requests. + * @see stepBack + * @see reverseContinue + */ + supportsStepBack: false, + + /** + * The debug adapter supports setting a variable to a value. + * @see setVariable + */ + supportsSetVariable: false, + + /** + * The debug adapter supports restarting a frame. + * @see restartFrame + */ + supportsRestartFrame: false, + + /** + * The debug adapter supports the `gotoTargets` request. + * @see gotoTargets + */ + supportsGotoTargetsRequest: false, + + /** + * The debug adapter supports the `stepInTargets` request. + * @see stepInTargets + */ + supportsStepInTargetsRequest: false, + + /** + * The debug adapter supports the `completions` request. + * @see completions + */ + supportsCompletionsRequest: false, + + /** + * The set of characters that should trigger completion in a REPL. + * If not specified, the UI should assume the `.` character. + * @see completions + */ + completionTriggerCharacters: [".", "[", '"', "'"], + + /** + * The debug adapter supports the `modules` request. + * @see modules + */ + supportsModulesRequest: false, + + /** + * The set of additional module information exposed by the debug adapter. + * @see modules + */ + additionalModuleColumns: [], + + /** + * Checksum algorithms supported by the debug adapter. + */ + supportedChecksumAlgorithms: [], + + /** + * The debug adapter supports the `restart` request. + * In this case a client should not implement `restart` by terminating + * and relaunching the adapter but by calling the `restart` request. + * @see restart + */ + supportsRestartRequest: false, + + /** + * The debug adapter supports `exceptionOptions` on the `setExceptionBreakpoints` request. + * @see setExceptionBreakpoints + */ + supportsExceptionOptions: false, + + /** + * The debug adapter supports a `format` attribute on the `stackTrace`, `variables`, and `evaluate` requests. + * @see stackTrace + * @see variables + * @see evaluate + */ + supportsValueFormattingOptions: false, + + /** + * The debug adapter supports the `exceptionInfo` request. + * @see exceptionInfo + */ + supportsExceptionInfoRequest: true, + + /** + * The debug adapter supports the `terminateDebuggee` attribute on the `disconnect` request. + * @see disconnect + */ + supportTerminateDebuggee: true, + + /** + * The debug adapter supports the `suspendDebuggee` attribute on the `disconnect` request. + * @see disconnect + */ + supportSuspendDebuggee: false, + + /** + * The debug adapter supports the delayed loading of parts of the stack, + * which requires that both the `startFrame` and `levels` arguments and + * the `totalFrames` result of the `stackTrace` request are supported. + * @see stackTrace + */ + supportsDelayedStackTraceLoading: true, + + /** + * The debug adapter supports the `loadedSources` request. + * @see loadedSources + */ + supportsLoadedSourcesRequest: true, + + /** + * The debug adapter supports log points by interpreting the `logMessage` attribute of the `SourceBreakpoint`. + * @see setBreakpoints + */ + supportsLogPoints: true, + + /** + * The debug adapter supports the `terminateThreads` request. + * @see terminateThreads + */ + supportsTerminateThreadsRequest: false, + + /** + * The debug adapter supports the `setExpression` request. + * @see setExpression + */ + supportsSetExpression: false, + + /** + * The debug adapter supports the `terminate` request. + * @see terminate + */ + supportsTerminateRequest: true, + + /** + * The debug adapter supports data breakpoints. + * @see setDataBreakpoints + */ + supportsDataBreakpoints: false, + + /** + * The debug adapter supports the `readMemory` request. + * @see readMemory + */ + supportsReadMemoryRequest: false, + + /** + * The debug adapter supports the `writeMemory` request. + * @see writeMemory + */ + supportsWriteMemoryRequest: false, + + /** + * The debug adapter supports the `disassemble` request. + * @see disassemble + */ + supportsDisassembleRequest: false, + + /** + * The debug adapter supports the `cancel` request. + * @see cancel + */ + supportsCancelRequest: false, + + /** + * The debug adapter supports the `breakpointLocations` request. + * @see breakpointLocations + */ + supportsBreakpointLocationsRequest: true, + + /** + * The debug adapter supports the `clipboard` context value in the `evaluate` request. + * @see evaluate + */ + supportsClipboardContext: false, + + /** + * The debug adapter supports stepping granularities (argument `granularity`) for the stepping requests. + * @see stepIn + */ + supportsSteppingGranularity: false, + + /** + * The debug adapter supports adding breakpoints based on instruction references. + * @see setInstructionBreakpoints + */ + supportsInstructionBreakpoints: false, + + /** + * The debug adapter supports `filterOptions` as an argument on the `setExceptionBreakpoints` request. + * @see setExceptionBreakpoints + */ + supportsExceptionFilterOptions: true, + + /** + * The debug adapter supports the `singleThread` property on the execution requests + * (`continue`, `next`, `stepIn`, `stepOut`, `reverseContinue`, `stepBack`). + */ + supportsSingleThreadExecutionRequests: false, +}; + +export default capabilities; diff --git a/packages/bun-debug-adapter-protocol/debugger/fixtures/preview.js b/packages/bun-debug-adapter-protocol/debugger/fixtures/preview.js new file mode 100644 index 000000000..15062240b --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/fixtures/preview.js @@ -0,0 +1,99 @@ +console.log( + undefined, + null, + true, + false, + 0, + 1, + Math.PI, + -Math.E, + NaN, + Infinity, + -Infinity, + BigInt(0), + BigInt(1), + BigInt("10000000000000"), + BigInt("-10000000000000"), + "", + " ", + "Hello", + "Hello World", + [], + [1, 2, 3], + ["a", 1, null, undefined], + [1, [2, [3, [4, [5, [6, [7, [8, [9, [10]]]]]]]]]], + [[[[[]]]]], + {}, + { a: 1 }, + { a: 1, b: 2, c: 3 }, + { a: { b: { c: { d: { e: { f: { g: { h: { i: { j: 10 } } } } } } } } } }, + function () {}, + function namedFunction() {}, + class {}, + class namedClass {}, + class namedClass { + a() {} + b = 1; + c = [ + null, + undefined, + "a", + { + a: 1, + b: 2, + c: 3, + }, + ]; + }, + new Date(0), + new Date(NaN), + new RegExp(), + new RegExp("abc"), + new RegExp("abc", "g"), + /abc/, + new Set(), + new Set([1, 2, 3]), + new WeakSet(), + new WeakSet([{ a: 1 }, { b: 2 }, { c: 3 }]), + new Map(), + new Map([ + ["a", 1], + ["b", 2], + ["c", 3], + ]), + new WeakMap(), + new WeakMap([ + [{ a: 1 }, 1], + [{ b: 2 }, 2], + [{ c: 3 }, 3], + ]), + Symbol(), + Symbol("namedSymbol"), + new Error(), + new TypeError("This is a TypeError"), + //"a".repeat(10000), + //["a"].fill("a", 0, 10000), + new Headers(), + new Headers({ + a: "1", + b: "2", + }), + new Request("https://example.com/"), + new Request("https://example.com/", { + method: "POST", + headers: { + a: "1", + b: "2", + }, + body: '{"example":true}', + }), + new Response(), + new Response('{"example":true}', { + status: 200, + statusText: "OK", + headers: { + a: "1", + b: "2", + }, + }), +); diff --git a/packages/bun-debug-adapter-protocol/debugger/fixtures/with-sourcemap.js b/packages/bun-debug-adapter-protocol/debugger/fixtures/with-sourcemap.js new file mode 100644 index 000000000..6c16a1202 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/fixtures/with-sourcemap.js @@ -0,0 +1,36 @@ +"use strict"; +export default { + fetch(request) { + const animal = getAnimal(request.url); + const voice = animal.talk(); + return new Response(voice); + }, +}; +function getAnimal(query) { + switch (query.split("/").pop()) { + case "dog": + return new Dog(); + case "cat": + return new Cat(); + } + return new Bird(); +} +class Dog { + name = "dog"; + talk() { + return "woof"; + } +} +class Cat { + name = "cat"; + talk() { + return "meow"; + } +} +class Bird { + name = "bird"; + talk() { + return "chirp"; + } +} +//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsicGFja2FnZXMvYnVuLWRlYnVnLWFkYXB0ZXItcHJvdG9jb2wvZGVidWdnZXIvZml4dHVyZXMvd2l0aC1zb3VyY2VtYXAudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImV4cG9ydCBkZWZhdWx0IHtcbiAgZmV0Y2gocmVxdWVzdDogUmVxdWVzdCk6IFJlc3BvbnNlIHtcbiAgICBjb25zdCBhbmltYWwgPSBnZXRBbmltYWwocmVxdWVzdC51cmwpO1xuICAgIGNvbnN0IHZvaWNlID0gYW5pbWFsLnRhbGsoKTtcbiAgICByZXR1cm4gbmV3IFJlc3BvbnNlKHZvaWNlKTtcbiAgfSxcbn07XG5cbmZ1bmN0aW9uIGdldEFuaW1hbChxdWVyeTogc3RyaW5nKTogQW5pbWFsIHtcbiAgc3dpdGNoIChxdWVyeS5zcGxpdChcIi9cIikucG9wKCkpIHtcbiAgICBjYXNlIFwiZG9nXCI6XG4gICAgICByZXR1cm4gbmV3IERvZygpO1xuICAgIGNhc2UgXCJjYXRcIjpcbiAgICAgIHJldHVybiBuZXcgQ2F0KCk7XG4gIH1cbiAgcmV0dXJuIG5ldyBCaXJkKCk7XG59XG5cbmludGVyZmFjZSBBbmltYWwge1xuICByZWFkb25seSBuYW1lOiBzdHJpbmc7XG4gIHRhbGsoKTogc3RyaW5nO1xufVxuXG5jbGFzcyBEb2cgaW1wbGVtZW50cyBBbmltYWwge1xuICBuYW1lID0gXCJkb2dcIjtcblxuICB0YWxrKCk6IHN0cmluZyB7XG4gICAgcmV0dXJuIFwid29vZlwiO1xuICB9XG59XG5cbmNsYXNzIENhdCBpbXBsZW1lbnRzIEFuaW1hbCB7XG4gIG5hbWUgPSBcImNhdFwiO1xuXG4gIHRhbGsoKTogc3RyaW5nIHtcbiAgICByZXR1cm4gXCJtZW93XCI7XG4gIH1cbn1cblxuY2xhc3MgQmlyZCBpbXBsZW1lbnRzIEFuaW1hbCB7XG4gIG5hbWUgPSBcImJpcmRcIjtcblxuICB0YWxrKCk6IHN0cmluZyB7XG4gICAgcmV0dXJuIFwiY2hpcnBcIjtcbiAgfVxufVxuIl0sCiAgIm1hcHBpbmdzIjogIjtBQUFBLGVBQWU7QUFBQSxFQUNiLE1BQU0sU0FBNEI7QUFDaEMsVUFBTSxTQUFTLFVBQVUsUUFBUSxHQUFHO0FBQ3BDLFVBQU0sUUFBUSxPQUFPLEtBQUs7QUFDMUIsV0FBTyxJQUFJLFNBQVMsS0FBSztBQUFBLEVBQzNCO0FBQ0Y7QUFFQSxTQUFTLFVBQVUsT0FBdUI7QUFDeEMsVUFBUSxNQUFNLE1BQU0sR0FBRyxFQUFFLElBQUksR0FBRztBQUFBLElBQzlCLEtBQUs7QUFDSCxhQUFPLElBQUksSUFBSTtBQUFBLElBQ2pCLEtBQUs7QUFDSCxhQUFPLElBQUksSUFBSTtBQUFBLEVBQ25CO0FBQ0EsU0FBTyxJQUFJLEtBQUs7QUFDbEI7QUFPQSxNQUFNLElBQXNCO0FBQUEsRUFDMUIsT0FBTztBQUFBLEVBRVAsT0FBZTtBQUNiLFdBQU87QUFBQSxFQUNUO0FBQ0Y7QUFFQSxNQUFNLElBQXNCO0FBQUEsRUFDMUIsT0FBTztBQUFBLEVBRVAsT0FBZTtBQUNiLFdBQU87QUFBQSxFQUNUO0FBQ0Y7QUFFQSxNQUFNLEtBQXVCO0FBQUEsRUFDM0IsT0FBTztBQUFBLEVBRVAsT0FBZTtBQUNiLFdBQU87QUFBQSxFQUNUO0FBQ0Y7IiwKICAibmFtZXMiOiBbXQp9Cg== diff --git a/packages/bun-debug-adapter-protocol/debugger/fixtures/with-sourcemap.ts b/packages/bun-debug-adapter-protocol/debugger/fixtures/with-sourcemap.ts new file mode 100644 index 000000000..f245ebf76 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/fixtures/with-sourcemap.ts @@ -0,0 +1,46 @@ +export default { + fetch(request: Request): Response { + const animal = getAnimal(request.url); + const voice = animal.talk(); + return new Response(voice); + }, +}; + +function getAnimal(query: string): Animal { + switch (query.split("/").pop()) { + case "dog": + return new Dog(); + case "cat": + return new Cat(); + } + return new Bird(); +} + +interface Animal { + readonly name: string; + talk(): string; +} + +class Dog implements Animal { + name = "dog"; + + talk(): string { + return "woof"; + } +} + +class Cat implements Animal { + name = "cat"; + + talk(): string { + return "meow"; + } +} + +class Bird implements Animal { + name = "bird"; + + talk(): string { + return "chirp"; + } +} diff --git a/packages/bun-debug-adapter-protocol/debugger/fixtures/without-sourcemap.js b/packages/bun-debug-adapter-protocol/debugger/fixtures/without-sourcemap.js new file mode 100644 index 000000000..6a5d9a948 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/fixtures/without-sourcemap.js @@ -0,0 +1,20 @@ +export default { + fetch(request) { + return new Response(a()); + }, +}; + +function a() { + return b(); +} + +function b() { + return c(); +} + +function c() { + function d() { + return "hello"; + } + return d(); +} diff --git a/packages/bun-debug-adapter-protocol/debugger/preview.test.ts b/packages/bun-debug-adapter-protocol/debugger/preview.test.ts new file mode 100644 index 000000000..666913719 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/preview.test.ts @@ -0,0 +1,62 @@ +import { beforeAll, afterAll, test, expect } from "bun:test"; +import type { JSC } from "../../bun-inspector-protocol"; +import { WebSocketInspector } from "../../bun-inspector-protocol"; +import type { PipedSubprocess } from "bun"; +import { spawn } from "bun"; +import { remoteObjectToString } from "./preview"; + +let subprocess: PipedSubprocess | undefined; +let objects: JSC.Runtime.RemoteObject[] = []; + +beforeAll(async () => { + subprocess = spawn({ + cwd: import.meta.dir, + cmd: [process.argv0, "--inspect-wait=0", "fixtures/preview.js"], + stdout: "pipe", + stderr: "pipe", + stdin: "pipe", + }); + const decoder = new TextDecoder(); + let url: URL; + for await (const chunk of subprocess!.stdout) { + const text = decoder.decode(chunk); + if (text.includes("ws://")) { + url = new URL(/(ws:\/\/.*)/.exec(text)![0]); + break; + } + } + objects = await new Promise((resolve, reject) => { + const inspector = new WebSocketInspector({ + url, + listener: { + ["Inspector.connected"]: () => { + inspector.send("Inspector.enable"); + inspector.send("Runtime.enable"); + inspector.send("Console.enable"); + inspector.send("Debugger.enable"); + inspector.send("Debugger.resume"); + inspector.send("Inspector.initialized"); + }, + ["Inspector.disconnected"]: error => { + reject(error); + }, + ["Console.messageAdded"]: ({ message }) => { + const { parameters } = message; + resolve(parameters!); + inspector.close(); + }, + }, + }); + inspector.start(); + }); +}); + +afterAll(() => { + subprocess?.kill(); +}); + +test("remoteObjectToString", () => { + for (const object of objects) { + expect(remoteObjectToString(object)).toMatchSnapshot(); + } +}); diff --git a/packages/bun-debug-adapter-protocol/debugger/preview.ts b/packages/bun-debug-adapter-protocol/debugger/preview.ts new file mode 100644 index 000000000..6012623d2 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/preview.ts @@ -0,0 +1,110 @@ +import type { JSC } from "../../bun-inspector-protocol"; + +export function remoteObjectToString(remoteObject: JSC.Runtime.RemoteObject): string { + const { type, subtype, value, description, className, preview } = remoteObject; + switch (type) { + case "undefined": + return "undefined"; + case "boolean": + case "number": + return description ?? JSON.stringify(value); + case "string": + return JSON.stringify(value ?? description); + case "symbol": + case "bigint": + return description!; + case "function": + return description!.replace("function", "ƒ") || "ƒ"; + } + switch (subtype) { + case "null": + return "null"; + case "regexp": + case "date": + case "error": + return description!; + } + if (preview) { + return objectPreviewToString(preview); + } + if (className) { + return className; + } + return description || "Object"; +} + +export function objectPreviewToString(objectPreview: JSC.Runtime.ObjectPreview): string { + const { type, subtype, entries, properties, overflow, description, size } = objectPreview; + if (type !== "object") { + return remoteObjectToString(objectPreview); + } + let items: string[]; + if (entries) { + items = entries.map(entryPreviewToString).sort(); + } else if (properties) { + if (isIndexed(subtype)) { + items = properties.map(indexedPropertyPreviewToString).sort(); + } else { + items = properties.map(namedPropertyPreviewToString).sort(); + } + } else { + items = ["…"]; + } + if (overflow) { + items.push("…"); + } + let label: string; + if (description === "Object") { + label = ""; + } else if (size === undefined) { + label = description!; + } else { + label = `${description}(${size})`; + } + if (!items.length) { + return label || "{}"; + } + if (label) { + label += " "; + } + if (isIndexed(subtype)) { + return `${label}[${items.join(", ")}]`; + } + return `${label}{${items.join(", ")}}`; +} + +function propertyPreviewToString(propertyPreview: JSC.Runtime.PropertyPreview): string { + const { type, value, ...preview } = propertyPreview; + if (type === "accessor") { + return "ƒ"; + } + return remoteObjectToString({ ...preview, type, description: value }); +} + +function entryPreviewToString(entryPreview: JSC.Runtime.EntryPreview): string { + const { key, value } = entryPreview; + if (key) { + return `${objectPreviewToString(key)} => ${objectPreviewToString(value)}`; + } + return objectPreviewToString(value); +} + +function namedPropertyPreviewToString(propertyPreview: JSC.Runtime.PropertyPreview): string { + const { name, valuePreview } = propertyPreview; + if (valuePreview) { + return `${name}: ${objectPreviewToString(valuePreview)}`; + } + return `${name}: ${propertyPreviewToString(propertyPreview)}`; +} + +function indexedPropertyPreviewToString(propertyPreview: JSC.Runtime.PropertyPreview): string { + const { valuePreview } = propertyPreview; + if (valuePreview) { + return objectPreviewToString(valuePreview); + } + return propertyPreviewToString(propertyPreview); +} + +function isIndexed(type?: JSC.Runtime.RemoteObject["subtype"]): boolean { + return type === "array" || type === "set" || type === "weakset"; +} diff --git a/packages/bun-debug-adapter-protocol/debugger/sourcemap.test.ts b/packages/bun-debug-adapter-protocol/debugger/sourcemap.test.ts new file mode 100644 index 000000000..44d9ca362 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/sourcemap.test.ts @@ -0,0 +1,31 @@ +import { test, expect } from "bun:test"; +import { readFileSync } from "node:fs"; +import { SourceMap } from "./sourcemap"; + +test("works without source map", () => { + const sourceMap = getSourceMap("without-sourcemap.js"); + expect(sourceMap.generatedLocation({ line: 7 })).toEqual({ line: 7, column: 0, verified: true }); + expect(sourceMap.generatedLocation({ line: 7, column: 2 })).toEqual({ line: 7, column: 2, verified: true }); + expect(sourceMap.originalLocation({ line: 11 })).toEqual({ line: 11, column: 0, verified: true }); + expect(sourceMap.originalLocation({ line: 11, column: 2 })).toEqual({ line: 11, column: 2, verified: true }); +}); + +test("works with source map", () => { + const sourceMap = getSourceMap("with-sourcemap.js"); + // FIXME: Columns don't appear to be accurate for `generatedLocation` + expect(sourceMap.generatedLocation({ line: 3 })).toMatchObject({ line: 4, verified: true }); + expect(sourceMap.generatedLocation({ line: 27 })).toMatchObject({ line: 20, verified: true }); + expect(sourceMap.originalLocation({ line: 32 })).toEqual({ line: 43, column: 4, verified: true }); + expect(sourceMap.originalLocation({ line: 13 })).toEqual({ line: 13, column: 6, verified: true }); +}); + +function getSourceMap(filename: string): SourceMap { + const { pathname } = new URL(`./fixtures/${filename}`, import.meta.url); + const source = readFileSync(pathname, "utf-8"); + const match = source.match(/\/\/# sourceMappingURL=(.*)$/m); + if (match) { + const [, url] = match; + return SourceMap(url); + } + return SourceMap(); +} diff --git a/packages/bun-debug-adapter-protocol/debugger/sourcemap.ts b/packages/bun-debug-adapter-protocol/debugger/sourcemap.ts new file mode 100644 index 000000000..adb6dc57d --- /dev/null +++ b/packages/bun-debug-adapter-protocol/debugger/sourcemap.ts @@ -0,0 +1,187 @@ +import type { LineRange, MappedPosition } from "source-map-js"; +import { SourceMapConsumer } from "source-map-js"; + +export type LocationRequest = { + line?: number; + column?: number; + url?: string; +}; + +export type Location = { + line: number; // 0-based + column: number; // 0-based +} & ( + | { + verified: true; + } + | { + verified?: false; + message?: string; + } +); + +export interface SourceMap { + generatedLocation(request: LocationRequest): Location; + originalLocation(request: LocationRequest): Location; +} + +class ActualSourceMap implements SourceMap { + #sourceMap: SourceMapConsumer; + #sources: string[]; + + constructor(sourceMap: SourceMapConsumer) { + this.#sourceMap = sourceMap; + this.#sources = (sourceMap as any)._absoluteSources; + } + + #getSource(url?: string): string { + const sources = this.#sources; + if (!sources.length) { + return ""; + } + if (sources.length === 1 || !url) { + return sources[0]; + } + for (const source of sources) { + if (url.endsWith(source)) { + return source; + } + } + return ""; + } + + generatedLocation(request: LocationRequest): Location { + const { line, column, url } = request; + let lineRange: LineRange; + try { + const source = this.#getSource(url); + lineRange = this.#sourceMap.generatedPositionFor({ + line: lineTo1BasedLine(line), + column: columnToColumn(column), + source, + }); + } catch (error) { + return { + line: lineToLine(line), + column: columnToColumn(column), + verified: false, + message: unknownToError(error), + }; + } + if (!locationIsValid(lineRange)) { + return { + line: lineToLine(line), + column: columnToColumn(column), + verified: false, + }; + } + const { line: gline, column: gcolumn } = lineRange; + return { + line: lineToLine(gline), + column: columnToColumn(gcolumn), + verified: true, + }; + } + + originalLocation(request: LocationRequest): Location { + const { line, column } = request; + let mappedPosition: MappedPosition; + try { + mappedPosition = this.#sourceMap.originalPositionFor({ + line: lineTo1BasedLine(line), + column: columnToColumn(column), + }); + } catch (error) { + return { + line: lineToLine(line), + column: columnToColumn(column), + verified: false, + message: unknownToError(error), + }; + } + if (!locationIsValid(mappedPosition)) { + return { + line: lineToLine(line), + column: columnToColumn(column), + verified: false, + }; + } + const { line: oline, column: ocolumn } = mappedPosition; + return { + line: lineTo0BasedLine(oline), + column: columnToColumn(ocolumn), + verified: true, + }; + } +} + +class NoopSourceMap implements SourceMap { + generatedLocation(request: LocationRequest): Location { + const { line, column } = request; + return { + line: lineToLine(line), + column: columnToColumn(column), + verified: true, + }; + } + + originalLocation(request: LocationRequest): Location { + const { line, column } = request; + return { + line: lineToLine(line), + column: columnToColumn(column), + verified: true, + }; + } +} + +const defaultSourceMap = new NoopSourceMap(); + +export function SourceMap(url?: string): SourceMap { + if (!url || !url.startsWith("data:")) { + return defaultSourceMap; + } + try { + const [_, base64] = url.split(",", 2); + const decoded = Buffer.from(base64, "base64url").toString("utf8"); + const schema = JSON.parse(decoded); + const sourceMap = new SourceMapConsumer(schema); + return new ActualSourceMap(sourceMap); + } catch (error) { + console.warn("Failed to parse source map URL", url); + } + return defaultSourceMap; +} + +function lineTo1BasedLine(line?: number): number { + return numberIsValid(line) ? line + 1 : 1; +} + +function lineTo0BasedLine(line?: number): number { + return numberIsValid(line) ? line - 1 : 0; +} + +function lineToLine(line?: number): number { + return numberIsValid(line) ? line : 0; +} + +function columnToColumn(column?: number): number { + return numberIsValid(column) ? column : 0; +} + +function locationIsValid(location: Location): location is Location { + const { line, column } = location; + return numberIsValid(line) && numberIsValid(column); +} + +function numberIsValid(number?: number): number is number { + return typeof number === "number" && isFinite(number) && number >= 0; +} + +function unknownToError(error: unknown): string { + if (error instanceof Error) { + const { message } = error; + return message; + } + return String(error); +} diff --git a/packages/bun-debug-adapter-protocol/index.ts b/packages/bun-debug-adapter-protocol/index.ts new file mode 100644 index 000000000..567a57525 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/index.ts @@ -0,0 +1,2 @@ +export type * from "./protocol"; +export * from "./debugger/adapter"; diff --git a/packages/bun-debug-adapter-protocol/package.json b/packages/bun-debug-adapter-protocol/package.json new file mode 100644 index 000000000..8bf68cf01 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/package.json @@ -0,0 +1,8 @@ +{ + "name": "bun-debug-adapter-protocol", + "dependencies": { + "semver": "^7.5.4", + "ws": "^8.13.0", + "source-map-js": "^1.0.2" + } +} diff --git a/packages/bun-debug-adapter-protocol/protocol/index.d.ts b/packages/bun-debug-adapter-protocol/protocol/index.d.ts new file mode 100644 index 000000000..abf9ecdec --- /dev/null +++ b/packages/bun-debug-adapter-protocol/protocol/index.d.ts @@ -0,0 +1,2696 @@ +// GENERATED - DO NOT EDIT +export namespace DAP { + /** + * Base class of requests, responses, and events. + */ + export type ProtocolMessage = { + /** + * Sequence number of the message (also known as message ID). The `seq` for the first message sent by a client or debug adapter is 1, and for each subsequent message is 1 greater than the previous message sent by that actor. `seq` can be used to order requests, responses, and events, and to associate requests with their corresponding responses. For protocol messages of type `request` the sequence number can be used to cancel the request. + */ + seq: number; + /** + * Message type. + */ + type: string; + }; + export type Request = ProtocolMessage & { + type: "request"; + /** + * The command to execute. + */ + command: string; + /** + * Object containing arguments for the command. + */ + arguments?: unknown; + }; + export type Event = ProtocolMessage & { + type: "event"; + /** + * Type of event. + */ + event: string; + /** + * Event-specific information. + */ + body?: unknown; + }; + export type Response = ProtocolMessage & { + type: "response"; + /** + * Sequence number of the corresponding request. + */ + request_seq: number; + /** + * Outcome of the request. + * If true, the request was successful and the `body` attribute may contain the result of the request. + * If the value is false, the attribute `message` contains the error in short form and the `body` may contain additional information (see `ErrorResponse.body.error`). + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * Contains the raw error in short form if `success` is false. + * This raw error might be interpreted by the client and is not shown in the UI. + * Some predefined values exist. + */ + message?: string; + /** + * Contains request result if success is true and error details if success is false. + */ + body?: unknown; + }; + /** + * On error (whenever `success` is false), the body can provide more details. + */ + export type ErrorResponse = { + /** + * A structured error message. + */ + error?: Message; + }; + /** + * Arguments for `cancel` request. + */ + export type CancelRequest = { + /** + * The ID (attribute `seq`) of the request to cancel. If missing no request is cancelled. + * Both a `requestId` and a `progressId` can be specified in one request. + */ + requestId?: number; + /** + * The ID (attribute `progressId`) of the progress to cancel. If missing no progress is cancelled. + * Both a `requestId` and a `progressId` can be specified in one request. + */ + progressId?: string; + }; + /** + * Response to `cancel` request. This is just an acknowledgement, so no body field is required. + */ + export type CancelResponse = {}; + /** + * This event indicates that the debug adapter is ready to accept configuration requests (e.g. `setBreakpoints`, `setExceptionBreakpoints`). + * A debug adapter is expected to send this event when it is ready to accept configuration requests (but not before the `initialize` request has finished). + * The sequence of events/requests is as follows: + * - adapters sends `initialized` event (after the `initialize` request has returned) + * - client sends zero or more `setBreakpoints` requests + * - client sends one `setFunctionBreakpoints` request (if corresponding capability `supportsFunctionBreakpoints` is true) + * - client sends a `setExceptionBreakpoints` request if one or more `exceptionBreakpointFilters` have been defined (or if `supportsConfigurationDoneRequest` is not true) + * - client sends other future configuration requests + * - client sends one `configurationDone` request to indicate the end of the configuration. + */ + export type InitializedEvent = {}; + /** + * The event indicates that the execution of the debuggee has stopped due to some condition. + * This can be caused by a breakpoint previously set, a stepping request has completed, by executing a debugger statement etc. + */ + export type StoppedEvent = { + /** + * The reason for the event. + * For backward compatibility this string is shown in the UI if the `description` attribute is missing (but it must not be translated). + */ + reason: string; + /** + * The full reason for the event, e.g. 'Paused on exception'. This string is shown in the UI as is and can be translated. + */ + description?: string; + /** + * The thread which was stopped. + */ + threadId?: number; + /** + * A value of true hints to the client that this event should not change the focus. + */ + preserveFocusHint?: boolean; + /** + * Additional information. E.g. if reason is `exception`, text contains the exception name. This string is shown in the UI. + */ + text?: string; + /** + * If `allThreadsStopped` is true, a debug adapter can announce that all threads have stopped. + * - The client should use this information to enable that all threads can be expanded to access their stacktraces. + * - If the attribute is missing or false, only the thread with the given `threadId` can be expanded. + */ + allThreadsStopped?: boolean; + /** + * Ids of the breakpoints that triggered the event. In most cases there is only a single breakpoint but here are some examples for multiple breakpoints: + * - Different types of breakpoints map to the same location. + * - Multiple source breakpoints get collapsed to the same instruction by the compiler/runtime. + * - Multiple function breakpoints with different function names map to the same location. + */ + hitBreakpointIds?: number[]; + }; + /** + * The event indicates that the execution of the debuggee has continued. + * Please note: a debug adapter is not expected to send this event in response to a request that implies that execution continues, e.g. `launch` or `continue`. + * It is only necessary to send a `continued` event if there was no previous request that implied this. + */ + export type ContinuedEvent = { + /** + * The thread which was continued. + */ + threadId: number; + /** + * If `allThreadsContinued` is true, a debug adapter can announce that all threads have continued. + */ + allThreadsContinued?: boolean; + }; + /** + * The event indicates that the debuggee has exited and returns its exit code. + */ + export type ExitedEvent = { + /** + * The exit code returned from the debuggee. + */ + exitCode: number; + }; + /** + * The event indicates that debugging of the debuggee has terminated. This does **not** mean that the debuggee itself has exited. + */ + export type TerminatedEvent = { + /** + * A debug adapter may set `restart` to true (or to an arbitrary object) to request that the client restarts the session. + * The value is not interpreted by the client and passed unmodified as an attribute `__restart` to the `launch` and `attach` requests. + */ + restart?: unknown; + }; + /** + * The event indicates that a thread has started or exited. + */ + export type ThreadEvent = { + /** + * The reason for the event. + */ + reason: string; + /** + * The identifier of the thread. + */ + threadId: number; + }; + /** + * The event indicates that the target has produced some output. + */ + export type OutputEvent = { + /** + * The output category. If not specified or if the category is not understood by the client, `console` is assumed. + */ + category?: string; + /** + * The output to report. + */ + output: string; + /** + * Support for keeping an output log organized by grouping related messages. + */ + group?: "start" | "startCollapsed" | "end"; + /** + * If an attribute `variablesReference` exists and its value is > 0, the output contains objects which can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. + */ + variablesReference?: number; + /** + * The source location where the output was produced. + */ + source?: Source; + /** + * The source location's line where the output was produced. + */ + line?: number; + /** + * The position in `line` where the output was produced. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + column?: number; + /** + * Additional data to report. For the `telemetry` category the data is sent to telemetry, for the other categories the data is shown in JSON format. + */ + data?: unknown; + }; + /** + * The event indicates that some information about a breakpoint has changed. + */ + export type BreakpointEvent = { + /** + * The reason for the event. + */ + reason: string; + /** + * The `id` attribute is used to find the target breakpoint, the other attributes are used as the new values. + */ + breakpoint: Breakpoint; + }; + /** + * The event indicates that some information about a module has changed. + */ + export type ModuleEvent = { + /** + * The reason for the event. + */ + reason: "new" | "changed" | "removed"; + /** + * The new, changed, or removed module. In case of `removed` only the module id is used. + */ + module: Module; + }; + /** + * The event indicates that some source has been added, changed, or removed from the set of all loaded sources. + */ + export type LoadedSourceEvent = { + /** + * The reason for the event. + */ + reason: "new" | "changed" | "removed"; + /** + * The new, changed, or removed source. + */ + source: Source; + }; + /** + * The event indicates that the debugger has begun debugging a new process. Either one that it has launched, or one that it has attached to. + */ + export type ProcessEvent = { + /** + * The logical name of the process. This is usually the full path to process's executable file. Example: /home/example/myproj/program.js. + */ + name: string; + /** + * The system process id of the debugged process. This property is missing for non-system processes. + */ + systemProcessId?: number; + /** + * If true, the process is running on the same computer as the debug adapter. + */ + isLocalProcess?: boolean; + /** + * Describes how the debug engine started debugging this process. + */ + startMethod?: "launch" | "attach" | "attachForSuspendedLaunch"; + /** + * The size of a pointer or address for this process, in bits. This value may be used by clients when formatting addresses for display. + */ + pointerSize?: number; + }; + /** + * The event indicates that one or more capabilities have changed. + * Since the capabilities are dependent on the client and its UI, it might not be possible to change that at random times (or too late). + * Consequently this event has a hint characteristic: a client can only be expected to make a 'best effort' in honoring individual capabilities but there are no guarantees. + * Only changed capabilities need to be included, all other capabilities keep their values. + */ + export type CapabilitiesEvent = { + /** + * The set of updated capabilities. + */ + capabilities: Capabilities; + }; + /** + * The event signals that a long running operation is about to start and provides additional information for the client to set up a corresponding progress and cancellation UI. + * The client is free to delay the showing of the UI in order to reduce flicker. + * This event should only be sent if the corresponding capability `supportsProgressReporting` is true. + */ + export type ProgressStartEvent = { + /** + * An ID that can be used in subsequent `progressUpdate` and `progressEnd` events to make them refer to the same progress reporting. + * IDs must be unique within a debug session. + */ + progressId: string; + /** + * Short title of the progress reporting. Shown in the UI to describe the long running operation. + */ + title: string; + /** + * The request ID that this progress report is related to. If specified a debug adapter is expected to emit progress events for the long running request until the request has been either completed or cancelled. + * If the request ID is omitted, the progress report is assumed to be related to some general activity of the debug adapter. + */ + requestId?: number; + /** + * If true, the request that reports progress may be cancelled with a `cancel` request. + * So this property basically controls whether the client should use UX that supports cancellation. + * Clients that don't support cancellation are allowed to ignore the setting. + */ + cancellable?: boolean; + /** + * More detailed progress message. + */ + message?: string; + /** + * Progress percentage to display (value range: 0 to 100). If omitted no percentage is shown. + */ + percentage?: number; + }; + /** + * The event signals that the progress reporting needs to be updated with a new message and/or percentage. + * The client does not have to update the UI immediately, but the clients needs to keep track of the message and/or percentage values. + * This event should only be sent if the corresponding capability `supportsProgressReporting` is true. + */ + export type ProgressUpdateEvent = { + /** + * The ID that was introduced in the initial `progressStart` event. + */ + progressId: string; + /** + * More detailed progress message. If omitted, the previous message (if any) is used. + */ + message?: string; + /** + * Progress percentage to display (value range: 0 to 100). If omitted no percentage is shown. + */ + percentage?: number; + }; + /** + * The event signals the end of the progress reporting with a final message. + * This event should only be sent if the corresponding capability `supportsProgressReporting` is true. + */ + export type ProgressEndEvent = { + /** + * The ID that was introduced in the initial `ProgressStartEvent`. + */ + progressId: string; + /** + * More detailed progress message. If omitted, the previous message (if any) is used. + */ + message?: string; + }; + /** + * This event signals that some state in the debug adapter has changed and requires that the client needs to re-render the data snapshot previously requested. + * Debug adapters do not have to emit this event for runtime changes like stopped or thread events because in that case the client refetches the new state anyway. But the event can be used for example to refresh the UI after rendering formatting has changed in the debug adapter. + * This event should only be sent if the corresponding capability `supportsInvalidatedEvent` is true. + */ + export type InvalidatedEvent = { + /** + * Set of logical areas that got invalidated. This property has a hint characteristic: a client can only be expected to make a 'best effort' in honoring the areas but there are no guarantees. If this property is missing, empty, or if values are not understood, the client should assume a single value `all`. + */ + areas?: InvalidatedAreas[]; + /** + * If specified, the client only needs to refetch data related to this thread. + */ + threadId?: number; + /** + * If specified, the client only needs to refetch data related to this stack frame (and the `threadId` is ignored). + */ + stackFrameId?: number; + }; + /** + * This event indicates that some memory range has been updated. It should only be sent if the corresponding capability `supportsMemoryEvent` is true. + * Clients typically react to the event by re-issuing a `readMemory` request if they show the memory identified by the `memoryReference` and if the updated memory range overlaps the displayed range. Clients should not make assumptions how individual memory references relate to each other, so they should not assume that they are part of a single continuous address range and might overlap. + * Debug adapters can use this event to indicate that the contents of a memory range has changed due to some other request like `setVariable` or `setExpression`. Debug adapters are not expected to emit this event for each and every memory change of a running program, because that information is typically not available from debuggers and it would flood clients with too many events. + */ + export type MemoryEvent = { + /** + * Memory reference of a memory range that has been updated. + */ + memoryReference: string; + /** + * Starting offset in bytes where memory has been updated. Can be negative. + */ + offset: number; + /** + * Number of bytes updated. + */ + count: number; + }; + /** + * Arguments for `runInTerminal` request. + */ + export type RunInTerminalRequest = { + /** + * What kind of terminal to launch. Defaults to `integrated` if not specified. + */ + kind?: "integrated" | "external"; + /** + * Title of the terminal. + */ + title?: string; + /** + * Working directory for the command. For non-empty, valid paths this typically results in execution of a change directory command. + */ + cwd: string; + /** + * List of arguments. The first argument is the command to run. + */ + args: string[]; + /** + * Environment key-value pairs that are added to or removed from the default environment. + */ + env?: {}; + /** + * This property should only be set if the corresponding capability `supportsArgsCanBeInterpretedByShell` is true. If the client uses an intermediary shell to launch the application, then the client must not attempt to escape characters with special meanings for the shell. The user is fully responsible for escaping as needed and that arguments using special characters may not be portable across shells. + */ + argsCanBeInterpretedByShell?: boolean; + }; + /** + * Response to `runInTerminal` request. + */ + export type RunInTerminalResponse = { + /** + * The process ID. The value should be less than or equal to 2147483647 (2^31-1). + */ + processId?: number; + /** + * The process ID of the terminal shell. The value should be less than or equal to 2147483647 (2^31-1). + */ + shellProcessId?: number; + }; + /** + * Arguments for `startDebugging` request. + */ + export type StartDebuggingRequest = { + /** + * Arguments passed to the new debug session. The arguments must only contain properties understood by the `launch` or `attach` requests of the debug adapter and they must not contain any client-specific properties (e.g. `type`) or client-specific features (e.g. substitutable 'variables'). + */ + configuration: {}; + /** + * Indicates whether the new debug session should be started with a `launch` or `attach` request. + */ + request: "launch" | "attach"; + }; + /** + * Response to `startDebugging` request. This is just an acknowledgement, so no body field is required. + */ + export type StartDebuggingResponse = {}; + /** + * Arguments for `initialize` request. + */ + export type InitializeRequest = { + /** + * The ID of the client using this adapter. + */ + clientID?: string; + /** + * The human-readable name of the client using this adapter. + */ + clientName?: string; + /** + * The ID of the debug adapter. + */ + adapterID: string; + /** + * The ISO-639 locale of the client using this adapter, e.g. en-US or de-CH. + */ + locale?: string; + /** + * If true all line numbers are 1-based (default). + */ + linesStartAt1?: boolean; + /** + * If true all column numbers are 1-based (default). + */ + columnsStartAt1?: boolean; + /** + * Determines in what format paths are specified. The default is `path`, which is the native format. + */ + pathFormat?: string; + /** + * Client supports the `type` attribute for variables. + */ + supportsVariableType?: boolean; + /** + * Client supports the paging of variables. + */ + supportsVariablePaging?: boolean; + /** + * Client supports the `runInTerminal` request. + */ + supportsRunInTerminalRequest?: boolean; + /** + * Client supports memory references. + */ + supportsMemoryReferences?: boolean; + /** + * Client supports progress reporting. + */ + supportsProgressReporting?: boolean; + /** + * Client supports the `invalidated` event. + */ + supportsInvalidatedEvent?: boolean; + /** + * Client supports the `memory` event. + */ + supportsMemoryEvent?: boolean; + /** + * Client supports the `argsCanBeInterpretedByShell` attribute on the `runInTerminal` request. + */ + supportsArgsCanBeInterpretedByShell?: boolean; + /** + * Client supports the `startDebugging` request. + */ + supportsStartDebuggingRequest?: boolean; + }; + /** + * The capabilities of this debug adapter. + */ + export type InitializeResponse = {}; + /** + * Arguments for `configurationDone` request. + */ + export type ConfigurationDoneRequest = {}; + /** + * Response to `configurationDone` request. This is just an acknowledgement, so no body field is required. + */ + export type ConfigurationDoneResponse = {}; + /** + * Arguments for `launch` request. Additional attributes are implementation specific. + */ + export type LaunchRequest = { + /** + * If true, the launch request should launch the program without enabling debugging. + */ + noDebug?: boolean; + /** + * Arbitrary data from the previous, restarted session. + * The data is sent as the `restart` attribute of the `terminated` event. + * The client should leave the data intact. + */ + __restart?: unknown; + }; + /** + * Response to `launch` request. This is just an acknowledgement, so no body field is required. + */ + export type LaunchResponse = {}; + /** + * Arguments for `attach` request. Additional attributes are implementation specific. + */ + export type AttachRequest = { + /** + * Arbitrary data from the previous, restarted session. + * The data is sent as the `restart` attribute of the `terminated` event. + * The client should leave the data intact. + */ + __restart?: unknown; + }; + /** + * Response to `attach` request. This is just an acknowledgement, so no body field is required. + */ + export type AttachResponse = {}; + /** + * Arguments for `restart` request. + */ + export type RestartRequest = { + /** + * The latest version of the `launch` or `attach` configuration. + */ + arguments?: unknown; + }; + /** + * Response to `restart` request. This is just an acknowledgement, so no body field is required. + */ + export type RestartResponse = {}; + /** + * Arguments for `disconnect` request. + */ + export type DisconnectRequest = { + /** + * A value of true indicates that this `disconnect` request is part of a restart sequence. + */ + restart?: boolean; + /** + * Indicates whether the debuggee should be terminated when the debugger is disconnected. + * If unspecified, the debug adapter is free to do whatever it thinks is best. + * The attribute is only honored by a debug adapter if the corresponding capability `supportTerminateDebuggee` is true. + */ + terminateDebuggee?: boolean; + /** + * Indicates whether the debuggee should stay suspended when the debugger is disconnected. + * If unspecified, the debuggee should resume execution. + * The attribute is only honored by a debug adapter if the corresponding capability `supportSuspendDebuggee` is true. + */ + suspendDebuggee?: boolean; + }; + /** + * Response to `disconnect` request. This is just an acknowledgement, so no body field is required. + */ + export type DisconnectResponse = {}; + /** + * Arguments for `terminate` request. + */ + export type TerminateRequest = { + /** + * A value of true indicates that this `terminate` request is part of a restart sequence. + */ + restart?: boolean; + }; + /** + * Response to `terminate` request. This is just an acknowledgement, so no body field is required. + */ + export type TerminateResponse = {}; + /** + * Arguments for `breakpointLocations` request. + */ + export type BreakpointLocationsRequest = { + /** + * The source location of the breakpoints; either `source.path` or `source.reference` must be specified. + */ + source: Source; + /** + * Start line of range to search possible breakpoint locations in. If only the line is specified, the request returns all possible locations in that line. + */ + line: number; + /** + * Start position within `line` to search possible breakpoint locations in. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. If no column is given, the first position in the start line is assumed. + */ + column?: number; + /** + * End line of range to search possible breakpoint locations in. If no end line is given, then the end line is assumed to be the start line. + */ + endLine?: number; + /** + * End position within `endLine` to search possible breakpoint locations in. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. If no end column is given, the last position in the end line is assumed. + */ + endColumn?: number; + }; + /** + * Response to `breakpointLocations` request. + * Contains possible locations for source breakpoints. + */ + export type BreakpointLocationsResponse = { + /** + * Sorted set of possible breakpoint locations. + */ + breakpoints: BreakpointLocation[]; + }; + /** + * Arguments for `setBreakpoints` request. + */ + export type SetBreakpointsRequest = { + /** + * The source location of the breakpoints; either `source.path` or `source.sourceReference` must be specified. + */ + source: Source; + /** + * The code locations of the breakpoints. + */ + breakpoints?: SourceBreakpoint[]; + /** + * Deprecated: The code locations of the breakpoints. + */ + lines?: number[]; + /** + * A value of true indicates that the underlying source has been modified which results in new breakpoint locations. + */ + sourceModified?: boolean; + }; + /** + * Response to `setBreakpoints` request. + * Returned is information about each breakpoint created by this request. + * This includes the actual code location and whether the breakpoint could be verified. + * The breakpoints returned are in the same order as the elements of the `breakpoints` + * (or the deprecated `lines`) array in the arguments. + */ + export type SetBreakpointsResponse = { + /** + * Information about the breakpoints. + * The array elements are in the same order as the elements of the `breakpoints` (or the deprecated `lines`) array in the arguments. + */ + breakpoints: Breakpoint[]; + }; + /** + * Arguments for `setFunctionBreakpoints` request. + */ + export type SetFunctionBreakpointsRequest = { + /** + * The function names of the breakpoints. + */ + breakpoints: FunctionBreakpoint[]; + }; + /** + * Response to `setFunctionBreakpoints` request. + * Returned is information about each breakpoint created by this request. + */ + export type SetFunctionBreakpointsResponse = { + /** + * Information about the breakpoints. The array elements correspond to the elements of the `breakpoints` array. + */ + breakpoints: Breakpoint[]; + }; + /** + * Arguments for `setExceptionBreakpoints` request. + */ + export type SetExceptionBreakpointsRequest = { + /** + * Set of exception filters specified by their ID. The set of all possible exception filters is defined by the `exceptionBreakpointFilters` capability. The `filter` and `filterOptions` sets are additive. + */ + filters: string[]; + /** + * Set of exception filters and their options. The set of all possible exception filters is defined by the `exceptionBreakpointFilters` capability. This attribute is only honored by a debug adapter if the corresponding capability `supportsExceptionFilterOptions` is true. The `filter` and `filterOptions` sets are additive. + */ + filterOptions?: ExceptionFilterOptions[]; + /** + * Configuration options for selected exceptions. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsExceptionOptions` is true. + */ + exceptionOptions?: ExceptionOptions[]; + }; + /** + * Response to `setExceptionBreakpoints` request. + * The response contains an array of `Breakpoint` objects with information about each exception breakpoint or filter. The `Breakpoint` objects are in the same order as the elements of the `filters`, `filterOptions`, `exceptionOptions` arrays given as arguments. If both `filters` and `filterOptions` are given, the returned array must start with `filters` information first, followed by `filterOptions` information. + * The `verified` property of a `Breakpoint` object signals whether the exception breakpoint or filter could be successfully created and whether the condition is valid. In case of an error the `message` property explains the problem. The `id` property can be used to introduce a unique ID for the exception breakpoint or filter so that it can be updated subsequently by sending breakpoint events. + * For backward compatibility both the `breakpoints` array and the enclosing `body` are optional. If these elements are missing a client is not able to show problems for individual exception breakpoints or filters. + */ + export type SetExceptionBreakpointsResponse = { + /** + * Information about the exception breakpoints or filters. + * The breakpoints returned are in the same order as the elements of the `filters`, `filterOptions`, `exceptionOptions` arrays in the arguments. If both `filters` and `filterOptions` are given, the returned array must start with `filters` information first, followed by `filterOptions` information. + */ + breakpoints?: Breakpoint[]; + }; + /** + * Arguments for `dataBreakpointInfo` request. + */ + export type DataBreakpointInfoRequest = { + /** + * Reference to the variable container if the data breakpoint is requested for a child of the container. The `variablesReference` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. + */ + variablesReference?: number; + /** + * The name of the variable's child to obtain data breakpoint information for. + * If `variablesReference` isn't specified, this can be an expression. + */ + name: string; + /** + * When `name` is an expression, evaluate it in the scope of this stack frame. If not specified, the expression is evaluated in the global scope. When `variablesReference` is specified, this property has no effect. + */ + frameId?: number; + }; + /** + * Response to `dataBreakpointInfo` request. + */ + export type DataBreakpointInfoResponse = { + /** + * An identifier for the data on which a data breakpoint can be registered with the `setDataBreakpoints` request or null if no data breakpoint is available. If a `variablesReference` or `frameId` is passed, the `dataId` is valid in the current suspended state, otherwise it's valid indefinitely. See 'Lifetime of Object References' in the Overview section for details. Breakpoints set using the `dataId` in the `setDataBreakpoints` request may outlive the lifetime of the associated `dataId`. + */ + dataId: unknown; + /** + * UI string that describes on what data the breakpoint is set on or why a data breakpoint is not available. + */ + description: string; + /** + * Attribute lists the available access types for a potential data breakpoint. A UI client could surface this information. + */ + accessTypes?: DataBreakpointAccessType[]; + /** + * Attribute indicates that a potential data breakpoint could be persisted across sessions. + */ + canPersist?: boolean; + }; + /** + * Arguments for `setDataBreakpoints` request. + */ + export type SetDataBreakpointsRequest = { + /** + * The contents of this array replaces all existing data breakpoints. An empty array clears all data breakpoints. + */ + breakpoints: DataBreakpoint[]; + }; + /** + * Response to `setDataBreakpoints` request. + * Returned is information about each breakpoint created by this request. + */ + export type SetDataBreakpointsResponse = { + /** + * Information about the data breakpoints. The array elements correspond to the elements of the input argument `breakpoints` array. + */ + breakpoints: Breakpoint[]; + }; + /** + * Arguments for `setInstructionBreakpoints` request + */ + export type SetInstructionBreakpointsRequest = { + /** + * The instruction references of the breakpoints + */ + breakpoints: InstructionBreakpoint[]; + }; + /** + * Response to `setInstructionBreakpoints` request + */ + export type SetInstructionBreakpointsResponse = { + /** + * Information about the breakpoints. The array elements correspond to the elements of the `breakpoints` array. + */ + breakpoints: Breakpoint[]; + }; + /** + * Arguments for `continue` request. + */ + export type ContinueRequest = { + /** + * Specifies the active thread. If the debug adapter supports single thread execution (see `supportsSingleThreadExecutionRequests`) and the argument `singleThread` is true, only the thread with this ID is resumed. + */ + threadId: number; + /** + * If this flag is true, execution is resumed only for the thread with given `threadId`. + */ + singleThread?: boolean; + }; + /** + * Response to `continue` request. + */ + export type ContinueResponse = { + /** + * The value true (or a missing property) signals to the client that all threads have been resumed. The value false indicates that not all threads were resumed. + */ + allThreadsContinued?: boolean; + }; + /** + * Arguments for `next` request. + */ + export type NextRequest = { + /** + * Specifies the thread for which to resume execution for one step (of the given granularity). + */ + threadId: number; + /** + * If this flag is true, all other suspended threads are not resumed. + */ + singleThread?: boolean; + /** + * Stepping granularity. If no granularity is specified, a granularity of `statement` is assumed. + */ + granularity?: SteppingGranularity; + }; + /** + * Response to `next` request. This is just an acknowledgement, so no body field is required. + */ + export type NextResponse = {}; + /** + * Arguments for `stepIn` request. + */ + export type StepInRequest = { + /** + * Specifies the thread for which to resume execution for one step-into (of the given granularity). + */ + threadId: number; + /** + * If this flag is true, all other suspended threads are not resumed. + */ + singleThread?: boolean; + /** + * Id of the target to step into. + */ + targetId?: number; + /** + * Stepping granularity. If no granularity is specified, a granularity of `statement` is assumed. + */ + granularity?: SteppingGranularity; + }; + /** + * Response to `stepIn` request. This is just an acknowledgement, so no body field is required. + */ + export type StepInResponse = {}; + /** + * Arguments for `stepOut` request. + */ + export type StepOutRequest = { + /** + * Specifies the thread for which to resume execution for one step-out (of the given granularity). + */ + threadId: number; + /** + * If this flag is true, all other suspended threads are not resumed. + */ + singleThread?: boolean; + /** + * Stepping granularity. If no granularity is specified, a granularity of `statement` is assumed. + */ + granularity?: SteppingGranularity; + }; + /** + * Response to `stepOut` request. This is just an acknowledgement, so no body field is required. + */ + export type StepOutResponse = {}; + /** + * Arguments for `stepBack` request. + */ + export type StepBackRequest = { + /** + * Specifies the thread for which to resume execution for one step backwards (of the given granularity). + */ + threadId: number; + /** + * If this flag is true, all other suspended threads are not resumed. + */ + singleThread?: boolean; + /** + * Stepping granularity to step. If no granularity is specified, a granularity of `statement` is assumed. + */ + granularity?: SteppingGranularity; + }; + /** + * Response to `stepBack` request. This is just an acknowledgement, so no body field is required. + */ + export type StepBackResponse = {}; + /** + * Arguments for `reverseContinue` request. + */ + export type ReverseContinueRequest = { + /** + * Specifies the active thread. If the debug adapter supports single thread execution (see `supportsSingleThreadExecutionRequests`) and the `singleThread` argument is true, only the thread with this ID is resumed. + */ + threadId: number; + /** + * If this flag is true, backward execution is resumed only for the thread with given `threadId`. + */ + singleThread?: boolean; + }; + /** + * Response to `reverseContinue` request. This is just an acknowledgement, so no body field is required. + */ + export type ReverseContinueResponse = {}; + /** + * Arguments for `restartFrame` request. + */ + export type RestartFrameRequest = { + /** + * Restart the stack frame identified by `frameId`. The `frameId` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. + */ + frameId: number; + }; + /** + * Response to `restartFrame` request. This is just an acknowledgement, so no body field is required. + */ + export type RestartFrameResponse = {}; + /** + * Arguments for `goto` request. + */ + export type GotoRequest = { + /** + * Set the goto target for this thread. + */ + threadId: number; + /** + * The location where the debuggee will continue to run. + */ + targetId: number; + }; + /** + * Response to `goto` request. This is just an acknowledgement, so no body field is required. + */ + export type GotoResponse = {}; + /** + * Arguments for `pause` request. + */ + export type PauseRequest = { + /** + * Pause execution for this thread. + */ + threadId: number; + }; + /** + * Response to `pause` request. This is just an acknowledgement, so no body field is required. + */ + export type PauseResponse = {}; + /** + * Arguments for `stackTrace` request. + */ + export type StackTraceRequest = { + /** + * Retrieve the stacktrace for this thread. + */ + threadId: number; + /** + * The index of the first frame to return; if omitted frames start at 0. + */ + startFrame?: number; + /** + * The maximum number of frames to return. If levels is not specified or 0, all frames are returned. + */ + levels?: number; + /** + * Specifies details on how to format the stack frames. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsValueFormattingOptions` is true. + */ + format?: StackFrameFormat; + }; + /** + * Response to `stackTrace` request. + */ + export type StackTraceResponse = { + /** + * The frames of the stack frame. If the array has length zero, there are no stack frames available. + * This means that there is no location information available. + */ + stackFrames: StackFrame[]; + /** + * The total number of frames available in the stack. If omitted or if `totalFrames` is larger than the available frames, a client is expected to request frames until a request returns less frames than requested (which indicates the end of the stack). Returning monotonically increasing `totalFrames` values for subsequent requests can be used to enforce paging in the client. + */ + totalFrames?: number; + }; + /** + * Arguments for `scopes` request. + */ + export type ScopesRequest = { + /** + * Retrieve the scopes for the stack frame identified by `frameId`. The `frameId` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. + */ + frameId: number; + }; + /** + * Response to `scopes` request. + */ + export type ScopesResponse = { + /** + * The scopes of the stack frame. If the array has length zero, there are no scopes available. + */ + scopes: Scope[]; + }; + /** + * Arguments for `variables` request. + */ + export type VariablesRequest = { + /** + * The variable for which to retrieve its children. The `variablesReference` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. + */ + variablesReference: number; + /** + * Filter to limit the child variables to either named or indexed. If omitted, both types are fetched. + */ + filter?: "indexed" | "named"; + /** + * The index of the first variable to return; if omitted children start at 0. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsVariablePaging` is true. + */ + start?: number; + /** + * The number of variables to return. If count is missing or 0, all variables are returned. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsVariablePaging` is true. + */ + count?: number; + /** + * Specifies details on how to format the Variable values. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsValueFormattingOptions` is true. + */ + format?: ValueFormat; + }; + /** + * Response to `variables` request. + */ + export type VariablesResponse = { + /** + * All (or a range) of variables for the given variable reference. + */ + variables: Variable[]; + }; + /** + * Arguments for `setVariable` request. + */ + export type SetVariableRequest = { + /** + * The reference of the variable container. The `variablesReference` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. + */ + variablesReference: number; + /** + * The name of the variable in the container. + */ + name: string; + /** + * The value of the variable. + */ + value: string; + /** + * Specifies details on how to format the response value. + */ + format?: ValueFormat; + }; + /** + * Response to `setVariable` request. + */ + export type SetVariableResponse = { + /** + * The new value of the variable. + */ + value: string; + /** + * The type of the new value. Typically shown in the UI when hovering over the value. + */ + type?: string; + /** + * If `variablesReference` is > 0, the new value is structured and its children can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. + */ + variablesReference?: number; + /** + * The number of named child variables. + * The client can use this information to present the variables in a paged UI and fetch them in chunks. + * The value should be less than or equal to 2147483647 (2^31-1). + */ + namedVariables?: number; + /** + * The number of indexed child variables. + * The client can use this information to present the variables in a paged UI and fetch them in chunks. + * The value should be less than or equal to 2147483647 (2^31-1). + */ + indexedVariables?: number; + }; + /** + * Arguments for `source` request. + */ + export type SourceRequest = { + /** + * Specifies the source content to load. Either `source.path` or `source.sourceReference` must be specified. + */ + source?: Source; + /** + * The reference to the source. This is the same as `source.sourceReference`. + * This is provided for backward compatibility since old clients do not understand the `source` attribute. + */ + sourceReference: number; + }; + /** + * Response to `source` request. + */ + export type SourceResponse = { + /** + * Content of the source reference. + */ + content: string; + /** + * Content type (MIME type) of the source. + */ + mimeType?: string; + }; + /** + * Response to `threads` request. + */ + export type ThreadsResponse = { + /** + * All threads. + */ + threads: Thread[]; + }; + /** + * Arguments for `terminateThreads` request. + */ + export type TerminateThreadsRequest = { + /** + * Ids of threads to be terminated. + */ + threadIds?: number[]; + }; + /** + * Response to `terminateThreads` request. This is just an acknowledgement, no body field is required. + */ + export type TerminateThreadsResponse = {}; + /** + * Arguments for `modules` request. + */ + export type ModulesRequest = { + /** + * The index of the first module to return; if omitted modules start at 0. + */ + startModule?: number; + /** + * The number of modules to return. If `moduleCount` is not specified or 0, all modules are returned. + */ + moduleCount?: number; + }; + /** + * Response to `modules` request. + */ + export type ModulesResponse = { + /** + * All modules or range of modules. + */ + modules: Module[]; + /** + * The total number of modules available. + */ + totalModules?: number; + }; + /** + * Arguments for `loadedSources` request. + */ + export type LoadedSourcesRequest = {}; + /** + * Response to `loadedSources` request. + */ + export type LoadedSourcesResponse = { + /** + * Set of loaded sources. + */ + sources: Source[]; + }; + /** + * Arguments for `evaluate` request. + */ + export type EvaluateRequest = { + /** + * The expression to evaluate. + */ + expression: string; + /** + * Evaluate the expression in the scope of this stack frame. If not specified, the expression is evaluated in the global scope. + */ + frameId?: number; + /** + * The context in which the evaluate request is used. + */ + context?: string; + /** + * Specifies details on how to format the result. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsValueFormattingOptions` is true. + */ + format?: ValueFormat; + }; + /** + * Response to `evaluate` request. + */ + export type EvaluateResponse = { + /** + * The result of the evaluate request. + */ + result: string; + /** + * The type of the evaluate result. + * This attribute should only be returned by a debug adapter if the corresponding capability `supportsVariableType` is true. + */ + type?: string; + /** + * Properties of an evaluate result that can be used to determine how to render the result in the UI. + */ + presentationHint?: VariablePresentationHint; + /** + * If `variablesReference` is > 0, the evaluate result is structured and its children can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. + */ + variablesReference: number; + /** + * The number of named child variables. + * The client can use this information to present the variables in a paged UI and fetch them in chunks. + * The value should be less than or equal to 2147483647 (2^31-1). + */ + namedVariables?: number; + /** + * The number of indexed child variables. + * The client can use this information to present the variables in a paged UI and fetch them in chunks. + * The value should be less than or equal to 2147483647 (2^31-1). + */ + indexedVariables?: number; + /** + * A memory reference to a location appropriate for this result. + * For pointer type eval results, this is generally a reference to the memory address contained in the pointer. + * This attribute should be returned by a debug adapter if corresponding capability `supportsMemoryReferences` is true. + */ + memoryReference?: string; + }; + /** + * Arguments for `setExpression` request. + */ + export type SetExpressionRequest = { + /** + * The l-value expression to assign to. + */ + expression: string; + /** + * The value expression to assign to the l-value expression. + */ + value: string; + /** + * Evaluate the expressions in the scope of this stack frame. If not specified, the expressions are evaluated in the global scope. + */ + frameId?: number; + /** + * Specifies how the resulting value should be formatted. + */ + format?: ValueFormat; + }; + /** + * Response to `setExpression` request. + */ + export type SetExpressionResponse = { + /** + * The new value of the expression. + */ + value: string; + /** + * The type of the value. + * This attribute should only be returned by a debug adapter if the corresponding capability `supportsVariableType` is true. + */ + type?: string; + /** + * Properties of a value that can be used to determine how to render the result in the UI. + */ + presentationHint?: VariablePresentationHint; + /** + * If `variablesReference` is > 0, the evaluate result is structured and its children can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. + */ + variablesReference?: number; + /** + * The number of named child variables. + * The client can use this information to present the variables in a paged UI and fetch them in chunks. + * The value should be less than or equal to 2147483647 (2^31-1). + */ + namedVariables?: number; + /** + * The number of indexed child variables. + * The client can use this information to present the variables in a paged UI and fetch them in chunks. + * The value should be less than or equal to 2147483647 (2^31-1). + */ + indexedVariables?: number; + }; + /** + * Arguments for `stepInTargets` request. + */ + export type StepInTargetsRequest = { + /** + * The stack frame for which to retrieve the possible step-in targets. + */ + frameId: number; + }; + /** + * Response to `stepInTargets` request. + */ + export type StepInTargetsResponse = { + /** + * The possible step-in targets of the specified source location. + */ + targets: StepInTarget[]; + }; + /** + * Arguments for `gotoTargets` request. + */ + export type GotoTargetsRequest = { + /** + * The source location for which the goto targets are determined. + */ + source: Source; + /** + * The line location for which the goto targets are determined. + */ + line: number; + /** + * The position within `line` for which the goto targets are determined. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + column?: number; + }; + /** + * Response to `gotoTargets` request. + */ + export type GotoTargetsResponse = { + /** + * The possible goto targets of the specified location. + */ + targets: GotoTarget[]; + }; + /** + * Arguments for `completions` request. + */ + export type CompletionsRequest = { + /** + * Returns completions in the scope of this stack frame. If not specified, the completions are returned for the global scope. + */ + frameId?: number; + /** + * One or more source lines. Typically this is the text users have typed into the debug console before they asked for completion. + */ + text: string; + /** + * The position within `text` for which to determine the completion proposals. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + column: number; + /** + * A line for which to determine the completion proposals. If missing the first line of the text is assumed. + */ + line?: number; + }; + /** + * Response to `completions` request. + */ + export type CompletionsResponse = { + /** + * The possible completions for . + */ + targets: CompletionItem[]; + }; + /** + * Arguments for `exceptionInfo` request. + */ + export type ExceptionInfoRequest = { + /** + * Thread for which exception information should be retrieved. + */ + threadId: number; + }; + /** + * Response to `exceptionInfo` request. + */ + export type ExceptionInfoResponse = { + /** + * ID of the exception that was thrown. + */ + exceptionId: string; + /** + * Descriptive text for the exception. + */ + description?: string; + /** + * Mode that caused the exception notification to be raised. + */ + breakMode: ExceptionBreakMode; + /** + * Detailed information about the exception. + */ + details?: ExceptionDetails; + }; + /** + * Arguments for `readMemory` request. + */ + export type ReadMemoryRequest = { + /** + * Memory reference to the base location from which data should be read. + */ + memoryReference: string; + /** + * Offset (in bytes) to be applied to the reference location before reading data. Can be negative. + */ + offset?: number; + /** + * Number of bytes to read at the specified location and offset. + */ + count: number; + }; + /** + * Response to `readMemory` request. + */ + export type ReadMemoryResponse = { + /** + * The address of the first byte of data returned. + * Treated as a hex value if prefixed with `0x`, or as a decimal value otherwise. + */ + address: string; + /** + * The number of unreadable bytes encountered after the last successfully read byte. + * This can be used to determine the number of bytes that should be skipped before a subsequent `readMemory` request succeeds. + */ + unreadableBytes?: number; + /** + * The bytes read from memory, encoded using base64. If the decoded length of `data` is less than the requested `count` in the original `readMemory` request, and `unreadableBytes` is zero or omitted, then the client should assume it's reached the end of readable memory. + */ + data?: string; + }; + /** + * Arguments for `writeMemory` request. + */ + export type WriteMemoryRequest = { + /** + * Memory reference to the base location to which data should be written. + */ + memoryReference: string; + /** + * Offset (in bytes) to be applied to the reference location before writing data. Can be negative. + */ + offset?: number; + /** + * Property to control partial writes. If true, the debug adapter should attempt to write memory even if the entire memory region is not writable. In such a case the debug adapter should stop after hitting the first byte of memory that cannot be written and return the number of bytes written in the response via the `offset` and `bytesWritten` properties. + * If false or missing, a debug adapter should attempt to verify the region is writable before writing, and fail the response if it is not. + */ + allowPartial?: boolean; + /** + * Bytes to write, encoded using base64. + */ + data: string; + }; + /** + * Response to `writeMemory` request. + */ + export type WriteMemoryResponse = { + /** + * Property that should be returned when `allowPartial` is true to indicate the offset of the first byte of data successfully written. Can be negative. + */ + offset?: number; + /** + * Property that should be returned when `allowPartial` is true to indicate the number of bytes starting from address that were successfully written. + */ + bytesWritten?: number; + }; + /** + * Arguments for `disassemble` request. + */ + export type DisassembleRequest = { + /** + * Memory reference to the base location containing the instructions to disassemble. + */ + memoryReference: string; + /** + * Offset (in bytes) to be applied to the reference location before disassembling. Can be negative. + */ + offset?: number; + /** + * Offset (in instructions) to be applied after the byte offset (if any) before disassembling. Can be negative. + */ + instructionOffset?: number; + /** + * Number of instructions to disassemble starting at the specified location and offset. + * An adapter must return exactly this number of instructions - any unavailable instructions should be replaced with an implementation-defined 'invalid instruction' value. + */ + instructionCount: number; + /** + * If true, the adapter should attempt to resolve memory addresses and other values to symbolic names. + */ + resolveSymbols?: boolean; + }; + /** + * Response to `disassemble` request. + */ + export type DisassembleResponse = { + /** + * The list of disassembled instructions. + */ + instructions: DisassembledInstruction[]; + }; + /** + * Information about the capabilities of a debug adapter. + */ + export type Capabilities = { + /** + * The debug adapter supports the `configurationDone` request. + */ + supportsConfigurationDoneRequest?: boolean; + /** + * The debug adapter supports function breakpoints. + */ + supportsFunctionBreakpoints?: boolean; + /** + * The debug adapter supports conditional breakpoints. + */ + supportsConditionalBreakpoints?: boolean; + /** + * The debug adapter supports breakpoints that break execution after a specified number of hits. + */ + supportsHitConditionalBreakpoints?: boolean; + /** + * The debug adapter supports a (side effect free) `evaluate` request for data hovers. + */ + supportsEvaluateForHovers?: boolean; + /** + * Available exception filter options for the `setExceptionBreakpoints` request. + */ + exceptionBreakpointFilters?: ExceptionBreakpointsFilter[]; + /** + * The debug adapter supports stepping back via the `stepBack` and `reverseContinue` requests. + */ + supportsStepBack?: boolean; + /** + * The debug adapter supports setting a variable to a value. + */ + supportsSetVariable?: boolean; + /** + * The debug adapter supports restarting a frame. + */ + supportsRestartFrame?: boolean; + /** + * The debug adapter supports the `gotoTargets` request. + */ + supportsGotoTargetsRequest?: boolean; + /** + * The debug adapter supports the `stepInTargets` request. + */ + supportsStepInTargetsRequest?: boolean; + /** + * The debug adapter supports the `completions` request. + */ + supportsCompletionsRequest?: boolean; + /** + * The set of characters that should trigger completion in a REPL. If not specified, the UI should assume the `.` character. + */ + completionTriggerCharacters?: string[]; + /** + * The debug adapter supports the `modules` request. + */ + supportsModulesRequest?: boolean; + /** + * The set of additional module information exposed by the debug adapter. + */ + additionalModuleColumns?: ColumnDescriptor[]; + /** + * Checksum algorithms supported by the debug adapter. + */ + supportedChecksumAlgorithms?: ChecksumAlgorithm[]; + /** + * The debug adapter supports the `restart` request. In this case a client should not implement `restart` by terminating and relaunching the adapter but by calling the `restart` request. + */ + supportsRestartRequest?: boolean; + /** + * The debug adapter supports `exceptionOptions` on the `setExceptionBreakpoints` request. + */ + supportsExceptionOptions?: boolean; + /** + * The debug adapter supports a `format` attribute on the `stackTrace`, `variables`, and `evaluate` requests. + */ + supportsValueFormattingOptions?: boolean; + /** + * The debug adapter supports the `exceptionInfo` request. + */ + supportsExceptionInfoRequest?: boolean; + /** + * The debug adapter supports the `terminateDebuggee` attribute on the `disconnect` request. + */ + supportTerminateDebuggee?: boolean; + /** + * The debug adapter supports the `suspendDebuggee` attribute on the `disconnect` request. + */ + supportSuspendDebuggee?: boolean; + /** + * The debug adapter supports the delayed loading of parts of the stack, which requires that both the `startFrame` and `levels` arguments and the `totalFrames` result of the `stackTrace` request are supported. + */ + supportsDelayedStackTraceLoading?: boolean; + /** + * The debug adapter supports the `loadedSources` request. + */ + supportsLoadedSourcesRequest?: boolean; + /** + * The debug adapter supports log points by interpreting the `logMessage` attribute of the `SourceBreakpoint`. + */ + supportsLogPoints?: boolean; + /** + * The debug adapter supports the `terminateThreads` request. + */ + supportsTerminateThreadsRequest?: boolean; + /** + * The debug adapter supports the `setExpression` request. + */ + supportsSetExpression?: boolean; + /** + * The debug adapter supports the `terminate` request. + */ + supportsTerminateRequest?: boolean; + /** + * The debug adapter supports data breakpoints. + */ + supportsDataBreakpoints?: boolean; + /** + * The debug adapter supports the `readMemory` request. + */ + supportsReadMemoryRequest?: boolean; + /** + * The debug adapter supports the `writeMemory` request. + */ + supportsWriteMemoryRequest?: boolean; + /** + * The debug adapter supports the `disassemble` request. + */ + supportsDisassembleRequest?: boolean; + /** + * The debug adapter supports the `cancel` request. + */ + supportsCancelRequest?: boolean; + /** + * The debug adapter supports the `breakpointLocations` request. + */ + supportsBreakpointLocationsRequest?: boolean; + /** + * The debug adapter supports the `clipboard` context value in the `evaluate` request. + */ + supportsClipboardContext?: boolean; + /** + * The debug adapter supports stepping granularities (argument `granularity`) for the stepping requests. + */ + supportsSteppingGranularity?: boolean; + /** + * The debug adapter supports adding breakpoints based on instruction references. + */ + supportsInstructionBreakpoints?: boolean; + /** + * The debug adapter supports `filterOptions` as an argument on the `setExceptionBreakpoints` request. + */ + supportsExceptionFilterOptions?: boolean; + /** + * The debug adapter supports the `singleThread` property on the execution requests (`continue`, `next`, `stepIn`, `stepOut`, `reverseContinue`, `stepBack`). + */ + supportsSingleThreadExecutionRequests?: boolean; + }; + /** + * An `ExceptionBreakpointsFilter` is shown in the UI as an filter option for configuring how exceptions are dealt with. + */ + export type ExceptionBreakpointsFilter = { + /** + * The internal ID of the filter option. This value is passed to the `setExceptionBreakpoints` request. + */ + filter: string; + /** + * The name of the filter option. This is shown in the UI. + */ + label: string; + /** + * A help text providing additional information about the exception filter. This string is typically shown as a hover and can be translated. + */ + description?: string; + /** + * Initial value of the filter option. If not specified a value false is assumed. + */ + default?: boolean; + /** + * Controls whether a condition can be specified for this filter option. If false or missing, a condition can not be set. + */ + supportsCondition?: boolean; + /** + * A help text providing information about the condition. This string is shown as the placeholder text for a text box and can be translated. + */ + conditionDescription?: string; + }; + /** + * A structured message object. Used to return errors from requests. + */ + export type Message = { + /** + * Unique (within a debug adapter implementation) identifier for the message. The purpose of these error IDs is to help extension authors that have the requirement that every user visible error message needs a corresponding error number, so that users or customer support can find information about the specific error more easily. + */ + id: number; + /** + * A format string for the message. Embedded variables have the form `{name}`. + * If variable name starts with an underscore character, the variable does not contain user data (PII) and can be safely used for telemetry purposes. + */ + format: string; + /** + * An object used as a dictionary for looking up the variables in the format string. + */ + variables?: {}; + /** + * If true send to telemetry. + */ + sendTelemetry?: boolean; + /** + * If true show user. + */ + showUser?: boolean; + /** + * A url where additional information about this message can be found. + */ + url?: string; + /** + * A label that is presented to the user as the UI for opening the url. + */ + urlLabel?: string; + }; + /** + * A Module object represents a row in the modules view. + * The `id` attribute identifies a module in the modules view and is used in a `module` event for identifying a module for adding, updating or deleting. + * The `name` attribute is used to minimally render the module in the UI. + * + * Additional attributes can be added to the module. They show up in the module view if they have a corresponding `ColumnDescriptor`. + * + * To avoid an unnecessary proliferation of additional attributes with similar semantics but different names, we recommend to re-use attributes from the 'recommended' list below first, and only introduce new attributes if nothing appropriate could be found. + */ + export type Module = { + /** + * Unique identifier for the module. + */ + id: unknown; + /** + * A name of the module. + */ + name: string; + /** + * Logical full path to the module. The exact definition is implementation defined, but usually this would be a full path to the on-disk file for the module. + */ + path?: string; + /** + * True if the module is optimized. + */ + isOptimized?: boolean; + /** + * True if the module is considered 'user code' by a debugger that supports 'Just My Code'. + */ + isUserCode?: boolean; + /** + * Version of Module. + */ + version?: string; + /** + * User-understandable description of if symbols were found for the module (ex: 'Symbols Loaded', 'Symbols not found', etc.) + */ + symbolStatus?: string; + /** + * Logical full path to the symbol file. The exact definition is implementation defined. + */ + symbolFilePath?: string; + /** + * Module created or modified, encoded as a RFC 3339 timestamp. + */ + dateTimeStamp?: string; + /** + * Address range covered by this module. + */ + addressRange?: string; + }; + /** + * A `ColumnDescriptor` specifies what module attribute to show in a column of the modules view, how to format it, + * and what the column's label should be. + * It is only used if the underlying UI actually supports this level of customization. + */ + export type ColumnDescriptor = { + /** + * Name of the attribute rendered in this column. + */ + attributeName: string; + /** + * Header UI label of column. + */ + label: string; + /** + * Format to use for the rendered values in this column. TBD how the format strings looks like. + */ + format?: string; + /** + * Datatype of values in this column. Defaults to `string` if not specified. + */ + type?: "string" | "number" | "boolean" | "unixTimestampUTC"; + /** + * Width of this column in characters (hint only). + */ + width?: number; + }; + /** + * A Thread + */ + export type Thread = { + /** + * Unique identifier for the thread. + */ + id: number; + /** + * The name of the thread. + */ + name: string; + }; + /** + * A `Source` is a descriptor for source code. + * It is returned from the debug adapter as part of a `StackFrame` and it is used by clients when specifying breakpoints. + */ + export type Source = { + /** + * The short name of the source. Every source returned from the debug adapter has a name. + * When sending a source to the debug adapter this name is optional. + */ + name?: string; + /** + * The path of the source to be shown in the UI. + * It is only used to locate and load the content of the source if no `sourceReference` is specified (or its value is 0). + */ + path?: string; + /** + * If the value > 0 the contents of the source must be retrieved through the `source` request (even if a path is specified). + * Since a `sourceReference` is only valid for a session, it can not be used to persist a source. + * The value should be less than or equal to 2147483647 (2^31-1). + */ + sourceReference?: number; + /** + * A hint for how to present the source in the UI. + * A value of `deemphasize` can be used to indicate that the source is not available or that it is skipped on stepping. + */ + presentationHint?: "normal" | "emphasize" | "deemphasize"; + /** + * The origin of this source. For example, 'internal module', 'inlined content from source map', etc. + */ + origin?: string; + /** + * A list of sources that are related to this source. These may be the source that generated this source. + */ + sources?: Source[]; + /** + * Additional data that a debug adapter might want to loop through the client. + * The client should leave the data intact and persist it across sessions. The client should not interpret the data. + */ + adapterData?: unknown; + /** + * The checksums associated with this file. + */ + checksums?: Checksum[]; + }; + /** + * A Stackframe contains the source location. + */ + export type StackFrame = { + /** + * An identifier for the stack frame. It must be unique across all threads. + * This id can be used to retrieve the scopes of the frame with the `scopes` request or to restart the execution of a stack frame. + */ + id: number; + /** + * The name of the stack frame, typically a method name. + */ + name: string; + /** + * The source of the frame. + */ + source?: Source; + /** + * The line within the source of the frame. If the source attribute is missing or doesn't exist, `line` is 0 and should be ignored by the client. + */ + line: number; + /** + * Start position of the range covered by the stack frame. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. If attribute `source` is missing or doesn't exist, `column` is 0 and should be ignored by the client. + */ + column: number; + /** + * The end line of the range covered by the stack frame. + */ + endLine?: number; + /** + * End position of the range covered by the stack frame. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + endColumn?: number; + /** + * Indicates whether this frame can be restarted with the `restart` request. Clients should only use this if the debug adapter supports the `restart` request and the corresponding capability `supportsRestartRequest` is true. If a debug adapter has this capability, then `canRestart` defaults to `true` if the property is absent. + */ + canRestart?: boolean; + /** + * A memory reference for the current instruction pointer in this frame. + */ + instructionPointerReference?: string; + /** + * The module associated with this frame, if any. + */ + moduleId?: unknown; + /** + * A hint for how to present this frame in the UI. + * A value of `label` can be used to indicate that the frame is an artificial frame that is used as a visual label or separator. A value of `subtle` can be used to change the appearance of a frame in a 'subtle' way. + */ + presentationHint?: "normal" | "label" | "subtle"; + }; + /** + * A `Scope` is a named container for variables. Optionally a scope can map to a source or a range within a source. + */ + export type Scope = { + /** + * Name of the scope such as 'Arguments', 'Locals', or 'Registers'. This string is shown in the UI as is and can be translated. + */ + name: string; + /** + * A hint for how to present this scope in the UI. If this attribute is missing, the scope is shown with a generic UI. + */ + presentationHint?: string; + /** + * The variables of this scope can be retrieved by passing the value of `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. + */ + variablesReference: number; + /** + * The number of named variables in this scope. + * The client can use this information to present the variables in a paged UI and fetch them in chunks. + */ + namedVariables?: number; + /** + * The number of indexed variables in this scope. + * The client can use this information to present the variables in a paged UI and fetch them in chunks. + */ + indexedVariables?: number; + /** + * If true, the number of variables in this scope is large or expensive to retrieve. + */ + expensive: boolean; + /** + * The source for this scope. + */ + source?: Source; + /** + * The start line of the range covered by this scope. + */ + line?: number; + /** + * Start position of the range covered by the scope. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + column?: number; + /** + * The end line of the range covered by this scope. + */ + endLine?: number; + /** + * End position of the range covered by the scope. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + endColumn?: number; + }; + /** + * A Variable is a name/value pair. + * The `type` attribute is shown if space permits or when hovering over the variable's name. + * The `kind` attribute is used to render additional properties of the variable, e.g. different icons can be used to indicate that a variable is public or private. + * If the value is structured (has children), a handle is provided to retrieve the children with the `variables` request. + * If the number of named or indexed children is large, the numbers should be returned via the `namedVariables` and `indexedVariables` attributes. + * The client can use this information to present the children in a paged UI and fetch them in chunks. + */ + export type Variable = { + /** + * The variable's name. + */ + name: string; + /** + * The variable's value. + * This can be a multi-line text, e.g. for a function the body of a function. + * For structured variables (which do not have a simple value), it is recommended to provide a one-line representation of the structured object. This helps to identify the structured object in the collapsed state when its children are not yet visible. + * An empty string can be used if no value should be shown in the UI. + */ + value: string; + /** + * The type of the variable's value. Typically shown in the UI when hovering over the value. + * This attribute should only be returned by a debug adapter if the corresponding capability `supportsVariableType` is true. + */ + type?: string; + /** + * Properties of a variable that can be used to determine how to render the variable in the UI. + */ + presentationHint?: VariablePresentationHint; + /** + * The evaluatable name of this variable which can be passed to the `evaluate` request to fetch the variable's value. + */ + evaluateName?: string; + /** + * If `variablesReference` is > 0, the variable is structured and its children can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. + */ + variablesReference: number; + /** + * The number of named child variables. + * The client can use this information to present the children in a paged UI and fetch them in chunks. + */ + namedVariables?: number; + /** + * The number of indexed child variables. + * The client can use this information to present the children in a paged UI and fetch them in chunks. + */ + indexedVariables?: number; + /** + * The memory reference for the variable if the variable represents executable code, such as a function pointer. + * This attribute is only required if the corresponding capability `supportsMemoryReferences` is true. + */ + memoryReference?: string; + }; + /** + * Properties of a variable that can be used to determine how to render the variable in the UI. + */ + export type VariablePresentationHint = { + /** + * The kind of variable. Before introducing additional values, try to use the listed values. + */ + kind?: string; + /** + * Set of attributes represented as an array of strings. Before introducing additional values, try to use the listed values. + */ + attributes?: string[]; + /** + * Visibility of variable. Before introducing additional values, try to use the listed values. + */ + visibility?: string; + /** + * If true, clients can present the variable with a UI that supports a specific gesture to trigger its evaluation. + * This mechanism can be used for properties that require executing code when retrieving their value and where the code execution can be expensive and/or produce side-effects. A typical example are properties based on a getter function. + * Please note that in addition to the `lazy` flag, the variable's `variablesReference` is expected to refer to a variable that will provide the value through another `variable` request. + */ + lazy?: boolean; + }; + /** + * Properties of a breakpoint location returned from the `breakpointLocations` request. + */ + export type BreakpointLocation = { + /** + * Start line of breakpoint location. + */ + line: number; + /** + * The start position of a breakpoint location. Position is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + column?: number; + /** + * The end line of breakpoint location if the location covers a range. + */ + endLine?: number; + /** + * The end position of a breakpoint location (if the location covers a range). Position is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + endColumn?: number; + }; + /** + * Properties of a breakpoint or logpoint passed to the `setBreakpoints` request. + */ + export type SourceBreakpoint = { + /** + * The source line of the breakpoint or logpoint. + */ + line: number; + /** + * Start position within source line of the breakpoint or logpoint. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + column?: number; + /** + * The expression for conditional breakpoints. + * It is only honored by a debug adapter if the corresponding capability `supportsConditionalBreakpoints` is true. + */ + condition?: string; + /** + * The expression that controls how many hits of the breakpoint are ignored. + * The debug adapter is expected to interpret the expression as needed. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsHitConditionalBreakpoints` is true. + * If both this property and `condition` are specified, `hitCondition` should be evaluated only if the `condition` is met, and the debug adapter should stop only if both conditions are met. + */ + hitCondition?: string; + /** + * If this attribute exists and is non-empty, the debug adapter must not 'break' (stop) + * but log the message instead. Expressions within `{}` are interpolated. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsLogPoints` is true. + * If either `hitCondition` or `condition` is specified, then the message should only be logged if those conditions are met. + */ + logMessage?: string; + }; + /** + * Properties of a breakpoint passed to the `setFunctionBreakpoints` request. + */ + export type FunctionBreakpoint = { + /** + * The name of the function. + */ + name: string; + /** + * An expression for conditional breakpoints. + * It is only honored by a debug adapter if the corresponding capability `supportsConditionalBreakpoints` is true. + */ + condition?: string; + /** + * An expression that controls how many hits of the breakpoint are ignored. + * The debug adapter is expected to interpret the expression as needed. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsHitConditionalBreakpoints` is true. + */ + hitCondition?: string; + }; + /** + * This enumeration defines all possible access types for data breakpoints. + */ + export type DataBreakpointAccessType = "read" | "write" | "readWrite"; + /** + * Properties of a data breakpoint passed to the `setDataBreakpoints` request. + */ + export type DataBreakpoint = { + /** + * An id representing the data. This id is returned from the `dataBreakpointInfo` request. + */ + dataId: string; + /** + * The access type of the data. + */ + accessType?: DataBreakpointAccessType; + /** + * An expression for conditional breakpoints. + */ + condition?: string; + /** + * An expression that controls how many hits of the breakpoint are ignored. + * The debug adapter is expected to interpret the expression as needed. + */ + hitCondition?: string; + }; + /** + * Properties of a breakpoint passed to the `setInstructionBreakpoints` request + */ + export type InstructionBreakpoint = { + /** + * The instruction reference of the breakpoint. + * This should be a memory or instruction pointer reference from an `EvaluateResponse`, `Variable`, `StackFrame`, `GotoTarget`, or `Breakpoint`. + */ + instructionReference: string; + /** + * The offset from the instruction reference. + * This can be negative. + */ + offset?: number; + /** + * An expression for conditional breakpoints. + * It is only honored by a debug adapter if the corresponding capability `supportsConditionalBreakpoints` is true. + */ + condition?: string; + /** + * An expression that controls how many hits of the breakpoint are ignored. + * The debug adapter is expected to interpret the expression as needed. + * The attribute is only honored by a debug adapter if the corresponding capability `supportsHitConditionalBreakpoints` is true. + */ + hitCondition?: string; + }; + /** + * Information about a breakpoint created in `setBreakpoints`, `setFunctionBreakpoints`, `setInstructionBreakpoints`, or `setDataBreakpoints` requests. + */ + export type Breakpoint = { + /** + * The identifier for the breakpoint. It is needed if breakpoint events are used to update or remove breakpoints. + */ + id?: number; + /** + * If true, the breakpoint could be set (but not necessarily at the desired location). + */ + verified: boolean; + /** + * A message about the state of the breakpoint. + * This is shown to the user and can be used to explain why a breakpoint could not be verified. + */ + message?: string; + /** + * The source where the breakpoint is located. + */ + source?: Source; + /** + * The start line of the actual range covered by the breakpoint. + */ + line?: number; + /** + * Start position of the source range covered by the breakpoint. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + column?: number; + /** + * The end line of the actual range covered by the breakpoint. + */ + endLine?: number; + /** + * End position of the source range covered by the breakpoint. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + * If no end line is given, then the end column is assumed to be in the start line. + */ + endColumn?: number; + /** + * A memory reference to where the breakpoint is set. + */ + instructionReference?: string; + /** + * The offset from the instruction reference. + * This can be negative. + */ + offset?: number; + }; + /** + * The granularity of one 'step' in the stepping requests `next`, `stepIn`, `stepOut`, and `stepBack`. + */ + export type SteppingGranularity = "statement" | "line" | "instruction"; + /** + * A `StepInTarget` can be used in the `stepIn` request and determines into which single target the `stepIn` request should step. + */ + export type StepInTarget = { + /** + * Unique identifier for a step-in target. + */ + id: number; + /** + * The name of the step-in target (shown in the UI). + */ + label: string; + /** + * The line of the step-in target. + */ + line?: number; + /** + * Start position of the range covered by the step in target. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + column?: number; + /** + * The end line of the range covered by the step-in target. + */ + endLine?: number; + /** + * End position of the range covered by the step in target. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. + */ + endColumn?: number; + }; + /** + * A `GotoTarget` describes a code location that can be used as a target in the `goto` request. + * The possible goto targets can be determined via the `gotoTargets` request. + */ + export type GotoTarget = { + /** + * Unique identifier for a goto target. This is used in the `goto` request. + */ + id: number; + /** + * The name of the goto target (shown in the UI). + */ + label: string; + /** + * The line of the goto target. + */ + line: number; + /** + * The column of the goto target. + */ + column?: number; + /** + * The end line of the range covered by the goto target. + */ + endLine?: number; + /** + * The end column of the range covered by the goto target. + */ + endColumn?: number; + /** + * A memory reference for the instruction pointer value represented by this target. + */ + instructionPointerReference?: string; + }; + /** + * `CompletionItems` are the suggestions returned from the `completions` request. + */ + export type CompletionItem = { + /** + * The label of this completion item. By default this is also the text that is inserted when selecting this completion. + */ + label: string; + /** + * If text is returned and not an empty string, then it is inserted instead of the label. + */ + text?: string; + /** + * A string that should be used when comparing this item with other items. If not returned or an empty string, the `label` is used instead. + */ + sortText?: string; + /** + * A human-readable string with additional information about this item, like type or symbol information. + */ + detail?: string; + /** + * The item's type. Typically the client uses this information to render the item in the UI with an icon. + */ + type?: CompletionItemType; + /** + * Start position (within the `text` attribute of the `completions` request) where the completion text is added. The position is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. If the start position is omitted the text is added at the location specified by the `column` attribute of the `completions` request. + */ + start?: number; + /** + * Length determines how many characters are overwritten by the completion text and it is measured in UTF-16 code units. If missing the value 0 is assumed which results in the completion text being inserted. + */ + length?: number; + /** + * Determines the start of the new selection after the text has been inserted (or replaced). `selectionStart` is measured in UTF-16 code units and must be in the range 0 and length of the completion text. If omitted the selection starts at the end of the completion text. + */ + selectionStart?: number; + /** + * Determines the length of the new selection after the text has been inserted (or replaced) and it is measured in UTF-16 code units. The selection can not extend beyond the bounds of the completion text. If omitted the length is assumed to be 0. + */ + selectionLength?: number; + }; + /** + * Some predefined types for the CompletionItem. Please note that not all clients have specific icons for all of them. + */ + export type CompletionItemType = + | "method" + | "function" + | "constructor" + | "field" + | "variable" + | "class" + | "interface" + | "module" + | "property" + | "unit" + | "value" + | "enum" + | "keyword" + | "snippet" + | "text" + | "color" + | "file" + | "reference" + | "customcolor"; + /** + * Names of checksum algorithms that may be supported by a debug adapter. + */ + export type ChecksumAlgorithm = "MD5" | "SHA1" | "SHA256" | "timestamp"; + /** + * The checksum of an item calculated by the specified algorithm. + */ + export type Checksum = { + /** + * The algorithm used to calculate this checksum. + */ + algorithm: ChecksumAlgorithm; + /** + * Value of the checksum, encoded as a hexadecimal value. + */ + checksum: string; + }; + /** + * Provides formatting information for a value. + */ + export type ValueFormat = { + /** + * Display the value in hex. + */ + hex?: boolean; + }; + export type StackFrameFormat = ValueFormat & { + /** + * Displays parameters for the stack frame. + */ + parameters?: boolean; + /** + * Displays the types of parameters for the stack frame. + */ + parameterTypes?: boolean; + /** + * Displays the names of parameters for the stack frame. + */ + parameterNames?: boolean; + /** + * Displays the values of parameters for the stack frame. + */ + parameterValues?: boolean; + /** + * Displays the line number of the stack frame. + */ + line?: boolean; + /** + * Displays the module of the stack frame. + */ + module?: boolean; + /** + * Includes all stack frames, including those the debug adapter might otherwise hide. + */ + includeAll?: boolean; + }; + /** + * An `ExceptionFilterOptions` is used to specify an exception filter together with a condition for the `setExceptionBreakpoints` request. + */ + export type ExceptionFilterOptions = { + /** + * ID of an exception filter returned by the `exceptionBreakpointFilters` capability. + */ + filterId: string; + /** + * An expression for conditional exceptions. + * The exception breaks into the debugger if the result of the condition is true. + */ + condition?: string; + }; + /** + * An `ExceptionOptions` assigns configuration options to a set of exceptions. + */ + export type ExceptionOptions = { + /** + * A path that selects a single or multiple exceptions in a tree. If `path` is missing, the whole tree is selected. + * By convention the first segment of the path is a category that is used to group exceptions in the UI. + */ + path?: ExceptionPathSegment[]; + /** + * Condition when a thrown exception should result in a break. + */ + breakMode: ExceptionBreakMode; + }; + /** + * This enumeration defines all possible conditions when a thrown exception should result in a break. + * never: never breaks, + * always: always breaks, + * unhandled: breaks when exception unhandled, + * userUnhandled: breaks if the exception is not handled by user code. + */ + export type ExceptionBreakMode = "never" | "always" | "unhandled" | "userUnhandled"; + /** + * An `ExceptionPathSegment` represents a segment in a path that is used to match leafs or nodes in a tree of exceptions. + * If a segment consists of more than one name, it matches the names provided if `negate` is false or missing, or it matches anything except the names provided if `negate` is true. + */ + export type ExceptionPathSegment = { + /** + * If false or missing this segment matches the names provided, otherwise it matches anything except the names provided. + */ + negate?: boolean; + /** + * Depending on the value of `negate` the names that should match or not match. + */ + names: string[]; + }; + /** + * Detailed information about an exception that has occurred. + */ + export type ExceptionDetails = { + /** + * Message contained in the exception. + */ + message?: string; + /** + * Short type name of the exception object. + */ + typeName?: string; + /** + * Fully-qualified type name of the exception object. + */ + fullTypeName?: string; + /** + * An expression that can be evaluated in the current scope to obtain the exception object. + */ + evaluateName?: string; + /** + * Stack trace at the time the exception was thrown. + */ + stackTrace?: string; + /** + * Details of the exception contained by this exception, if any. + */ + innerException?: ExceptionDetails[]; + }; + /** + * Represents a single disassembled instruction. + */ + export type DisassembledInstruction = { + /** + * The address of the instruction. Treated as a hex value if prefixed with `0x`, or as a decimal value otherwise. + */ + address: string; + /** + * Raw bytes representing the instruction and its operands, in an implementation-defined format. + */ + instructionBytes?: string; + /** + * Text representing the instruction and its operands, in an implementation-defined format. + */ + instruction: string; + /** + * Name of the symbol that corresponds with the location of this instruction, if any. + */ + symbol?: string; + /** + * Source location that corresponds to this instruction, if any. + * Should always be set (if available) on the first instruction returned, + * but can be omitted afterwards if this instruction maps to the same source file as the previous instruction. + */ + location?: Source; + /** + * The line within the source location that corresponds to this instruction, if any. + */ + line?: number; + /** + * The column within the line that corresponds to this instruction, if any. + */ + column?: number; + /** + * The end line of the range that corresponds to this instruction, if any. + */ + endLine?: number; + /** + * The end column of the range that corresponds to this instruction, if any. + */ + endColumn?: number; + }; + /** + * Logical areas that can be invalidated by the `invalidated` event. + */ + export type InvalidatedAreas = string; + export type ErrorRequest = {}; + export type ThreadsRequest = {}; + export type RequestMap = { + cancel: CancelRequest; + runInTerminal: RunInTerminalRequest; + startDebugging: StartDebuggingRequest; + initialize: InitializeRequest; + configurationDone: ConfigurationDoneRequest; + launch: LaunchRequest; + attach: AttachRequest; + restart: RestartRequest; + disconnect: DisconnectRequest; + terminate: TerminateRequest; + breakpointLocations: BreakpointLocationsRequest; + setBreakpoints: SetBreakpointsRequest; + setFunctionBreakpoints: SetFunctionBreakpointsRequest; + setExceptionBreakpoints: SetExceptionBreakpointsRequest; + dataBreakpointInfo: DataBreakpointInfoRequest; + setDataBreakpoints: SetDataBreakpointsRequest; + setInstructionBreakpoints: SetInstructionBreakpointsRequest; + continue: ContinueRequest; + next: NextRequest; + stepIn: StepInRequest; + stepOut: StepOutRequest; + stepBack: StepBackRequest; + reverseContinue: ReverseContinueRequest; + restartFrame: RestartFrameRequest; + goto: GotoRequest; + pause: PauseRequest; + stackTrace: StackTraceRequest; + scopes: ScopesRequest; + variables: VariablesRequest; + setVariable: SetVariableRequest; + source: SourceRequest; + terminateThreads: TerminateThreadsRequest; + modules: ModulesRequest; + loadedSources: LoadedSourcesRequest; + evaluate: EvaluateRequest; + setExpression: SetExpressionRequest; + stepInTargets: StepInTargetsRequest; + gotoTargets: GotoTargetsRequest; + completions: CompletionsRequest; + exceptionInfo: ExceptionInfoRequest; + readMemory: ReadMemoryRequest; + writeMemory: WriteMemoryRequest; + disassemble: DisassembleRequest; + error: ErrorRequest; + threads: ThreadsRequest; + }; + export type ResponseMap = { + error: ErrorResponse; + cancel: CancelResponse; + runInTerminal: RunInTerminalResponse; + startDebugging: StartDebuggingResponse; + initialize: InitializeResponse; + configurationDone: ConfigurationDoneResponse; + launch: LaunchResponse; + attach: AttachResponse; + restart: RestartResponse; + disconnect: DisconnectResponse; + terminate: TerminateResponse; + breakpointLocations: BreakpointLocationsResponse; + setBreakpoints: SetBreakpointsResponse; + setFunctionBreakpoints: SetFunctionBreakpointsResponse; + setExceptionBreakpoints: SetExceptionBreakpointsResponse; + dataBreakpointInfo: DataBreakpointInfoResponse; + setDataBreakpoints: SetDataBreakpointsResponse; + setInstructionBreakpoints: SetInstructionBreakpointsResponse; + continue: ContinueResponse; + next: NextResponse; + stepIn: StepInResponse; + stepOut: StepOutResponse; + stepBack: StepBackResponse; + reverseContinue: ReverseContinueResponse; + restartFrame: RestartFrameResponse; + goto: GotoResponse; + pause: PauseResponse; + stackTrace: StackTraceResponse; + scopes: ScopesResponse; + variables: VariablesResponse; + setVariable: SetVariableResponse; + source: SourceResponse; + threads: ThreadsResponse; + terminateThreads: TerminateThreadsResponse; + modules: ModulesResponse; + loadedSources: LoadedSourcesResponse; + evaluate: EvaluateResponse; + setExpression: SetExpressionResponse; + stepInTargets: StepInTargetsResponse; + gotoTargets: GotoTargetsResponse; + completions: CompletionsResponse; + exceptionInfo: ExceptionInfoResponse; + readMemory: ReadMemoryResponse; + writeMemory: WriteMemoryResponse; + disassemble: DisassembleResponse; + }; + export type EventMap = { + initialized: InitializedEvent; + stopped: StoppedEvent; + continued: ContinuedEvent; + exited: ExitedEvent; + terminated: TerminatedEvent; + thread: ThreadEvent; + output: OutputEvent; + breakpoint: BreakpointEvent; + module: ModuleEvent; + loadedSource: LoadedSourceEvent; + process: ProcessEvent; + capabilities: CapabilitiesEvent; + progressStart: ProgressStartEvent; + progressUpdate: ProgressUpdateEvent; + progressEnd: ProgressEndEvent; + invalidated: InvalidatedEvent; + memory: MemoryEvent; + }; +} diff --git a/packages/bun-debug-adapter-protocol/protocol/schema.d.ts b/packages/bun-debug-adapter-protocol/protocol/schema.d.ts new file mode 100644 index 000000000..bf6f2d810 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/protocol/schema.d.ts @@ -0,0 +1,37 @@ +export type Protocol = { + $schema: string; + title: string; + description: string; + type: "object"; + definitions: Record<string, Type>; +}; + +export type Type = { + description?: string; +} & ( + | { + type: "number" | "integer" | "boolean"; + } + | { + type: "string"; + enum?: string[]; + enumDescriptions?: string[]; + } + | { + type: "object"; + properties?: Record<string, Type>; + required?: string[]; + } + | { + type: "array"; + items?: Type; + } + | { + type?: undefined; + $ref: string; + } + | { + type?: undefined; + allOf: Type[]; + } +); diff --git a/packages/bun-debug-adapter-protocol/scripts/generate-protocol.ts b/packages/bun-debug-adapter-protocol/scripts/generate-protocol.ts new file mode 100644 index 000000000..724a48490 --- /dev/null +++ b/packages/bun-debug-adapter-protocol/scripts/generate-protocol.ts @@ -0,0 +1,176 @@ +import type { Protocol, Type } from "../protocol/schema.d.ts"; +import { writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; + +run().catch(console.error); + +async function run() { + const cwd = new URL("../protocol/", import.meta.url); + const runner = "Bun" in globalThis ? "bunx" : "npx"; + const write = (name: string, data: string) => { + const path = new URL(name, cwd); + writeFileSync(path, data); + spawnSync(runner, ["prettier", "--write", path.pathname], { cwd, stdio: "ignore" }); + }; + const schema: Protocol = await download( + "https://microsoft.github.io/debug-adapter-protocol/debugAdapterProtocol.json", + ); + write("protocol.json", JSON.stringify(schema)); + const types = formatProtocol(schema); + write("index.d.ts", `// GENERATED - DO NOT EDIT\n${types}`); +} + +function formatProtocol(protocol: Protocol, extraTs?: string): string { + const { definitions } = protocol; + const requestMap = new Map(); + const responseMap = new Map(); + const eventMap = new Map(); + let body = `export namespace DAP {`; + loop: for (const [key, definition] of Object.entries(definitions)) { + if (/[a-z]+Request$/i.test(key)) { + continue; + } + if (/[a-z]+Arguments$/i.test(key)) { + const name = key.replace(/(Request)?Arguments$/, ""); + const requestName = `${name}Request`; + requestMap.set(toMethod(name), requestName); + body += formatType(definition, requestName); + continue; + } + if ("allOf" in definition) { + const { allOf } = definition; + for (const type of allOf) { + if (type.type !== "object") { + continue; + } + const { description, properties = {} } = type; + if (/[a-z]+Event$/i.test(key)) { + const { event, body: type = {} } = properties; + if (!event || !("enum" in event)) { + continue; + } + const [eventKey] = event.enum ?? []; + eventMap.set(eventKey, key); + const eventType: Type = { + type: "object", + description, + ...type, + }; + body += formatType(eventType, key); + continue loop; + } + if (/[a-z]+Response$/i.test(key)) { + const { body: type = {} } = properties; + const bodyType: Type = { + type: "object", + description, + ...type, + }; + const name = key.replace(/Response$/, ""); + responseMap.set(toMethod(name), key); + body += formatType(bodyType, key); + continue loop; + } + } + } + body += formatType(definition, key); + } + for (const [key, name] of responseMap) { + if (requestMap.has(key)) { + continue; + } + const requestName = `${name.replace(/Response$/, "")}Request`; + requestMap.set(key, requestName); + body += formatType({ type: "object", properties: {} }, requestName); + } + body += formatMapType("RequestMap", requestMap); + body += formatMapType("ResponseMap", responseMap); + body += formatMapType("EventMap", eventMap); + if (extraTs) { + body += extraTs; + } + return body + "};"; +} + +function formatMapType(key: string, typeMap: Map<string, string>): string { + const type: Type = { + type: "object", + required: [...typeMap.keys()], + properties: Object.fromEntries([...typeMap.entries()].map(([key, value]) => [key, { $ref: value }])), + }; + return formatType(type, key); +} + +function formatType(type: Type, key?: string): string { + const { description, type: kind } = type; + let body = ""; + if (key) { + if (description) { + body += `\n${toComment(description)}\n`; + } + body += `export type ${key}=`; + } + if (kind === "boolean") { + body += "boolean"; + } else if (kind === "number" || kind === "integer") { + body += "number"; + } else if (kind === "string") { + const { enum: choices } = type; + if (choices) { + body += choices.map(value => `"${value}"`).join("|"); + } else { + body += "string"; + } + } else if (kind === "array") { + const { items } = type; + const itemType = items ? formatType(items) : "unknown"; + body += `${itemType}[]`; + } else if (kind === "object") { + const { properties, required } = type; + if (!properties || Object.keys(properties).length === 0) { + body += "{}"; + } else { + body += "{"; + for (const [key, { description, ...type }] of Object.entries(properties)) { + if (description) { + body += `\n${toComment(description)}`; + } + const delimit = required?.includes(key) ? ":" : "?:"; + body += `\n${key}${delimit}${formatType(type)};`; + } + body += "}"; + } + } else if ("$ref" in type) { + const { $ref: ref } = type; + body += ref.split("/").pop() || "unknown"; + } else if ("allOf" in type) { + const { allOf } = type; + body += allOf.map(type => formatType(type)).join("&"); + } else { + body += "unknown"; + } + if (key) { + body += ";"; + } + return body; +} + +function toMethod(name: string): string { + return `${name.substring(0, 1).toLowerCase()}${name.substring(1)}`; +} + +function toComment(description?: string): string { + if (!description) { + return ""; + } + const lines = ["/**", ...description.split("\n").map(line => ` * ${line.trim()}`), "*/"]; + return lines.join("\n"); +} + +async function download<T>(url: string | URL): Promise<T> { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`Failed to download ${url}: ${response.statusText}`); + } + return response.json(); +} diff --git a/packages/web-inspector-bun/tsconfig.json b/packages/bun-debug-adapter-protocol/tsconfig.json index 669cfeccf..bada4ff8f 100644 --- a/packages/web-inspector-bun/tsconfig.json +++ b/packages/bun-debug-adapter-protocol/tsconfig.json @@ -3,19 +3,20 @@ "lib": ["ESNext"], "module": "esnext", "target": "esnext", - "moduleResolution": "bundler", + "moduleResolution": "nodenext", "moduleDetection": "force", "allowImportingTsExtensions": true, "noEmit": true, "composite": true, + "strict": true, "downlevelIteration": true, "skipLibCheck": true, - "jsx": "preserve", "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, + "inlineSourceMap": true, "allowJs": true, - "types": [ - "bun-types" // add Bun global - ] - } + "types": ["bun-types"], + "outDir": "dist", + }, + "include": [".", "../bun-types/index.d.ts", "../bun-inspector-protocol/index"] } diff --git a/packages/bun-ecosystem/package.json b/packages/bun-ecosystem/package.json index 1899684cd..190314a31 100644 --- a/packages/bun-ecosystem/package.json +++ b/packages/bun-ecosystem/package.json @@ -1,4 +1,5 @@ { + "name": "bun-ecosystem-ci", "private": true, "dependencies": { "globby": "^13.1.3" @@ -11,4 +12,4 @@ "format": "prettier --write src", "test": "bun run src/runner.ts" } -}
\ No newline at end of file +} diff --git a/packages/web-inspector-bun/.gitignore b/packages/bun-inspector-frontend/.gitignore index f4e40f314..f4e40f314 100644 --- a/packages/web-inspector-bun/.gitignore +++ b/packages/bun-inspector-frontend/.gitignore diff --git a/packages/web-inspector-bun/README.md b/packages/bun-inspector-frontend/README.md index dc7545d60..a2be402f9 100644 --- a/packages/web-inspector-bun/README.md +++ b/packages/bun-inspector-frontend/README.md @@ -1,4 +1,4 @@ -# web-inspector-bun +# bun-devtools-frontend This is the WebKit Web Inspector bundled as standalone assets. diff --git a/packages/web-inspector-bun/build.ts b/packages/bun-inspector-frontend/build.ts index 4b1eb50e1..4b1eb50e1 100644 --- a/packages/web-inspector-bun/build.ts +++ b/packages/bun-inspector-frontend/build.ts diff --git a/packages/web-inspector-bun/bun.lockb b/packages/bun-inspector-frontend/bun.lockb Binary files differindex 9133cce88..9133cce88 100755 --- a/packages/web-inspector-bun/bun.lockb +++ b/packages/bun-inspector-frontend/bun.lockb diff --git a/packages/web-inspector-bun/package.json b/packages/bun-inspector-frontend/package.json index 6421ae745..6421ae745 100644 --- a/packages/web-inspector-bun/package.json +++ b/packages/bun-inspector-frontend/package.json diff --git a/packages/bun-inspector-frontend/tsconfig.json b/packages/bun-inspector-frontend/tsconfig.json new file mode 100644 index 000000000..53e5cdcf5 --- /dev/null +++ b/packages/bun-inspector-frontend/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "lib": ["ESNext"], + "module": "esnext", + "target": "esnext", + "moduleResolution": "nodenext", + "moduleDetection": "force", + "strict": true, + "downlevelIteration": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "inlineSourceMap": true, + "allowJs": true, + "noImplicitAny": false, + "outDir": "dist", + "types": ["node"] + }, + "include": [".", "../bun-types/index.d.ts"] +} diff --git a/packages/bun-inspector-protocol/.gitattributes b/packages/bun-inspector-protocol/.gitattributes new file mode 100644 index 000000000..f2af6eac2 --- /dev/null +++ b/packages/bun-inspector-protocol/.gitattributes @@ -0,0 +1,2 @@ +protocol/*/protocol.json linguist-generated=true +protocol/*/index.d.ts linguist-generated=true diff --git a/packages/bun-inspector-protocol/.gitignore b/packages/bun-inspector-protocol/.gitignore new file mode 100644 index 000000000..eeb2e65f0 --- /dev/null +++ b/packages/bun-inspector-protocol/.gitignore @@ -0,0 +1,2 @@ +protocol/*.json +protocol/v8 diff --git a/packages/bun-inspector-protocol/README.md b/packages/bun-inspector-protocol/README.md new file mode 100644 index 000000000..ae7408ee0 --- /dev/null +++ b/packages/bun-inspector-protocol/README.md @@ -0,0 +1 @@ +# bun-inspector-protocol diff --git a/packages/bun-inspector-protocol/bun.lockb b/packages/bun-inspector-protocol/bun.lockb Binary files differnew file mode 100755 index 000000000..36874030e --- /dev/null +++ b/packages/bun-inspector-protocol/bun.lockb diff --git a/packages/bun-inspector-protocol/index.ts b/packages/bun-inspector-protocol/index.ts new file mode 100644 index 000000000..5b0d8b43b --- /dev/null +++ b/packages/bun-inspector-protocol/index.ts @@ -0,0 +1,3 @@ +export type * from "./protocol"; +export type * from "./inspector"; +export * from "./inspector/websocket"; diff --git a/packages/bun-inspector-protocol/inspector/fixtures/inspectee.js b/packages/bun-inspector-protocol/inspector/fixtures/inspectee.js new file mode 100644 index 000000000..ea9301171 --- /dev/null +++ b/packages/bun-inspector-protocol/inspector/fixtures/inspectee.js @@ -0,0 +1,7 @@ +export default { + fetch(request) { + console.log(request); + debugger; + return new Response(); + }, +}; diff --git a/packages/bun-inspector-protocol/inspector/index.d.ts b/packages/bun-inspector-protocol/inspector/index.d.ts new file mode 100644 index 000000000..4baf4ddc0 --- /dev/null +++ b/packages/bun-inspector-protocol/inspector/index.d.ts @@ -0,0 +1,49 @@ +import type { JSC } from ".."; + +/** + * A client that can send and receive messages to/from a debugger. + */ +export abstract class Inspector { + constructor(listener?: InspectorListener); + /** + * Starts the inspector. + */ + start(...args: unknown[]): void; + /** + * Sends a request to the debugger. + */ + send<M extends keyof JSC.RequestMap & keyof JSC.ResponseMap>( + method: M, + params?: JSC.RequestMap[M], + ): Promise<JSC.ResponseMap[M]>; + /** + * Accepts a message from the debugger. + * @param message the unparsed message from the debugger + */ + accept(message: string): void; + /** + * If the inspector is closed. + */ + get closed(): boolean; + /** + * Closes the inspector. + */ + close(...args: unknown[]): void; +} + +export type InspectorListener = { + /** + * Defines a handler when a debugger event is received. + */ + [M in keyof JSC.EventMap]?: (event: JSC.EventMap[M]) => void; +} & { + /** + * Defines a handler when the debugger is connected or reconnected. + */ + ["Inspector.connected"]?: () => void; + /** + * Defines a handler when the debugger is disconnected. + * @param error the error that caused the disconnect, if any + */ + ["Inspector.disconnected"]?: (error?: Error) => void; +}; diff --git a/packages/bun-inspector-protocol/inspector/websocket.test.ts b/packages/bun-inspector-protocol/inspector/websocket.test.ts new file mode 100644 index 000000000..7f5fa0b8c --- /dev/null +++ b/packages/bun-inspector-protocol/inspector/websocket.test.ts @@ -0,0 +1,83 @@ +import { afterAll, beforeAll, mock, test, expect } from "bun:test"; +import type { JSC } from ".."; +import type { InspectorListener } from "."; +import { WebSocketInspector } from "./websocket"; +import { sleep, spawn } from "bun"; + +let inspectee: any; +let url: string; + +beforeAll(async () => { + const { pathname } = new URL("fixtures/inspectee.js", import.meta.url); + inspectee = spawn({ + cmd: [process.argv0, "--inspect", pathname], + stdout: "pipe", + stderr: "pipe", + }); + url = await new Promise(async resolve => { + for await (const chunk of inspectee.stdout) { + const text = new TextDecoder().decode(chunk); + const match = /(wss?:\/\/.*:[0-9]+\/.*)/.exec(text); + if (!match) { + continue; + } + const [_, url] = match; + resolve(url); + } + }); +}); + +afterAll(() => { + inspectee?.kill(); +}); + +test( + "WebSocketInspector", + async () => { + const listener: InspectorListener = { + ["Inspector.connected"]: mock((...args) => { + expect(args).toBeEmpty(); + }), + ["Inspector.disconnected"]: mock((error?: Error) => { + expect(error).toBeUndefined(); + }), + ["Debugger.scriptParsed"]: mock((event: JSC.Debugger.ScriptParsedEvent) => { + expect(event).toMatchObject({ + endColumn: expect.any(Number), + endLine: expect.any(Number), + isContentScript: expect.any(Boolean), + module: expect.any(Boolean), + scriptId: expect.any(String), + startColumn: expect.any(Number), + startLine: expect.any(Number), + url: expect.any(String), + }); + }), + }; + const inspector = new WebSocketInspector({ + url, + listener, + }); + inspector.start(); + inspector.send("Runtime.enable"); + inspector.send("Debugger.enable"); + //expect(inspector.send("Runtime.enable")).resolves.toBeEmpty(); + //expect(inspector.send("Debugger.enable")).resolves.toBeEmpty(); + expect(inspector.send("Runtime.evaluate", { expression: "1 + 1" })).resolves.toMatchObject({ + result: { + type: "number", + value: 2, + description: "2", + }, + wasThrown: false, + }); + expect(listener["Inspector.connected"]).toHaveBeenCalled(); + expect(listener["Debugger.scriptParsed"]).toHaveBeenCalled(); + inspector.close(); + expect(inspector.closed).toBeTrue(); + expect(listener["Inspector.disconnected"]).toHaveBeenCalled(); + }, + { + timeout: 100000, + }, +); diff --git a/packages/bun-inspector-protocol/inspector/websocket.ts b/packages/bun-inspector-protocol/inspector/websocket.ts new file mode 100644 index 000000000..71dc60a1e --- /dev/null +++ b/packages/bun-inspector-protocol/inspector/websocket.ts @@ -0,0 +1,196 @@ +import type { Inspector, InspectorListener } from "."; +import { JSC } from ".."; +import { WebSocket } from "ws"; + +export type WebSocketInspectorOptions = { + url?: string | URL; + listener?: InspectorListener; +}; + +/** + * An inspector that communicates with a debugger over a WebSocket. + */ +export class WebSocketInspector implements Inspector { + #url?: URL; + #webSocket?: WebSocket; + #requestId: number; + #pendingRequests: Map<number, (result: unknown) => void>; + #pendingMessages: string[]; + #listener: InspectorListener; + + constructor({ url, listener }: WebSocketInspectorOptions) { + this.#url = url ? new URL(url) : undefined; + this.#listener = listener ?? {}; + this.#requestId = 1; + this.#pendingRequests = new Map(); + this.#pendingMessages = []; + } + + start(url?: string | URL): void { + if (url) { + this.#url = new URL(url); + } + if (this.#url) { + this.#connect(); + } + } + + #connect(): void { + if (!this.#url) { + return; + } + this.#webSocket?.close(); + let webSocket: WebSocket; + try { + console.log("[jsc] connecting", this.#url.href); + webSocket = new WebSocket(this.#url, { + headers: { + "Ref-Event-Loop": "0", + }, + }); + } catch (error) { + this.#close(unknownToError(error)); + return; + } + webSocket.addEventListener("open", () => { + console.log("[jsc] connected"); + for (const message of this.#pendingMessages) { + this.#send(message); + } + this.#pendingMessages.length = 0; + this.#listener["Inspector.connected"]?.(); + }); + webSocket.addEventListener("message", ({ data }) => { + if (typeof data === "string") { + this.accept(data); + } + }); + webSocket.addEventListener("error", event => { + console.log("[jsc] error", event); + this.#close(unknownToError(event)); + }); + webSocket.addEventListener("unexpected-response", () => { + console.log("[jsc] unexpected-response"); + this.#close(new Error("WebSocket upgrade failed")); + }); + webSocket.addEventListener("close", ({ code, reason }) => { + console.log("[jsc] closed", code, reason); + if (code === 1001) { + this.#close(); + } else { + this.#close(new Error(`WebSocket closed: ${code} ${reason}`.trimEnd())); + } + }); + this.#webSocket = webSocket; + } + + send<M extends keyof JSC.RequestMap & keyof JSC.ResponseMap>( + method: M, + params?: JSC.RequestMap[M] | undefined, + ): Promise<JSC.ResponseMap[M]> { + const id = this.#requestId++; + const request = { id, method, params }; + console.log("[jsc] -->", request); + return new Promise((resolve, reject) => { + const done = (result: any) => { + this.#pendingRequests.delete(id); + if (result instanceof Error) { + reject(result); + } else { + resolve(result); + } + }; + this.#pendingRequests.set(id, done); + this.#send(JSON.stringify(request)); + }); + } + + #send(message: string): void { + if (this.#webSocket) { + const { readyState } = this.#webSocket!; + if (readyState === WebSocket.OPEN) { + this.#webSocket.send(message); + } + return; + } + if (!this.#pendingMessages.includes(message)) { + this.#pendingMessages.push(message); + } + } + + accept(message: string): void { + let event: JSC.Event | JSC.Response; + try { + event = JSON.parse(message); + } catch (error) { + console.error("Failed to parse message:", message); + return; + } + console.log("[jsc] <--", event); + if ("id" in event) { + const { id } = event; + const resolve = this.#pendingRequests.get(id); + if (!resolve) { + console.error(`Failed to accept response for unknown ID ${id}:`, event); + return; + } + this.#pendingRequests.delete(id); + if ("error" in event) { + const { error } = event; + const { message } = error; + resolve(new Error(message)); + } else { + const { result } = event; + resolve(result); + } + } else { + const { method, params } = event; + try { + // @ts-ignore + this.#listener[method]?.(params); + } catch (error) { + console.error(`Failed to accept ${method} event:`, error); + return; + } + } + } + + get closed(): boolean { + if (!this.#webSocket) { + return true; + } + const { readyState } = this.#webSocket; + switch (readyState) { + case WebSocket.CLOSED: + case WebSocket.CLOSING: + return true; + } + return false; + } + + close(code?: number, reason?: string): void { + this.#webSocket?.close(code ?? 1001, reason); + } + + #close(error?: Error): void { + try { + this.#listener["Inspector.disconnected"]?.(error); + } finally { + for (const resolve of this.#pendingRequests.values()) { + resolve(error ?? new Error("WebSocket closed")); + } + this.#pendingRequests.clear(); + } + } +} + +function unknownToError(input: unknown): Error { + if (input instanceof Error) { + return input; + } + if (typeof input === "object" && input !== null && "message" in input) { + const { message } = input; + return new Error(`${message}`); + } + return new Error(`${input}`); +} diff --git a/packages/bun-inspector-protocol/package.json b/packages/bun-inspector-protocol/package.json new file mode 100644 index 000000000..bb61cf86f --- /dev/null +++ b/packages/bun-inspector-protocol/package.json @@ -0,0 +1,7 @@ +{ + "name": "bun-inspector-protocol", + "version": "0.0.1", + "dependencies": { + "ws": "^8.13.0" + } +} diff --git a/packages/bun-inspector-protocol/protocol/index.d.ts b/packages/bun-inspector-protocol/protocol/index.d.ts new file mode 100644 index 000000000..ec88ecf36 --- /dev/null +++ b/packages/bun-inspector-protocol/protocol/index.d.ts @@ -0,0 +1 @@ +export type { JSC } from "./jsc"; diff --git a/packages/bun-inspector-protocol/protocol/jsc/index.d.ts b/packages/bun-inspector-protocol/protocol/jsc/index.d.ts new file mode 100644 index 000000000..88e7f0a90 --- /dev/null +++ b/packages/bun-inspector-protocol/protocol/jsc/index.d.ts @@ -0,0 +1,3695 @@ +// GENERATED - DO NOT EDIT +export namespace JSC { + export namespace Console { + /** + * Channels for different types of log messages. + */ + export type ChannelSource = + | "xml" + | "javascript" + | "network" + | "console-api" + | "storage" + | "appcache" + | "rendering" + | "css" + | "security" + | "content-blocker" + | "media" + | "mediasource" + | "webrtc" + | "itp-debug" + | "private-click-measurement" + | "payment-request" + | "other"; + /** + * Level of logging. + */ + export type ChannelLevel = "off" | "basic" | "verbose"; + /** + * The reason the console is being cleared. + */ + export type ClearReason = "console-api" | "main-frame-navigation"; + /** + * Logging channel. + */ + export type Channel = { + source: ChannelSource; + level: ChannelLevel; + }; + /** + * Console message. + */ + export type ConsoleMessage = { + source: ChannelSource; + /** + * Message severity. + */ + level: "log" | "info" | "warning" | "error" | "debug"; + /** + * Message text. + */ + text: string; + /** + * Console message type. + */ + type?: + | "log" + | "dir" + | "dirxml" + | "table" + | "trace" + | "clear" + | "startGroup" + | "startGroupCollapsed" + | "endGroup" + | "assert" + | "timing" + | "profile" + | "profileEnd" + | "image" + | undefined; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message. + */ + line?: number | undefined; + /** + * Column number on the line in the resource that generated this message. + */ + column?: number | undefined; + /** + * Repeat count for repeated messages. + */ + repeatCount?: number | undefined; + /** + * Message parameters in case of the formatted message. + */ + parameters?: Runtime.RemoteObject[] | undefined; + /** + * JavaScript stack trace for assertions and error messages. + */ + stackTrace?: StackTrace | undefined; + /** + * Identifier of the network request associated with this message. + */ + networkRequestId?: Network.RequestId | undefined; + /** + * Time when this message was added. Currently only used when an expensive operation happens to make sure that the frontend can account for it. + */ + timestamp?: number | undefined; + }; + /** + * Stack entry for console errors and assertions. + */ + export type CallFrame = { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Script identifier. + */ + scriptId: Debugger.ScriptId; + /** + * JavaScript script line number. + */ + lineNumber: number; + /** + * JavaScript script column number. + */ + columnNumber: number; + }; + /** + * Call frames for async function calls, console assertions, and error messages. + */ + export type StackTrace = { + callFrames: CallFrame[]; + /** + * Whether the first item in <code>callFrames</code> is the native function that scheduled the asynchronous operation (e.g. setTimeout). + */ + topCallFrameIsBoundary?: boolean | undefined; + /** + * Whether one or more frames have been truncated from the bottom of the stack. + */ + truncated?: boolean | undefined; + /** + * Parent StackTrace. + */ + parentStackTrace?: StackTrace | undefined; + }; + /** + * Issued when new console message is added. + * @event `Console.messageAdded` + */ + export type MessageAddedEvent = { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + }; + /** + * Issued when subsequent message(s) are equal to the previous one(s). + * @event `Console.messageRepeatCountUpdated` + */ + export type MessageRepeatCountUpdatedEvent = { + /** + * New repeat count value. + */ + count: number; + /** + * Timestamp of the latest message. + */ + timestamp?: number | undefined; + }; + /** + * Issued when console is cleared. This happens either upon <code>clearMessages</code> command or after page navigation. + * @event `Console.messagesCleared` + */ + export type MessagesClearedEvent = { + /** + * The reason the console is being cleared. + */ + reason: ClearReason; + }; + /** + * Issued from console.takeHeapSnapshot. + * @event `Console.heapSnapshot` + */ + export type HeapSnapshotEvent = { + timestamp: number; + /** + * Snapshot at the end of tracking. + */ + snapshotData: Heap.HeapSnapshotData; + /** + * Optional title provided to console.takeHeapSnapshot. + */ + title?: string | undefined; + }; + /** + * Enables console domain, sends the messages collected so far to the client by means of the <code>messageAdded</code> notification. + * @request `Console.enable` + */ + export type EnableRequest = {}; + /** + * Enables console domain, sends the messages collected so far to the client by means of the <code>messageAdded</code> notification. + * @response `Console.enable` + */ + export type EnableResponse = {}; + /** + * Disables console domain, prevents further console messages from being reported to the client. + * @request `Console.disable` + */ + export type DisableRequest = {}; + /** + * Disables console domain, prevents further console messages from being reported to the client. + * @response `Console.disable` + */ + export type DisableResponse = {}; + /** + * Clears console messages collected in the browser. + * @request `Console.clearMessages` + */ + export type ClearMessagesRequest = {}; + /** + * Clears console messages collected in the browser. + * @response `Console.clearMessages` + */ + export type ClearMessagesResponse = {}; + /** + * List of the different message sources that are non-default logging channels. + * @request `Console.getLoggingChannels` + */ + export type GetLoggingChannelsRequest = {}; + /** + * List of the different message sources that are non-default logging channels. + * @response `Console.getLoggingChannels` + */ + export type GetLoggingChannelsResponse = { + /** + * Logging channels. + */ + channels: Channel[]; + }; + /** + * Modify the level of a channel. + * @request `Console.setLoggingChannelLevel` + */ + export type SetLoggingChannelLevelRequest = { + /** + * Logging channel to modify. + */ + source: ChannelSource; + /** + * New level. + */ + level: ChannelLevel; + }; + /** + * Modify the level of a channel. + * @response `Console.setLoggingChannelLevel` + */ + export type SetLoggingChannelLevelResponse = {}; + } + export namespace CPUProfiler { + /** + * CPU usage for an individual thread. + */ + export type ThreadInfo = { + /** + * Some thread identification information. + */ + name: string; + /** + * CPU usage for this thread. This should not exceed 100% for an individual thread. + */ + usage: number; + /** + * Type of thread. There should be a single main thread. + */ + type?: "main" | "webkit" | undefined; + /** + * A thread may be associated with a target, such as a Worker, in the process. + */ + targetId?: string | undefined; + }; + export type Event = { + timestamp: number; + /** + * Percent of total cpu usage. If there are multiple cores the usage may be greater than 100%. + */ + usage: number; + /** + * Per-thread CPU usage information. Does not include the main thread. + */ + threads?: ThreadInfo[] | undefined; + }; + /** + * Tracking started. + * @event `CPUProfiler.trackingStart` + */ + export type TrackingStartEvent = { + timestamp: number; + }; + /** + * Periodic tracking updates with event data. + * @event `CPUProfiler.trackingUpdate` + */ + export type TrackingUpdateEvent = { + event: Event; + }; + /** + * Tracking stopped. + * @event `CPUProfiler.trackingComplete` + */ + export type TrackingCompleteEvent = { + timestamp: number; + }; + /** + * Start tracking cpu usage. + * @request `CPUProfiler.startTracking` + */ + export type StartTrackingRequest = {}; + /** + * Start tracking cpu usage. + * @response `CPUProfiler.startTracking` + */ + export type StartTrackingResponse = {}; + /** + * Stop tracking cpu usage. This will produce a `trackingComplete` event. + * @request `CPUProfiler.stopTracking` + */ + export type StopTrackingRequest = {}; + /** + * Stop tracking cpu usage. This will produce a `trackingComplete` event. + * @response `CPUProfiler.stopTracking` + */ + export type StopTrackingResponse = {}; + } + export namespace Debugger { + /** + * Breakpoint identifier. + */ + export type BreakpointId = string; + /** + * Breakpoint action identifier. + */ + export type BreakpointActionIdentifier = number; + /** + * Unique script identifier. + */ + export type ScriptId = string; + /** + * Call frame identifier. + */ + export type CallFrameId = string; + /** + * Location in the source code. + */ + export type Location = { + /** + * Script identifier as reported in the <code>Debugger.scriptParsed</code>. + */ + scriptId: ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + }; + /** + * Action to perform when a breakpoint is triggered. + */ + export type BreakpointAction = { + /** + * Different kinds of breakpoint actions. + */ + type: "log" | "evaluate" | "sound" | "probe"; + /** + * Data associated with this breakpoint type (e.g. for type "eval" this is the JavaScript string to evaluate). + */ + data?: string | undefined; + /** + * A frontend-assigned identifier for this breakpoint action. + */ + id?: BreakpointActionIdentifier | undefined; + /** + * Indicates whether this action should be executed with a user gesture or not. Defaults to <code>false<code>. + */ + emulateUserGesture?: boolean | undefined; + }; + /** + * Extra options that modify breakpoint behavior. + */ + export type BreakpointOptions = { + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + /** + * Actions to perform automatically when the breakpoint is triggered. + */ + actions?: BreakpointAction[] | undefined; + /** + * Automatically continue after hitting this breakpoint and running actions. + */ + autoContinue?: boolean | undefined; + /** + * Number of times to ignore this breakpoint, before stopping on the breakpoint and running actions. + */ + ignoreCount?: number | undefined; + }; + /** + * Information about the function. + */ + export type FunctionDetails = { + /** + * Location of the function. + */ + location: Location; + /** + * Name of the function. Not present for anonymous functions. + */ + name?: string | undefined; + /** + * Display name of the function(specified in 'displayName' property on the function object). + */ + displayName?: string | undefined; + /** + * Scope chain for this closure. + */ + scopeChain?: Scope[] | undefined; + }; + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + export type CallFrame = { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + location: Location; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * <code>this</code> object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * Is the current frame tail deleted from a tail call. + */ + isTailDeleted: boolean; + }; + /** + * Scope description. + */ + export type Scope = { + /** + * Object representing the scope. For <code>global</code> and <code>with</code> scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + /** + * Scope type. + */ + type: "global" | "with" | "closure" | "catch" | "functionName" | "globalLexicalEnvironment" | "nestedLexical"; + /** + * Name associated with the scope. + */ + name?: string | undefined; + /** + * Location if available of the scope definition. + */ + location?: Location | undefined; + /** + * Whether the scope has any variables. + */ + empty?: boolean | undefined; + }; + /** + * A sample collected by evaluating a probe breakpoint action. + */ + export type ProbeSample = { + /** + * Identifier of the probe breakpoint action that created the sample. + */ + probeId: BreakpointActionIdentifier; + /** + * Unique identifier for this sample. + */ + sampleId: number; + /** + * A batch identifier which is the same for all samples taken at the same breakpoint hit. + */ + batchId: number; + /** + * Timestamp of when the sample was taken. + */ + timestamp: number; + /** + * Contents of the sample. + */ + payload: Runtime.RemoteObject; + }; + /** + * The pause reason auxiliary data when paused because of an assertion. + */ + export type AssertPauseReason = { + /** + * The console.assert message string if provided. + */ + message?: string | undefined; + }; + /** + * The pause reason auxiliary data when paused because of hitting a breakpoint. + */ + export type BreakpointPauseReason = { + /** + * The identifier of the breakpoint causing the pause. + */ + breakpointId: string; + }; + /** + * The pause reason auxiliary data when paused because of a Content Security Policy directive. + */ + export type CSPViolationPauseReason = { + /** + * The CSP directive that blocked script execution. + */ + directive: string; + }; + /** + * Called when global has been cleared and debugger client should reset its state. Happens upon navigation or reload. + * @event `Debugger.globalObjectCleared` + */ + export type GlobalObjectClearedEvent = {}; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + * @event `Debugger.scriptParsed` + */ + export type ScriptParsedEvent = { + /** + * Identifier of the script parsed. + */ + scriptId: ScriptId; + /** + * URL of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Determines whether this script is a user extension script. + */ + isContentScript?: boolean | undefined; + /** + * sourceURL name of the script (if any). + */ + sourceURL?: string | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True if this script was parsed as a module. + */ + module?: boolean | undefined; + }; + /** + * Fired when virtual machine fails to parse the script. + * @event `Debugger.scriptFailedToParse` + */ + export type ScriptFailedToParseEvent = { + /** + * URL of the script that failed to parse. + */ + url: string; + /** + * Source text of the script that failed to parse. + */ + scriptSource: string; + /** + * Line offset of the script within the resource. + */ + startLine: number; + /** + * Line with error. + */ + errorLine: number; + /** + * Parse error message. + */ + errorMessage: string; + }; + /** + * Fired when breakpoint is resolved to an actual script and location. + * @event `Debugger.breakpointResolved` + */ + export type BreakpointResolvedEvent = { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + }; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + * @event `Debugger.paused` + */ + export type PausedEvent = { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: + | "URL" + | "DOM" + | "AnimationFrame" + | "Interval" + | "Listener" + | "Timeout" + | "exception" + | "assert" + | "CSPViolation" + | "DebuggerStatement" + | "Breakpoint" + | "PauseOnNextStatement" + | "Microtask" + | "FunctionCall" + | "BlackboxedScript" + | "other"; + /** + * Object containing break-specific auxiliary properties. + */ + data?: Record<string, unknown> | undefined; + /** + * Linked list of asynchronous StackTraces. + */ + asyncStackTrace?: Console.StackTrace | undefined; + }; + /** + * Fired when the virtual machine resumed execution. + * @event `Debugger.resumed` + */ + export type ResumedEvent = {}; + /** + * Fires when a new probe sample is collected. + * @event `Debugger.didSampleProbe` + */ + export type DidSampleProbeEvent = { + /** + * A collected probe sample. + */ + sample: ProbeSample; + }; + /** + * Fired when a "sound" breakpoint action is triggered on a breakpoint. + * @event `Debugger.playBreakpointActionSound` + */ + export type PlayBreakpointActionSoundEvent = { + /** + * Breakpoint action identifier. + */ + breakpointActionId: BreakpointActionIdentifier; + }; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + * @request `Debugger.enable` + */ + export type EnableRequest = {}; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + * @response `Debugger.enable` + */ + export type EnableResponse = {}; + /** + * Disables debugger for given page. + * @request `Debugger.disable` + */ + export type DisableRequest = {}; + /** + * Disables debugger for given page. + * @response `Debugger.disable` + */ + export type DisableResponse = {}; + /** + * Set the async stack trace depth for the page. A value of zero disables recording of async stack traces. + * @request `Debugger.setAsyncStackTraceDepth` + */ + export type SetAsyncStackTraceDepthRequest = { + /** + * Async stack trace depth. + */ + depth: number; + }; + /** + * Set the async stack trace depth for the page. A value of zero disables recording of async stack traces. + * @response `Debugger.setAsyncStackTraceDepth` + */ + export type SetAsyncStackTraceDepthResponse = {}; + /** + * Activates / deactivates all breakpoints on the page. + * @request `Debugger.setBreakpointsActive` + */ + export type SetBreakpointsActiveRequest = { + /** + * New value for breakpoints active state. + */ + active: boolean; + }; + /** + * Activates / deactivates all breakpoints on the page. + * @response `Debugger.setBreakpointsActive` + */ + export type SetBreakpointsActiveResponse = {}; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in <code>locations</code> property. Further matching script parsing will result in subsequent <code>breakpointResolved</code> events issued. This logical breakpoint will survive page reloads. + * @request `Debugger.setBreakpointByUrl` + */ + export type SetBreakpointByUrlRequest = { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either <code>url</code> or <code>urlRegex</code> must be specified. + */ + urlRegex?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Options to apply to this breakpoint to modify its behavior. + */ + options?: BreakpointOptions | undefined; + }; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in <code>locations</code> property. Further matching script parsing will result in subsequent <code>breakpointResolved</code> events issued. This logical breakpoint will survive page reloads. + * @response `Debugger.setBreakpointByUrl` + */ + export type SetBreakpointByUrlResponse = { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + }; + /** + * Sets JavaScript breakpoint at a given location. + * @request `Debugger.setBreakpoint` + */ + export type SetBreakpointRequest = { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Options to apply to this breakpoint to modify its behavior. + */ + options?: BreakpointOptions | undefined; + }; + /** + * Sets JavaScript breakpoint at a given location. + * @response `Debugger.setBreakpoint` + */ + export type SetBreakpointResponse = { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + }; + /** + * Removes JavaScript breakpoint. + * @request `Debugger.removeBreakpoint` + */ + export type RemoveBreakpointRequest = { + breakpointId: BreakpointId; + }; + /** + * Removes JavaScript breakpoint. + * @response `Debugger.removeBreakpoint` + */ + export type RemoveBreakpointResponse = {}; + /** + * Adds a JavaScript breakpoint that pauses execution whenever a function with the given name is about to be called. + * @request `Debugger.addSymbolicBreakpoint` + */ + export type AddSymbolicBreakpointRequest = { + /** + * The name of the function to pause in when called. + */ + symbol: string; + /** + * If true, symbol is case sensitive. Defaults to true. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats symbol as a regex. Defaults to false. + */ + isRegex?: boolean | undefined; + /** + * Options to apply to this breakpoint to modify its behavior. + */ + options?: BreakpointOptions | undefined; + }; + /** + * Adds a JavaScript breakpoint that pauses execution whenever a function with the given name is about to be called. + * @response `Debugger.addSymbolicBreakpoint` + */ + export type AddSymbolicBreakpointResponse = {}; + /** + * Removes a previously added symbolic breakpoint. + * @request `Debugger.removeSymbolicBreakpoint` + */ + export type RemoveSymbolicBreakpointRequest = { + /** + * The name of the function to pause in when called. + */ + symbol: string; + /** + * If true, symbol is case sensitive. Defaults to true. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats symbol as a regex. Defaults to false. + */ + isRegex?: boolean | undefined; + }; + /** + * Removes a previously added symbolic breakpoint. + * @response `Debugger.removeSymbolicBreakpoint` + */ + export type RemoveSymbolicBreakpointResponse = {}; + /** + * Continues execution until the current evaluation completes. This will trigger either a Debugger.paused or Debugger.resumed event. + * @request `Debugger.continueUntilNextRunLoop` + */ + export type ContinueUntilNextRunLoopRequest = {}; + /** + * Continues execution until the current evaluation completes. This will trigger either a Debugger.paused or Debugger.resumed event. + * @response `Debugger.continueUntilNextRunLoop` + */ + export type ContinueUntilNextRunLoopResponse = {}; + /** + * Continues execution until specific location is reached. This will trigger either a Debugger.paused or Debugger.resumed event. + * @request `Debugger.continueToLocation` + */ + export type ContinueToLocationRequest = { + /** + * Location to continue to. + */ + location: Location; + }; + /** + * Continues execution until specific location is reached. This will trigger either a Debugger.paused or Debugger.resumed event. + * @response `Debugger.continueToLocation` + */ + export type ContinueToLocationResponse = {}; + /** + * Steps over the expression. This will trigger either a Debugger.paused or Debugger.resumed event. + * @request `Debugger.stepNext` + */ + export type StepNextRequest = {}; + /** + * Steps over the expression. This will trigger either a Debugger.paused or Debugger.resumed event. + * @response `Debugger.stepNext` + */ + export type StepNextResponse = {}; + /** + * Steps over the statement. This will trigger either a Debugger.paused or Debugger.resumed event. + * @request `Debugger.stepOver` + */ + export type StepOverRequest = {}; + /** + * Steps over the statement. This will trigger either a Debugger.paused or Debugger.resumed event. + * @response `Debugger.stepOver` + */ + export type StepOverResponse = {}; + /** + * Steps into the function call. This will trigger either a Debugger.paused or Debugger.resumed event. + * @request `Debugger.stepInto` + */ + export type StepIntoRequest = {}; + /** + * Steps into the function call. This will trigger either a Debugger.paused or Debugger.resumed event. + * @response `Debugger.stepInto` + */ + export type StepIntoResponse = {}; + /** + * Steps out of the function call. This will trigger either a Debugger.paused or Debugger.resumed event. + * @request `Debugger.stepOut` + */ + export type StepOutRequest = {}; + /** + * Steps out of the function call. This will trigger either a Debugger.paused or Debugger.resumed event. + * @response `Debugger.stepOut` + */ + export type StepOutResponse = {}; + /** + * Stops on the next JavaScript statement. + * @request `Debugger.pause` + */ + export type PauseRequest = {}; + /** + * Stops on the next JavaScript statement. + * @response `Debugger.pause` + */ + export type PauseResponse = {}; + /** + * Resumes JavaScript execution. This will trigger a Debugger.resumed event. + * @request `Debugger.resume` + */ + export type ResumeRequest = {}; + /** + * Resumes JavaScript execution. This will trigger a Debugger.resumed event. + * @response `Debugger.resume` + */ + export type ResumeResponse = {}; + /** + * Searches for given string in script content. + * @request `Debugger.searchInContent` + */ + export type SearchInContentRequest = { + /** + * Id of the script to search in. + */ + scriptId: ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + }; + /** + * Searches for given string in script content. + * @response `Debugger.searchInContent` + */ + export type SearchInContentResponse = { + /** + * List of search matches. + */ + result: GenericTypes.SearchMatch[]; + }; + /** + * Returns source for the script with given id. + * @request `Debugger.getScriptSource` + */ + export type GetScriptSourceRequest = { + /** + * Id of the script to get source for. + */ + scriptId: ScriptId; + }; + /** + * Returns source for the script with given id. + * @response `Debugger.getScriptSource` + */ + export type GetScriptSourceResponse = { + /** + * Script source. + */ + scriptSource: string; + }; + /** + * Returns detailed information on given function. + * @request `Debugger.getFunctionDetails` + */ + export type GetFunctionDetailsRequest = { + /** + * Id of the function to get location for. + */ + functionId: Runtime.RemoteObjectId; + }; + /** + * Returns detailed information on given function. + * @response `Debugger.getFunctionDetails` + */ + export type GetFunctionDetailsResponse = { + /** + * Information about the function. + */ + details: FunctionDetails; + }; + /** + * Returns a list of valid breakpoint locations within the given location range. + * @request `Debugger.getBreakpointLocations` + */ + export type GetBreakpointLocationsRequest = { + /** + * Starting location to look for breakpoint locations after (inclusive). Must have same scriptId as end. + */ + start: Location; + /** + * Ending location to look for breakpoint locations before (exclusive). Must have same scriptId as start. + */ + end: Location; + }; + /** + * Returns a list of valid breakpoint locations within the given location range. + * @response `Debugger.getBreakpointLocations` + */ + export type GetBreakpointLocationsResponse = { + /** + * List of resolved breakpoint locations. + */ + locations: Location[]; + }; + /** + * Control whether the debugger pauses execution before `debugger` statements. + * @request `Debugger.setPauseOnDebuggerStatements` + */ + export type SetPauseOnDebuggerStatementsRequest = { + enabled: boolean; + /** + * Options to apply to this breakpoint to modify its behavior. + */ + options?: BreakpointOptions | undefined; + }; + /** + * Control whether the debugger pauses execution before `debugger` statements. + * @response `Debugger.setPauseOnDebuggerStatements` + */ + export type SetPauseOnDebuggerStatementsResponse = {}; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is <code>none</code>. + * @request `Debugger.setPauseOnExceptions` + */ + export type SetPauseOnExceptionsRequest = { + /** + * Pause on exceptions mode. + */ + state: "none" | "uncaught" | "all"; + /** + * Options to apply to this breakpoint to modify its behavior. + */ + options?: BreakpointOptions | undefined; + }; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is <code>none</code>. + * @response `Debugger.setPauseOnExceptions` + */ + export type SetPauseOnExceptionsResponse = {}; + /** + * Set pause on assertions state. Assertions are console.assert assertions. + * @request `Debugger.setPauseOnAssertions` + */ + export type SetPauseOnAssertionsRequest = { + enabled: boolean; + /** + * Options to apply to this breakpoint to modify its behavior. + */ + options?: BreakpointOptions | undefined; + }; + /** + * Set pause on assertions state. Assertions are console.assert assertions. + * @response `Debugger.setPauseOnAssertions` + */ + export type SetPauseOnAssertionsResponse = {}; + /** + * Pause when running the next JavaScript microtask. + * @request `Debugger.setPauseOnMicrotasks` + */ + export type SetPauseOnMicrotasksRequest = { + enabled: boolean; + /** + * Options to apply to this breakpoint to modify its behavior. + */ + options?: BreakpointOptions | undefined; + }; + /** + * Pause when running the next JavaScript microtask. + * @response `Debugger.setPauseOnMicrotasks` + */ + export type SetPauseOnMicrotasksResponse = {}; + /** + * Change whether to pause in the debugger for internal scripts. The default value is false. + * @request `Debugger.setPauseForInternalScripts` + */ + export type SetPauseForInternalScriptsRequest = { + shouldPause: boolean; + }; + /** + * Change whether to pause in the debugger for internal scripts. The default value is false. + * @response `Debugger.setPauseForInternalScripts` + */ + export type SetPauseForInternalScriptsResponse = {}; + /** + * Evaluates expression on a given call frame. + * @request `Debugger.evaluateOnCallFrame` + */ + export type EvaluateOnCallFrameRequest = { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using <code>releaseObjectGroup</code>). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Specifies whether evaluation should stop on exceptions and mute console. Overrides setPauseOnException state. + */ + doNotPauseOnExceptionsAndMuteConsole?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether the resulting value should be considered for saving in the $n history. + */ + saveResult?: boolean | undefined; + /** + * Whether the expression should be considered to be in a user gesture or not. + */ + emulateUserGesture?: boolean | undefined; + }; + /** + * Evaluates expression on a given call frame. + * @response `Debugger.evaluateOnCallFrame` + */ + export type EvaluateOnCallFrameResponse = { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * If the result was saved, this is the $n index that can be used to access the value. + */ + savedResultIndex?: number | undefined; + }; + /** + * Sets whether the given URL should be in the list of blackboxed scripts, which are ignored when pausing/stepping/debugging. + * @request `Debugger.setShouldBlackboxURL` + */ + export type SetShouldBlackboxURLRequest = { + url: string; + shouldBlackbox: boolean; + /** + * If true, <code>url</code> is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treat <code>url</code> as regular expression. + */ + isRegex?: boolean | undefined; + }; + /** + * Sets whether the given URL should be in the list of blackboxed scripts, which are ignored when pausing/stepping/debugging. + * @response `Debugger.setShouldBlackboxURL` + */ + export type SetShouldBlackboxURLResponse = {}; + /** + * Sets whether evaluation of breakpoint conditions, ignore counts, and actions happen at the location of the breakpoint or are deferred due to blackboxing. + * @request `Debugger.setBlackboxBreakpointEvaluations` + */ + export type SetBlackboxBreakpointEvaluationsRequest = { + blackboxBreakpointEvaluations: boolean; + }; + /** + * Sets whether evaluation of breakpoint conditions, ignore counts, and actions happen at the location of the breakpoint or are deferred due to blackboxing. + * @response `Debugger.setBlackboxBreakpointEvaluations` + */ + export type SetBlackboxBreakpointEvaluationsResponse = {}; + } + export namespace GenericTypes { + /** + * Search match in a resource. + */ + export type SearchMatch = { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + }; + } + export namespace Heap { + /** + * Information about a garbage collection. + */ + export type GarbageCollection = { + /** + * The type of garbage collection. + */ + type: "full" | "partial"; + startTime: number; + endTime: number; + }; + /** + * JavaScriptCore HeapSnapshot JSON data. + */ + export type HeapSnapshotData = string; + /** + * Information about the garbage collection. + * @event `Heap.garbageCollected` + */ + export type GarbageCollectedEvent = { + collection: GarbageCollection; + }; + /** + * Tracking started. + * @event `Heap.trackingStart` + */ + export type TrackingStartEvent = { + timestamp: number; + /** + * Snapshot at the start of tracking. + */ + snapshotData: HeapSnapshotData; + }; + /** + * Tracking stopped. + * @event `Heap.trackingComplete` + */ + export type TrackingCompleteEvent = { + timestamp: number; + /** + * Snapshot at the end of tracking. + */ + snapshotData: HeapSnapshotData; + }; + /** + * Enables Heap domain events. + * @request `Heap.enable` + */ + export type EnableRequest = {}; + /** + * Enables Heap domain events. + * @response `Heap.enable` + */ + export type EnableResponse = {}; + /** + * Disables Heap domain events. + * @request `Heap.disable` + */ + export type DisableRequest = {}; + /** + * Disables Heap domain events. + * @response `Heap.disable` + */ + export type DisableResponse = {}; + /** + * Trigger a full garbage collection. + * @request `Heap.gc` + */ + export type GcRequest = {}; + /** + * Trigger a full garbage collection. + * @response `Heap.gc` + */ + export type GcResponse = {}; + /** + * Take a heap snapshot. + * @request `Heap.snapshot` + */ + export type SnapshotRequest = {}; + /** + * Take a heap snapshot. + * @response `Heap.snapshot` + */ + export type SnapshotResponse = { + timestamp: number; + snapshotData: HeapSnapshotData; + }; + /** + * Start tracking heap changes. This will produce a `trackingStart` event. + * @request `Heap.startTracking` + */ + export type StartTrackingRequest = {}; + /** + * Start tracking heap changes. This will produce a `trackingStart` event. + * @response `Heap.startTracking` + */ + export type StartTrackingResponse = {}; + /** + * Stop tracking heap changes. This will produce a `trackingComplete` event. + * @request `Heap.stopTracking` + */ + export type StopTrackingRequest = {}; + /** + * Stop tracking heap changes. This will produce a `trackingComplete` event. + * @response `Heap.stopTracking` + */ + export type StopTrackingResponse = {}; + /** + * Returns a preview (string, Debugger.FunctionDetails, or Runtime.ObjectPreview) for a Heap.HeapObjectId. + * @request `Heap.getPreview` + */ + export type GetPreviewRequest = { + /** + * Identifier of the heap object within the snapshot. + */ + heapObjectId: number; + }; + /** + * Returns a preview (string, Debugger.FunctionDetails, or Runtime.ObjectPreview) for a Heap.HeapObjectId. + * @response `Heap.getPreview` + */ + export type GetPreviewResponse = { + /** + * String value. + */ + string?: string | undefined; + /** + * Function details. + */ + functionDetails?: Debugger.FunctionDetails | undefined; + /** + * Object preview. + */ + preview?: Runtime.ObjectPreview | undefined; + }; + /** + * Returns the strongly referenced Runtime.RemoteObject for a Heap.HeapObjectId. + * @request `Heap.getRemoteObject` + */ + export type GetRemoteObjectRequest = { + /** + * Identifier of the heap object within the snapshot. + */ + heapObjectId: number; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + }; + /** + * Returns the strongly referenced Runtime.RemoteObject for a Heap.HeapObjectId. + * @response `Heap.getRemoteObject` + */ + export type GetRemoteObjectResponse = { + /** + * Resulting object. + */ + result: Runtime.RemoteObject; + }; + } + export namespace Inspector { + /** + * undefined + * @event `Inspector.evaluateForTestInFrontend` + */ + export type EvaluateForTestInFrontendEvent = { + script: string; + }; + /** + * undefined + * @event `Inspector.inspect` + */ + export type InspectEvent = { + object: Runtime.RemoteObject; + hints: Record<string, unknown>; + }; + /** + * Enables inspector domain notifications. + * @request `Inspector.enable` + */ + export type EnableRequest = {}; + /** + * Enables inspector domain notifications. + * @response `Inspector.enable` + */ + export type EnableResponse = {}; + /** + * Disables inspector domain notifications. + * @request `Inspector.disable` + */ + export type DisableRequest = {}; + /** + * Disables inspector domain notifications. + * @response `Inspector.disable` + */ + export type DisableResponse = {}; + /** + * Sent by the frontend after all initialization messages have been sent. + * @request `Inspector.initialized` + */ + export type InitializedRequest = {}; + /** + * Sent by the frontend after all initialization messages have been sent. + * @response `Inspector.initialized` + */ + export type InitializedResponse = {}; + } + export namespace Network { + /** + * Unique loader identifier. + */ + export type LoaderId = string; + /** + * Unique frame identifier. + */ + export type FrameId = string; + /** + * Unique request identifier. + */ + export type RequestId = string; + /** + * Elapsed seconds since frontend connected. + */ + export type Timestamp = number; + /** + * Number of seconds since epoch. + */ + export type Walltime = number; + /** + * Controls how much referrer information is sent with the request + */ + export type ReferrerPolicy = + | "empty-string" + | "no-referrer" + | "no-referrer-when-downgrade" + | "same-origin" + | "origin" + | "strict-origin" + | "origin-when-cross-origin" + | "strict-origin-when-cross-origin" + | "unsafe-url"; + /** + * Request / response headers as keys / values of JSON object. + */ + export type Headers = Record<string, unknown>; + /** + * Timing information for the request. + */ + export type ResourceTiming = { + /** + * Request is initiated + */ + startTime: Timestamp; + /** + * Started redirect resolution. + */ + redirectStart: Timestamp; + /** + * Finished redirect resolution. + */ + redirectEnd: Timestamp; + /** + * Resource fetching started. + */ + fetchStart: Timestamp; + /** + * Started DNS address resolve in milliseconds relative to fetchStart. + */ + domainLookupStart: number; + /** + * Finished DNS address resolve in milliseconds relative to fetchStart. + */ + domainLookupEnd: number; + /** + * Started connecting to the remote host in milliseconds relative to fetchStart. + */ + connectStart: number; + /** + * Connected to the remote host in milliseconds relative to fetchStart. + */ + connectEnd: number; + /** + * Started SSL handshake in milliseconds relative to fetchStart. + */ + secureConnectionStart: number; + /** + * Started sending request in milliseconds relative to fetchStart. + */ + requestStart: number; + /** + * Started receiving response headers in milliseconds relative to fetchStart. + */ + responseStart: number; + /** + * Finished receiving response headers in milliseconds relative to fetchStart. + */ + responseEnd: number; + }; + /** + * HTTP request data. + */ + export type Request = { + /** + * Request URL. + */ + url: string; + /** + * HTTP request method. + */ + method: string; + /** + * HTTP request headers. + */ + headers: Headers; + /** + * HTTP POST request data. + */ + postData?: string | undefined; + /** + * The level of included referrer information. + */ + referrerPolicy?: ReferrerPolicy | undefined; + /** + * The base64 cryptographic hash of the resource. + */ + integrity?: string | undefined; + }; + /** + * HTTP response data. + */ + export type Response = { + /** + * Response URL. This URL can be different from CachedResource.url in case of redirect. + */ + url: string; + /** + * HTTP response status code. + */ + status: number; + /** + * HTTP response status text. + */ + statusText: string; + /** + * HTTP response headers. + */ + headers: Headers; + /** + * Resource mimeType as determined by the browser. + */ + mimeType: string; + /** + * Specifies where the response came from. + */ + source: "unknown" | "network" | "memory-cache" | "disk-cache" | "service-worker" | "inspector-override"; + /** + * Refined HTTP request headers that were actually transmitted over the network. + */ + requestHeaders?: Headers | undefined; + /** + * Timing information for the given request. + */ + timing?: ResourceTiming | undefined; + /** + * The security information for the given request. + */ + security?: Security.Security | undefined; + }; + /** + * Network load metrics. + */ + export type Metrics = { + /** + * Network protocol. ALPN Protocol ID Identification Sequence, as per RFC 7301 (for example, http/2, http/1.1, spdy/3.1) + */ + protocol?: string | undefined; + /** + * Network priority. + */ + priority?: "low" | "medium" | "high" | undefined; + /** + * Connection identifier. + */ + connectionIdentifier?: string | undefined; + /** + * Remote IP address. + */ + remoteAddress?: string | undefined; + /** + * Refined HTTP request headers that were actually transmitted over the network. + */ + requestHeaders?: Headers | undefined; + /** + * Total HTTP request header bytes sent over the network. + */ + requestHeaderBytesSent?: number | undefined; + /** + * Total HTTP request body bytes sent over the network. + */ + requestBodyBytesSent?: number | undefined; + /** + * Total HTTP response header bytes received over the network. + */ + responseHeaderBytesReceived?: number | undefined; + /** + * Total HTTP response body bytes received over the network. + */ + responseBodyBytesReceived?: number | undefined; + /** + * Total decoded response body size in bytes. + */ + responseBodyDecodedSize?: number | undefined; + /** + * Connection information for the completed request. + */ + securityConnection?: Security.Connection | undefined; + /** + * Whether or not the connection was proxied through a server. If <code>true</code>, the <code>remoteAddress</code> will be for the proxy server, not the server that provided the resource to the proxy server. + */ + isProxyConnection?: boolean | undefined; + }; + /** + * WebSocket request data. + */ + export type WebSocketRequest = { + /** + * HTTP response headers. + */ + headers: Headers; + }; + /** + * WebSocket response data. + */ + export type WebSocketResponse = { + /** + * HTTP response status code. + */ + status: number; + /** + * HTTP response status text. + */ + statusText: string; + /** + * HTTP response headers. + */ + headers: Headers; + }; + /** + * WebSocket frame data. + */ + export type WebSocketFrame = { + /** + * WebSocket frame opcode. + */ + opcode: number; + /** + * WebSocket frame mask. + */ + mask: boolean; + /** + * WebSocket frame payload data, binary frames (opcode = 2) are base64-encoded. + */ + payloadData: string; + /** + * WebSocket frame payload length in bytes. + */ + payloadLength: number; + }; + /** + * Information about the cached resource. + */ + export type CachedResource = { + /** + * Resource URL. This is the url of the original network request. + */ + url: string; + /** + * Type of this resource. + */ + type: Page.ResourceType; + /** + * Cached response data. + */ + response?: Response | undefined; + /** + * Cached response body size. + */ + bodySize: number; + /** + * URL of source map associated with this resource (if any). + */ + sourceMapURL?: string | undefined; + }; + /** + * Information about the request initiator. + */ + export type Initiator = { + /** + * Type of this initiator. + */ + type: "parser" | "script" | "other"; + /** + * Initiator JavaScript stack trace, set for Script only. + */ + stackTrace?: Console.StackTrace | undefined; + /** + * Initiator URL, set for Parser type only. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type only. + */ + lineNumber?: number | undefined; + /** + * Set if the load was triggered by a DOM node, in addition to the other initiator information. + */ + nodeId?: DOM.NodeId | undefined; + }; + /** + * Different stages of a network request. + */ + export type NetworkStage = "request" | "response"; + /** + * Different stages of a network request. + */ + export type ResourceErrorType = "General" | "AccessControl" | "Cancellation" | "Timeout"; + /** + * Fired when page is about to send HTTP request. + * @event `Network.requestWillBeSent` + */ + export type RequestWillBeSentEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Frame identifier. + */ + frameId: FrameId; + /** + * Loader identifier. + */ + loaderId: LoaderId; + /** + * URL of the document this request is loaded for. + */ + documentURL: string; + /** + * Request data. + */ + request: Request; + timestamp: Timestamp; + walltime: Walltime; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Redirect response data. + */ + redirectResponse?: Response | undefined; + /** + * Resource type. + */ + type?: Page.ResourceType | undefined; + /** + * Identifier for the context of where the load originated. In general this is the target identifier. For Workers this will be the workerId. + */ + targetId?: string | undefined; + }; + /** + * Fired when HTTP response is available. + * @event `Network.responseReceived` + */ + export type ResponseReceivedEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Frame identifier. + */ + frameId: FrameId; + /** + * Loader identifier. + */ + loaderId: LoaderId; + /** + * Timestamp. + */ + timestamp: Timestamp; + /** + * Resource type. + */ + type: Page.ResourceType; + /** + * Response data. + */ + response: Response; + }; + /** + * Fired when data chunk was received over the network. + * @event `Network.dataReceived` + */ + export type DataReceivedEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: Timestamp; + /** + * Data chunk length. + */ + dataLength: number; + /** + * Actual bytes received (might be less than dataLength for compressed encodings). + */ + encodedDataLength: number; + }; + /** + * Fired when HTTP request has finished loading. + * @event `Network.loadingFinished` + */ + export type LoadingFinishedEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: Timestamp; + /** + * URL of source map associated with this resource (if any). + */ + sourceMapURL?: string | undefined; + /** + * Network metrics. + */ + metrics?: Metrics | undefined; + }; + /** + * Fired when HTTP request has failed to load. + * @event `Network.loadingFailed` + */ + export type LoadingFailedEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: Timestamp; + /** + * User friendly error message. + */ + errorText: string; + /** + * True if loading was canceled. + */ + canceled?: boolean | undefined; + }; + /** + * Fired when HTTP request has been served from memory cache. + * @event `Network.requestServedFromMemoryCache` + */ + export type RequestServedFromMemoryCacheEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Frame identifier. + */ + frameId: FrameId; + /** + * Loader identifier. + */ + loaderId: LoaderId; + /** + * URL of the document this request is loaded for. + */ + documentURL: string; + /** + * Timestamp. + */ + timestamp: Timestamp; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Cached resource data. + */ + resource: CachedResource; + }; + /** + * Fired when HTTP request has been intercepted. The frontend must respond with <code>Network.interceptContinue</code>, <code>Network.interceptWithRequest</code>` or <code>Network.interceptWithResponse</code>` to resolve this request. + * @event `Network.requestIntercepted` + */ + export type RequestInterceptedEvent = { + /** + * Identifier for this intercepted network. Corresponds with an earlier <code>Network.requestWillBeSent</code>. + */ + requestId: RequestId; + /** + * Original request content that would proceed if this is continued. + */ + request: Request; + }; + /** + * Fired when HTTP response has been intercepted. The frontend must response with <code>Network.interceptContinue</code> or <code>Network.interceptWithResponse</code>` to continue this response. + * @event `Network.responseIntercepted` + */ + export type ResponseInterceptedEvent = { + /** + * Identifier for this intercepted network. Corresponds with an earlier <code>Network.requestWillBeSent</code>. + */ + requestId: RequestId; + /** + * Original response content that would proceed if this is continued. + */ + response: Response; + }; + /** + * Fired when WebSocket is about to initiate handshake. + * @event `Network.webSocketWillSendHandshakeRequest` + */ + export type WebSocketWillSendHandshakeRequestEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + timestamp: Timestamp; + walltime: Walltime; + /** + * WebSocket request data. + */ + request: WebSocketRequest; + }; + /** + * Fired when WebSocket handshake response becomes available. + * @event `Network.webSocketHandshakeResponseReceived` + */ + export type WebSocketHandshakeResponseReceivedEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + timestamp: Timestamp; + /** + * WebSocket response data. + */ + response: WebSocketResponse; + }; + /** + * Fired upon WebSocket creation. + * @event `Network.webSocketCreated` + */ + export type WebSocketCreatedEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * WebSocket request URL. + */ + url: string; + }; + /** + * Fired when WebSocket is closed. + * @event `Network.webSocketClosed` + */ + export type WebSocketClosedEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: Timestamp; + }; + /** + * Fired when WebSocket frame is received. + * @event `Network.webSocketFrameReceived` + */ + export type WebSocketFrameReceivedEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: Timestamp; + /** + * WebSocket response data. + */ + response: WebSocketFrame; + }; + /** + * Fired when WebSocket frame error occurs. + * @event `Network.webSocketFrameError` + */ + export type WebSocketFrameErrorEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: Timestamp; + /** + * WebSocket frame error message. + */ + errorMessage: string; + }; + /** + * Fired when WebSocket frame is sent. + * @event `Network.webSocketFrameSent` + */ + export type WebSocketFrameSentEvent = { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: Timestamp; + /** + * WebSocket response data. + */ + response: WebSocketFrame; + }; + /** + * Enables network tracking, network events will now be delivered to the client. + * @request `Network.enable` + */ + export type EnableRequest = {}; + /** + * Enables network tracking, network events will now be delivered to the client. + * @response `Network.enable` + */ + export type EnableResponse = {}; + /** + * Disables network tracking, prevents network events from being sent to the client. + * @request `Network.disable` + */ + export type DisableRequest = {}; + /** + * Disables network tracking, prevents network events from being sent to the client. + * @response `Network.disable` + */ + export type DisableResponse = {}; + /** + * Specifies whether to always send extra HTTP headers with the requests from this page. + * @request `Network.setExtraHTTPHeaders` + */ + export type SetExtraHTTPHeadersRequest = { + /** + * Map with extra HTTP headers. + */ + headers: Headers; + }; + /** + * Specifies whether to always send extra HTTP headers with the requests from this page. + * @response `Network.setExtraHTTPHeaders` + */ + export type SetExtraHTTPHeadersResponse = {}; + /** + * Returns content served for the given request. + * @request `Network.getResponseBody` + */ + export type GetResponseBodyRequest = { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + }; + /** + * Returns content served for the given request. + * @response `Network.getResponseBody` + */ + export type GetResponseBodyResponse = { + /** + * Response body. + */ + body: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + }; + /** + * Toggles whether the resource cache may be used when loading resources in the inspected page. If <code>true</code>, the resource cache will not be used when loading resources. + * @request `Network.setResourceCachingDisabled` + */ + export type SetResourceCachingDisabledRequest = { + /** + * Whether to prevent usage of the resource cache. + */ + disabled: boolean; + }; + /** + * Toggles whether the resource cache may be used when loading resources in the inspected page. If <code>true</code>, the resource cache will not be used when loading resources. + * @response `Network.setResourceCachingDisabled` + */ + export type SetResourceCachingDisabledResponse = {}; + /** + * Loads a resource in the context of a frame on the inspected page without cross origin checks. + * @request `Network.loadResource` + */ + export type LoadResourceRequest = { + /** + * Frame to load the resource from. + */ + frameId: FrameId; + /** + * URL of the resource to load. + */ + url: string; + }; + /** + * Loads a resource in the context of a frame on the inspected page without cross origin checks. + * @response `Network.loadResource` + */ + export type LoadResourceResponse = { + /** + * Resource content. + */ + content: string; + /** + * Resource mimeType. + */ + mimeType: string; + /** + * HTTP response status code. + */ + status: number; + }; + /** + * Fetches a serialized secure certificate for the given requestId to be displayed via InspectorFrontendHost.showCertificate. + * @request `Network.getSerializedCertificate` + */ + export type GetSerializedCertificateRequest = { + requestId: RequestId; + }; + /** + * Fetches a serialized secure certificate for the given requestId to be displayed via InspectorFrontendHost.showCertificate. + * @response `Network.getSerializedCertificate` + */ + export type GetSerializedCertificateResponse = { + /** + * Represents a base64 encoded WebCore::CertificateInfo object. + */ + serializedCertificate: string; + }; + /** + * Resolves JavaScript WebSocket object for given request id. + * @request `Network.resolveWebSocket` + */ + export type ResolveWebSocketRequest = { + /** + * Identifier of the WebSocket resource to resolve. + */ + requestId: RequestId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + }; + /** + * Resolves JavaScript WebSocket object for given request id. + * @response `Network.resolveWebSocket` + */ + export type ResolveWebSocketResponse = { + /** + * JavaScript object wrapper for given node. + */ + object: Runtime.RemoteObject; + }; + /** + * Enable interception of network requests. + * @request `Network.setInterceptionEnabled` + */ + export type SetInterceptionEnabledRequest = { + enabled: boolean; + }; + /** + * Enable interception of network requests. + * @response `Network.setInterceptionEnabled` + */ + export type SetInterceptionEnabledResponse = {}; + /** + * Add an interception. + * @request `Network.addInterception` + */ + export type AddInterceptionRequest = { + /** + * URL pattern to intercept, intercept everything if not specified or empty + */ + url: string; + /** + * Stage to intercept. + */ + stage: NetworkStage; + /** + * If false, ignores letter casing of `url` parameter. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats `url` parameter as a regular expression. + */ + isRegex?: boolean | undefined; + }; + /** + * Add an interception. + * @response `Network.addInterception` + */ + export type AddInterceptionResponse = {}; + /** + * Remove an interception. + * @request `Network.removeInterception` + */ + export type RemoveInterceptionRequest = { + url: string; + /** + * Stage to intercept. + */ + stage: NetworkStage; + /** + * If false, ignores letter casing of `url` parameter. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats `url` parameter as a regular expression. + */ + isRegex?: boolean | undefined; + }; + /** + * Remove an interception. + * @response `Network.removeInterception` + */ + export type RemoveInterceptionResponse = {}; + /** + * Continue request or response without modifications. + * @request `Network.interceptContinue` + */ + export type InterceptContinueRequest = { + /** + * Identifier for the intercepted Network request or response to continue. + */ + requestId: RequestId; + /** + * Stage to continue. + */ + stage: NetworkStage; + }; + /** + * Continue request or response without modifications. + * @response `Network.interceptContinue` + */ + export type InterceptContinueResponse = {}; + /** + * Replace intercepted request with the provided one. + * @request `Network.interceptWithRequest` + */ + export type InterceptWithRequestRequest = { + /** + * Identifier for the intercepted Network request or response to continue. + */ + requestId: RequestId; + /** + * HTTP request url. + */ + url?: string | undefined; + /** + * HTTP request method. + */ + method?: string | undefined; + /** + * HTTP response headers. Pass through original values if unmodified. + */ + headers?: Headers | undefined; + /** + * HTTP POST request data, base64-encoded. + */ + postData?: string | undefined; + }; + /** + * Replace intercepted request with the provided one. + * @response `Network.interceptWithRequest` + */ + export type InterceptWithRequestResponse = {}; + /** + * Provide response content for an intercepted response. + * @request `Network.interceptWithResponse` + */ + export type InterceptWithResponseRequest = { + /** + * Identifier for the intercepted Network response to modify. + */ + requestId: RequestId; + content: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + /** + * MIME Type for the data. + */ + mimeType?: string | undefined; + /** + * HTTP response status code. Pass through original values if unmodified. + */ + status?: number | undefined; + /** + * HTTP response status text. Pass through original values if unmodified. + */ + statusText?: string | undefined; + /** + * HTTP response headers. Pass through original values if unmodified. + */ + headers?: Headers | undefined; + }; + /** + * Provide response content for an intercepted response. + * @response `Network.interceptWithResponse` + */ + export type InterceptWithResponseResponse = {}; + /** + * Provide response for an intercepted request. Request completely bypasses the network in this case and is immediately fulfilled with the provided data. + * @request `Network.interceptRequestWithResponse` + */ + export type InterceptRequestWithResponseRequest = { + /** + * Identifier for the intercepted Network response to modify. + */ + requestId: RequestId; + content: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + /** + * MIME Type for the data. + */ + mimeType: string; + /** + * HTTP response status code. + */ + status: number; + /** + * HTTP response status text. + */ + statusText: string; + /** + * HTTP response headers. + */ + headers: Headers; + }; + /** + * Provide response for an intercepted request. Request completely bypasses the network in this case and is immediately fulfilled with the provided data. + * @response `Network.interceptRequestWithResponse` + */ + export type InterceptRequestWithResponseResponse = {}; + /** + * Fail request with given error type. + * @request `Network.interceptRequestWithError` + */ + export type InterceptRequestWithErrorRequest = { + /** + * Identifier for the intercepted Network request to fail. + */ + requestId: RequestId; + /** + * Deliver error reason for the request failure. + */ + errorType: ResourceErrorType; + }; + /** + * Fail request with given error type. + * @response `Network.interceptRequestWithError` + */ + export type InterceptRequestWithErrorResponse = {}; + /** + * Emulate various network conditions (e.g. bytes per second, latency, etc.). + * @request `Network.setEmulatedConditions` + */ + export type SetEmulatedConditionsRequest = { + /** + * Limits the bytes per second of requests if positive. Removes any limits if zero or not provided. + */ + bytesPerSecondLimit?: number | undefined; + }; + /** + * Emulate various network conditions (e.g. bytes per second, latency, etc.). + * @response `Network.setEmulatedConditions` + */ + export type SetEmulatedConditionsResponse = {}; + } + export namespace Runtime { + /** + * Unique object identifier. + */ + export type RemoteObjectId = string; + /** + * Mirror object referencing original JavaScript object. + */ + export type RemoteObject = { + /** + * Object type. + */ + type: "object" | "function" | "undefined" | "string" | "number" | "boolean" | "symbol" | "bigint"; + /** + * Object subtype hint. Specified for <code>object</code> <code>function</code> (for class) type values only. + */ + subtype?: + | "array" + | "null" + | "node" + | "regexp" + | "date" + | "error" + | "map" + | "set" + | "weakmap" + | "weakset" + | "iterator" + | "class" + | "proxy" + | "weakref" + | undefined; + /** + * Object class (constructor) name. Specified for <code>object</code> type values only. + */ + className?: string | undefined; + /** + * Remote object value (in case of primitive values or JSON values if it was requested). + */ + value?: unknown | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Size of the array/collection. Specified for array/map/set/weakmap/weakset object type values only. + */ + size?: number | undefined; + /** + * Remote object for the class prototype. Specified for class object type values only. + */ + classPrototype?: RemoteObject | undefined; + /** + * Preview containing abbreviated property values. Specified for <code>object</code> type values only. + */ + preview?: ObjectPreview | undefined; + }; + /** + * Object containing abbreviated remote object value. + */ + export type ObjectPreview = { + /** + * Object type. + */ + type: "object" | "function" | "undefined" | "string" | "number" | "boolean" | "symbol" | "bigint"; + /** + * Object subtype hint. Specified for <code>object</code> type values only. + */ + subtype?: + | "array" + | "null" + | "node" + | "regexp" + | "date" + | "error" + | "map" + | "set" + | "weakmap" + | "weakset" + | "iterator" + | "class" + | "proxy" + | "weakref" + | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Determines whether preview is lossless (contains all information of the original object). + */ + lossless: boolean; + /** + * True iff some of the properties of the original did not fit. + */ + overflow?: boolean | undefined; + /** + * List of the properties. + */ + properties?: PropertyPreview[] | undefined; + /** + * List of the entries. Specified for <code>map</code> and <code>set</code> subtype values only. + */ + entries?: EntryPreview[] | undefined; + /** + * Size of the array/collection. Specified for array/map/set/weakmap/weakset object type values only. + */ + size?: number | undefined; + }; + export type PropertyPreview = { + /** + * Property name. + */ + name: string; + /** + * Object type. + */ + type: "object" | "function" | "undefined" | "string" | "number" | "boolean" | "symbol" | "bigint" | "accessor"; + /** + * Object subtype hint. Specified for <code>object</code> type values only. + */ + subtype?: + | "array" + | "null" + | "node" + | "regexp" + | "date" + | "error" + | "map" + | "set" + | "weakmap" + | "weakset" + | "iterator" + | "class" + | "proxy" + | "weakref" + | undefined; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * True if this is a private field. + */ + isPrivate?: boolean | undefined; + /** + * True if this is an internal property. + */ + internal?: boolean | undefined; + }; + export type EntryPreview = { + /** + * Entry key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Entry value. + */ + value: ObjectPreview; + }; + export type CollectionEntry = { + /** + * Entry key of a map-like collection, otherwise not provided. + */ + key?: Runtime.RemoteObject | undefined; + /** + * Entry value. + */ + value: Runtime.RemoteObject; + }; + /** + * Object property descriptor. + */ + export type PropertyDescriptor = { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or <code>undefined</code> if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or <code>undefined</code> if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable?: boolean | undefined; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is a symbol. + */ + symbol?: Runtime.RemoteObject | undefined; + /** + * True if the property is a private field. + */ + isPrivate?: boolean | undefined; + /** + * True if the property value came from a native getter. + */ + nativeGetter?: boolean | undefined; + }; + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + export type InternalPropertyDescriptor = { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + }; + /** + * Represents function call argument. Either remote object id <code>objectId</code> or primitive <code>value</code> or neither of (for undefined) them should be specified. + */ + export type CallArgument = { + /** + * Primitive value. + */ + value?: unknown | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + }; + /** + * Id of an execution context. + */ + export type ExecutionContextId = number; + /** + * Type of the execution context. + */ + export type ExecutionContextType = "normal" | "user" | "internal"; + /** + * Description of an isolated world. + */ + export type ExecutionContextDescription = { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + type: ExecutionContextType; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Id of the owning frame. + */ + frameId: Network.FrameId; + }; + /** + * Syntax error type: "none" for no error, "irrecoverable" for unrecoverable errors, "unterminated-literal" for when there is an unterminated literal, "recoverable" for when the expression is unfinished but valid so far. + */ + export type SyntaxErrorType = "none" | "irrecoverable" | "unterminated-literal" | "recoverable"; + /** + * Range of an error in source code. + */ + export type ErrorRange = { + /** + * Start offset of range (inclusive). + */ + startOffset: number; + /** + * End offset of range (exclusive). + */ + endOffset: number; + }; + export type StructureDescription = { + /** + * Array of strings, where the strings represent object properties. + */ + fields?: string[] | undefined; + /** + * Array of strings, where the strings represent optional object properties. + */ + optionalFields?: string[] | undefined; + /** + * Name of the constructor. + */ + constructorName?: string | undefined; + /** + * Pointer to the StructureRepresentation of the protoype if one exists. + */ + prototypeStructure?: StructureDescription | undefined; + /** + * If true, it indicates that the fields in this StructureDescription may be inaccurate. I.e, there might have been fields that have been deleted before it was profiled or it has fields we haven't profiled. + */ + isImprecise?: boolean | undefined; + }; + export type TypeSet = { + /** + * Indicates if this type description has been type Function. + */ + isFunction: boolean; + /** + * Indicates if this type description has been type Undefined. + */ + isUndefined: boolean; + /** + * Indicates if this type description has been type Null. + */ + isNull: boolean; + /** + * Indicates if this type description has been type Boolean. + */ + isBoolean: boolean; + /** + * Indicates if this type description has been type Integer. + */ + isInteger: boolean; + /** + * Indicates if this type description has been type Number. + */ + isNumber: boolean; + /** + * Indicates if this type description has been type String. + */ + isString: boolean; + /** + * Indicates if this type description has been type Object. + */ + isObject: boolean; + /** + * Indicates if this type description has been type Symbol. + */ + isSymbol: boolean; + /** + * Indicates if this type description has been type BigInt. + */ + isBigInt: boolean; + }; + /** + * Container for type information that has been gathered. + */ + export type TypeDescription = { + /** + * If true, we were able to correlate the offset successfuly with a program location. If false, the offset may be bogus or the offset may be from a CodeBlock that hasn't executed. + */ + isValid: boolean; + /** + * Least common ancestor of all Constructors if the TypeDescription has seen any structures. This string is the display name of the shared constructor function. + */ + leastCommonAncestor?: string | undefined; + /** + * Set of booleans for determining the aggregate type of this type description. + */ + typeSet?: TypeSet | undefined; + /** + * Array of descriptions for all structures seen for this variable. + */ + structures?: StructureDescription[] | undefined; + /** + * If true, this indicates that no more structures are being profiled because some maximum threshold has been reached and profiling has stopped because of memory pressure. + */ + isTruncated?: boolean | undefined; + }; + /** + * Describes the location of an expression we want type information for. + */ + export type TypeLocation = { + /** + * What kind of type information do we want (normal, function return values, 'this' statement). + */ + typeInformationDescriptor: number; + /** + * sourceID uniquely identifying a script + */ + sourceID: string; + /** + * character offset for assignment range + */ + divot: number; + }; + /** + * From Wikipedia: a basic block is a portion of the code within a program with only one entry point and only one exit point. This type gives the location of a basic block and if that basic block has executed. + */ + export type BasicBlock = { + /** + * Start offset of the basic block. + */ + startOffset: number; + /** + * End offset of the basic block. + */ + endOffset: number; + /** + * Indicates if the basic block has executed before. + */ + hasExecuted: boolean; + /** + * Indicates how many times the basic block has executed. + */ + executionCount: number; + }; + /** + * Issued when new execution context is created. + * @event `Runtime.executionContextCreated` + */ + export type ExecutionContextCreatedEvent = { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + }; + /** + * Parses JavaScript source code for errors. + * @request `Runtime.parse` + */ + export type ParseRequest = { + /** + * Source code to parse. + */ + source: string; + }; + /** + * Parses JavaScript source code for errors. + * @response `Runtime.parse` + */ + export type ParseResponse = { + /** + * Parse result. + */ + result: SyntaxErrorType; + /** + * Parse error message. + */ + message?: string | undefined; + /** + * Range in the source where the error occurred. + */ + range?: ErrorRange | undefined; + }; + /** + * Evaluates expression on global object. + * @request `Runtime.evaluate` + */ + export type EvaluateRequest = { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Specifies whether evaluation should stop on exceptions and mute console. Overrides setPauseOnException state. + */ + doNotPauseOnExceptionsAndMuteConsole?: boolean | undefined; + /** + * Specifies in which isolated context to perform evaluation. Each content script lives in an isolated context and this parameter may be used to specify one of those contexts. If the parameter is omitted or 0 the evaluation will be performed in the context of the inspected page. + */ + contextId?: Runtime.ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether the resulting value should be considered for saving in the $n history. + */ + saveResult?: boolean | undefined; + /** + * Whether the expression should be considered to be in a user gesture or not. + */ + emulateUserGesture?: boolean | undefined; + }; + /** + * Evaluates expression on global object. + * @response `Runtime.evaluate` + */ + export type EvaluateResponse = { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * If the result was saved, this is the $n index that can be used to access the value. + */ + savedResultIndex?: number | undefined; + }; + /** + * Calls the async callback when the promise with the given ID gets settled. + * @request `Runtime.awaitPromise` + */ + export type AwaitPromiseRequest = { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether the resulting value should be considered for saving in the $n history. + */ + saveResult?: boolean | undefined; + }; + /** + * Calls the async callback when the promise with the given ID gets settled. + * @response `Runtime.awaitPromise` + */ + export type AwaitPromiseResponse = { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * If the result was saved, this is the $n index that can be used to access the value. + */ + savedResultIndex?: number | undefined; + }; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + * @request `Runtime.callFunctionOn` + */ + export type CallFunctionOnRequest = { + /** + * Identifier of the object to call function on. + */ + objectId: RemoteObjectId; + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * Specifies whether function call should stop on exceptions and mute console. Overrides setPauseOnException state. + */ + doNotPauseOnExceptionsAndMuteConsole?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether the expression should be considered to be in a user gesture or not. + */ + emulateUserGesture?: boolean | undefined; + }; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + * @response `Runtime.callFunctionOn` + */ + export type CallFunctionOnResponse = { + /** + * Call result. + */ + result: RemoteObject; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + }; + /** + * Returns a preview for the given object. + * @request `Runtime.getPreview` + */ + export type GetPreviewRequest = { + /** + * Identifier of the object to return a preview for. + */ + objectId: RemoteObjectId; + }; + /** + * Returns a preview for the given object. + * @response `Runtime.getPreview` + */ + export type GetPreviewResponse = { + preview: ObjectPreview; + }; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + * @request `Runtime.getProperties` + */ + export type GetPropertiesRequest = { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the object itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If provided skip to this value before collecting values. Otherwise, start at the beginning. Has no effect when the `objectId` is for a `iterator`/`WeakMap`/`WeakSet` object. + */ + fetchStart?: number | undefined; + /** + * If provided only return `fetchCount` values. Otherwise, return values all the way to the end. + */ + fetchCount?: number | undefined; + /** + * Whether preview should be generated for property values. + */ + generatePreview?: boolean | undefined; + }; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + * @response `Runtime.getProperties` + */ + export type GetPropertiesResponse = { + /** + * Object properties. + */ + properties: PropertyDescriptor[]; + /** + * Internal object properties. Only included if `fetchStart` is 0. + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + }; + /** + * Returns displayable properties of a given object. Object group of the result is inherited from the target object. Displayable properties are own properties, internal properties, and native getters in the prototype chain (assumed to be bindings and treated like own properties for the frontend). + * @request `Runtime.getDisplayableProperties` + */ + export type GetDisplayablePropertiesRequest = { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If provided skip to this value before collecting values. Otherwise, start at the beginning. Has no effect when the `objectId` is for a `iterator`/`WeakMap`/`WeakSet` object. + */ + fetchStart?: number | undefined; + /** + * If provided only return `fetchCount` values. Otherwise, return values all the way to the end. + */ + fetchCount?: number | undefined; + /** + * Whether preview should be generated for property values. + */ + generatePreview?: boolean | undefined; + }; + /** + * Returns displayable properties of a given object. Object group of the result is inherited from the target object. Displayable properties are own properties, internal properties, and native getters in the prototype chain (assumed to be bindings and treated like own properties for the frontend). + * @response `Runtime.getDisplayableProperties` + */ + export type GetDisplayablePropertiesResponse = { + /** + * Object properties. + */ + properties: PropertyDescriptor[]; + /** + * Internal object properties. Only included if `fetchStart` is 0. + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + }; + /** + * Returns entries of given Map / Set collection. + * @request `Runtime.getCollectionEntries` + */ + export type GetCollectionEntriesRequest = { + /** + * Id of the collection to get entries for. + */ + objectId: Runtime.RemoteObjectId; + /** + * Symbolic group name that can be used to release multiple. If not provided, it will be the same objectGroup as the RemoteObject determined from <code>objectId</code>. This is useful for WeakMap to release the collection entries. + */ + objectGroup?: string | undefined; + /** + * If provided skip to this value before collecting values. Otherwise, start at the beginning. Has no effect when the `objectId<` is for a `iterator<`/`WeakMap<`/`WeakSet<` object. + */ + fetchStart?: number | undefined; + /** + * If provided only return `fetchCount` values. Otherwise, return values all the way to the end. + */ + fetchCount?: number | undefined; + }; + /** + * Returns entries of given Map / Set collection. + * @response `Runtime.getCollectionEntries` + */ + export type GetCollectionEntriesResponse = { + /** + * Array of collection entries. + */ + entries: CollectionEntry[]; + }; + /** + * Assign a saved result index to this value. + * @request `Runtime.saveResult` + */ + export type SaveResultRequest = { + /** + * Id or value of the object to save. + */ + value: CallArgument; + /** + * Unique id of the execution context. To specify in which execution context script evaluation should be performed. If not provided, determine from the CallArgument's objectId. + */ + contextId?: ExecutionContextId | undefined; + }; + /** + * Assign a saved result index to this value. + * @response `Runtime.saveResult` + */ + export type SaveResultResponse = { + /** + * If the value was saved, this is the $n index that can be used to access the value. + */ + savedResultIndex?: number | undefined; + }; + /** + * Creates an additional reference to all saved values in the Console using the the given string as a prefix instead of $. + * @request `Runtime.setSavedResultAlias` + */ + export type SetSavedResultAliasRequest = { + /** + * Passing an empty/null string will clear the alias. + */ + alias?: string | undefined; + }; + /** + * Creates an additional reference to all saved values in the Console using the the given string as a prefix instead of $. + * @response `Runtime.setSavedResultAlias` + */ + export type SetSavedResultAliasResponse = {}; + /** + * Releases remote object with given id. + * @request `Runtime.releaseObject` + */ + export type ReleaseObjectRequest = { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + }; + /** + * Releases remote object with given id. + * @response `Runtime.releaseObject` + */ + export type ReleaseObjectResponse = {}; + /** + * Releases all remote objects that belong to a given group. + * @request `Runtime.releaseObjectGroup` + */ + export type ReleaseObjectGroupRequest = { + /** + * Symbolic object group name. + */ + objectGroup: string; + }; + /** + * Releases all remote objects that belong to a given group. + * @response `Runtime.releaseObjectGroup` + */ + export type ReleaseObjectGroupResponse = {}; + /** + * Enables reporting of execution contexts creation by means of <code>executionContextCreated</code> event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + * @request `Runtime.enable` + */ + export type EnableRequest = {}; + /** + * Enables reporting of execution contexts creation by means of <code>executionContextCreated</code> event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + * @response `Runtime.enable` + */ + export type EnableResponse = {}; + /** + * Disables reporting of execution contexts creation. + * @request `Runtime.disable` + */ + export type DisableRequest = {}; + /** + * Disables reporting of execution contexts creation. + * @response `Runtime.disable` + */ + export type DisableResponse = {}; + /** + * Returns detailed information on the given function. + * @request `Runtime.getRuntimeTypesForVariablesAtOffsets` + */ + export type GetRuntimeTypesForVariablesAtOffsetsRequest = { + /** + * An array of type locations we're requesting information for. Results are expected in the same order they're sent in. + */ + locations: TypeLocation[]; + }; + /** + * Returns detailed information on the given function. + * @response `Runtime.getRuntimeTypesForVariablesAtOffsets` + */ + export type GetRuntimeTypesForVariablesAtOffsetsResponse = { + types: TypeDescription[]; + }; + /** + * Enables type profiling on the VM. + * @request `Runtime.enableTypeProfiler` + */ + export type EnableTypeProfilerRequest = {}; + /** + * Enables type profiling on the VM. + * @response `Runtime.enableTypeProfiler` + */ + export type EnableTypeProfilerResponse = {}; + /** + * Disables type profiling on the VM. + * @request `Runtime.disableTypeProfiler` + */ + export type DisableTypeProfilerRequest = {}; + /** + * Disables type profiling on the VM. + * @response `Runtime.disableTypeProfiler` + */ + export type DisableTypeProfilerResponse = {}; + /** + * Enables control flow profiling on the VM. + * @request `Runtime.enableControlFlowProfiler` + */ + export type EnableControlFlowProfilerRequest = {}; + /** + * Enables control flow profiling on the VM. + * @response `Runtime.enableControlFlowProfiler` + */ + export type EnableControlFlowProfilerResponse = {}; + /** + * Disables control flow profiling on the VM. + * @request `Runtime.disableControlFlowProfiler` + */ + export type DisableControlFlowProfilerRequest = {}; + /** + * Disables control flow profiling on the VM. + * @response `Runtime.disableControlFlowProfiler` + */ + export type DisableControlFlowProfilerResponse = {}; + /** + * Returns a list of basic blocks for the given sourceID with information about their text ranges and whether or not they have executed. + * @request `Runtime.getBasicBlocks` + */ + export type GetBasicBlocksRequest = { + /** + * Indicates which sourceID information is requested for. + */ + sourceID: string; + }; + /** + * Returns a list of basic blocks for the given sourceID with information about their text ranges and whether or not they have executed. + * @response `Runtime.getBasicBlocks` + */ + export type GetBasicBlocksResponse = { + basicBlocks: BasicBlock[]; + }; + } + export namespace ScriptProfiler { + export type EventType = "API" | "Microtask" | "Other"; + export type Event = { + startTime: number; + endTime: number; + type: EventType; + }; + export type ExpressionLocation = { + /** + * 1-based. + */ + line: number; + /** + * 1-based. + */ + column: number; + }; + export type StackFrame = { + /** + * Unique script identifier. + */ + sourceID: Debugger.ScriptId; + /** + * A displayable name for the stack frame. i.e function name, (program), etc. + */ + name: string; + /** + * -1 if unavailable. 1-based if available. + */ + line: number; + /** + * -1 if unavailable. 1-based if available. + */ + column: number; + url: string; + expressionLocation?: ExpressionLocation | undefined; + }; + export type StackTrace = { + timestamp: number; + /** + * First array item is the bottom of the call stack and last array item is the top of the call stack. + */ + stackFrames: StackFrame[]; + }; + export type Samples = { + stackTraces: StackTrace[]; + }; + /** + * Tracking started. + * @event `ScriptProfiler.trackingStart` + */ + export type TrackingStartEvent = { + timestamp: number; + }; + /** + * Periodic tracking updates with event data. + * @event `ScriptProfiler.trackingUpdate` + */ + export type TrackingUpdateEvent = { + event: Event; + }; + /** + * Tracking stopped. Includes any buffered data during tracking, such as profiling information. + * @event `ScriptProfiler.trackingComplete` + */ + export type TrackingCompleteEvent = { + timestamp: number; + /** + * Stack traces. + */ + samples?: Samples | undefined; + }; + /** + * Start tracking script evaluations. + * @request `ScriptProfiler.startTracking` + */ + export type StartTrackingRequest = { + /** + * Start the sampling profiler, defaults to false. + */ + includeSamples?: boolean | undefined; + }; + /** + * Start tracking script evaluations. + * @response `ScriptProfiler.startTracking` + */ + export type StartTrackingResponse = {}; + /** + * Stop tracking script evaluations. This will produce a `trackingComplete` event. + * @request `ScriptProfiler.stopTracking` + */ + export type StopTrackingRequest = {}; + /** + * Stop tracking script evaluations. This will produce a `trackingComplete` event. + * @response `ScriptProfiler.stopTracking` + */ + export type StopTrackingResponse = {}; + } + export type EventMap = { + "Console.messageAdded": Console.MessageAddedEvent; + "Console.messageRepeatCountUpdated": Console.MessageRepeatCountUpdatedEvent; + "Console.messagesCleared": Console.MessagesClearedEvent; + "Console.heapSnapshot": Console.HeapSnapshotEvent; + "CPUProfiler.trackingStart": CPUProfiler.TrackingStartEvent; + "CPUProfiler.trackingUpdate": CPUProfiler.TrackingUpdateEvent; + "CPUProfiler.trackingComplete": CPUProfiler.TrackingCompleteEvent; + "Debugger.globalObjectCleared": Debugger.GlobalObjectClearedEvent; + "Debugger.scriptParsed": Debugger.ScriptParsedEvent; + "Debugger.scriptFailedToParse": Debugger.ScriptFailedToParseEvent; + "Debugger.breakpointResolved": Debugger.BreakpointResolvedEvent; + "Debugger.paused": Debugger.PausedEvent; + "Debugger.resumed": Debugger.ResumedEvent; + "Debugger.didSampleProbe": Debugger.DidSampleProbeEvent; + "Debugger.playBreakpointActionSound": Debugger.PlayBreakpointActionSoundEvent; + "Heap.garbageCollected": Heap.GarbageCollectedEvent; + "Heap.trackingStart": Heap.TrackingStartEvent; + "Heap.trackingComplete": Heap.TrackingCompleteEvent; + "Inspector.evaluateForTestInFrontend": Inspector.EvaluateForTestInFrontendEvent; + "Inspector.inspect": Inspector.InspectEvent; + "Network.requestWillBeSent": Network.RequestWillBeSentEvent; + "Network.responseReceived": Network.ResponseReceivedEvent; + "Network.dataReceived": Network.DataReceivedEvent; + "Network.loadingFinished": Network.LoadingFinishedEvent; + "Network.loadingFailed": Network.LoadingFailedEvent; + "Network.requestServedFromMemoryCache": Network.RequestServedFromMemoryCacheEvent; + "Network.requestIntercepted": Network.RequestInterceptedEvent; + "Network.responseIntercepted": Network.ResponseInterceptedEvent; + "Network.webSocketWillSendHandshakeRequest": Network.WebSocketWillSendHandshakeRequestEvent; + "Network.webSocketHandshakeResponseReceived": Network.WebSocketHandshakeResponseReceivedEvent; + "Network.webSocketCreated": Network.WebSocketCreatedEvent; + "Network.webSocketClosed": Network.WebSocketClosedEvent; + "Network.webSocketFrameReceived": Network.WebSocketFrameReceivedEvent; + "Network.webSocketFrameError": Network.WebSocketFrameErrorEvent; + "Network.webSocketFrameSent": Network.WebSocketFrameSentEvent; + "Runtime.executionContextCreated": Runtime.ExecutionContextCreatedEvent; + "ScriptProfiler.trackingStart": ScriptProfiler.TrackingStartEvent; + "ScriptProfiler.trackingUpdate": ScriptProfiler.TrackingUpdateEvent; + "ScriptProfiler.trackingComplete": ScriptProfiler.TrackingCompleteEvent; + }; + export type RequestMap = { + "Console.enable": Console.EnableRequest; + "Console.disable": Console.DisableRequest; + "Console.clearMessages": Console.ClearMessagesRequest; + "Console.getLoggingChannels": Console.GetLoggingChannelsRequest; + "Console.setLoggingChannelLevel": Console.SetLoggingChannelLevelRequest; + "CPUProfiler.startTracking": CPUProfiler.StartTrackingRequest; + "CPUProfiler.stopTracking": CPUProfiler.StopTrackingRequest; + "Debugger.enable": Debugger.EnableRequest; + "Debugger.disable": Debugger.DisableRequest; + "Debugger.setAsyncStackTraceDepth": Debugger.SetAsyncStackTraceDepthRequest; + "Debugger.setBreakpointsActive": Debugger.SetBreakpointsActiveRequest; + "Debugger.setBreakpointByUrl": Debugger.SetBreakpointByUrlRequest; + "Debugger.setBreakpoint": Debugger.SetBreakpointRequest; + "Debugger.removeBreakpoint": Debugger.RemoveBreakpointRequest; + "Debugger.addSymbolicBreakpoint": Debugger.AddSymbolicBreakpointRequest; + "Debugger.removeSymbolicBreakpoint": Debugger.RemoveSymbolicBreakpointRequest; + "Debugger.continueUntilNextRunLoop": Debugger.ContinueUntilNextRunLoopRequest; + "Debugger.continueToLocation": Debugger.ContinueToLocationRequest; + "Debugger.stepNext": Debugger.StepNextRequest; + "Debugger.stepOver": Debugger.StepOverRequest; + "Debugger.stepInto": Debugger.StepIntoRequest; + "Debugger.stepOut": Debugger.StepOutRequest; + "Debugger.pause": Debugger.PauseRequest; + "Debugger.resume": Debugger.ResumeRequest; + "Debugger.searchInContent": Debugger.SearchInContentRequest; + "Debugger.getScriptSource": Debugger.GetScriptSourceRequest; + "Debugger.getFunctionDetails": Debugger.GetFunctionDetailsRequest; + "Debugger.getBreakpointLocations": Debugger.GetBreakpointLocationsRequest; + "Debugger.setPauseOnDebuggerStatements": Debugger.SetPauseOnDebuggerStatementsRequest; + "Debugger.setPauseOnExceptions": Debugger.SetPauseOnExceptionsRequest; + "Debugger.setPauseOnAssertions": Debugger.SetPauseOnAssertionsRequest; + "Debugger.setPauseOnMicrotasks": Debugger.SetPauseOnMicrotasksRequest; + "Debugger.setPauseForInternalScripts": Debugger.SetPauseForInternalScriptsRequest; + "Debugger.evaluateOnCallFrame": Debugger.EvaluateOnCallFrameRequest; + "Debugger.setShouldBlackboxURL": Debugger.SetShouldBlackboxURLRequest; + "Debugger.setBlackboxBreakpointEvaluations": Debugger.SetBlackboxBreakpointEvaluationsRequest; + "Heap.enable": Heap.EnableRequest; + "Heap.disable": Heap.DisableRequest; + "Heap.gc": Heap.GcRequest; + "Heap.snapshot": Heap.SnapshotRequest; + "Heap.startTracking": Heap.StartTrackingRequest; + "Heap.stopTracking": Heap.StopTrackingRequest; + "Heap.getPreview": Heap.GetPreviewRequest; + "Heap.getRemoteObject": Heap.GetRemoteObjectRequest; + "Inspector.enable": Inspector.EnableRequest; + "Inspector.disable": Inspector.DisableRequest; + "Inspector.initialized": Inspector.InitializedRequest; + "Network.enable": Network.EnableRequest; + "Network.disable": Network.DisableRequest; + "Network.setExtraHTTPHeaders": Network.SetExtraHTTPHeadersRequest; + "Network.getResponseBody": Network.GetResponseBodyRequest; + "Network.setResourceCachingDisabled": Network.SetResourceCachingDisabledRequest; + "Network.loadResource": Network.LoadResourceRequest; + "Network.getSerializedCertificate": Network.GetSerializedCertificateRequest; + "Network.resolveWebSocket": Network.ResolveWebSocketRequest; + "Network.setInterceptionEnabled": Network.SetInterceptionEnabledRequest; + "Network.addInterception": Network.AddInterceptionRequest; + "Network.removeInterception": Network.RemoveInterceptionRequest; + "Network.interceptContinue": Network.InterceptContinueRequest; + "Network.interceptWithRequest": Network.InterceptWithRequestRequest; + "Network.interceptWithResponse": Network.InterceptWithResponseRequest; + "Network.interceptRequestWithResponse": Network.InterceptRequestWithResponseRequest; + "Network.interceptRequestWithError": Network.InterceptRequestWithErrorRequest; + "Network.setEmulatedConditions": Network.SetEmulatedConditionsRequest; + "Runtime.parse": Runtime.ParseRequest; + "Runtime.evaluate": Runtime.EvaluateRequest; + "Runtime.awaitPromise": Runtime.AwaitPromiseRequest; + "Runtime.callFunctionOn": Runtime.CallFunctionOnRequest; + "Runtime.getPreview": Runtime.GetPreviewRequest; + "Runtime.getProperties": Runtime.GetPropertiesRequest; + "Runtime.getDisplayableProperties": Runtime.GetDisplayablePropertiesRequest; + "Runtime.getCollectionEntries": Runtime.GetCollectionEntriesRequest; + "Runtime.saveResult": Runtime.SaveResultRequest; + "Runtime.setSavedResultAlias": Runtime.SetSavedResultAliasRequest; + "Runtime.releaseObject": Runtime.ReleaseObjectRequest; + "Runtime.releaseObjectGroup": Runtime.ReleaseObjectGroupRequest; + "Runtime.enable": Runtime.EnableRequest; + "Runtime.disable": Runtime.DisableRequest; + "Runtime.getRuntimeTypesForVariablesAtOffsets": Runtime.GetRuntimeTypesForVariablesAtOffsetsRequest; + "Runtime.enableTypeProfiler": Runtime.EnableTypeProfilerRequest; + "Runtime.disableTypeProfiler": Runtime.DisableTypeProfilerRequest; + "Runtime.enableControlFlowProfiler": Runtime.EnableControlFlowProfilerRequest; + "Runtime.disableControlFlowProfiler": Runtime.DisableControlFlowProfilerRequest; + "Runtime.getBasicBlocks": Runtime.GetBasicBlocksRequest; + "ScriptProfiler.startTracking": ScriptProfiler.StartTrackingRequest; + "ScriptProfiler.stopTracking": ScriptProfiler.StopTrackingRequest; + }; + export type ResponseMap = { + "Console.enable": Console.EnableResponse; + "Console.disable": Console.DisableResponse; + "Console.clearMessages": Console.ClearMessagesResponse; + "Console.getLoggingChannels": Console.GetLoggingChannelsResponse; + "Console.setLoggingChannelLevel": Console.SetLoggingChannelLevelResponse; + "CPUProfiler.startTracking": CPUProfiler.StartTrackingResponse; + "CPUProfiler.stopTracking": CPUProfiler.StopTrackingResponse; + "Debugger.enable": Debugger.EnableResponse; + "Debugger.disable": Debugger.DisableResponse; + "Debugger.setAsyncStackTraceDepth": Debugger.SetAsyncStackTraceDepthResponse; + "Debugger.setBreakpointsActive": Debugger.SetBreakpointsActiveResponse; + "Debugger.setBreakpointByUrl": Debugger.SetBreakpointByUrlResponse; + "Debugger.setBreakpoint": Debugger.SetBreakpointResponse; + "Debugger.removeBreakpoint": Debugger.RemoveBreakpointResponse; + "Debugger.addSymbolicBreakpoint": Debugger.AddSymbolicBreakpointResponse; + "Debugger.removeSymbolicBreakpoint": Debugger.RemoveSymbolicBreakpointResponse; + "Debugger.continueUntilNextRunLoop": Debugger.ContinueUntilNextRunLoopResponse; + "Debugger.continueToLocation": Debugger.ContinueToLocationResponse; + "Debugger.stepNext": Debugger.StepNextResponse; + "Debugger.stepOver": Debugger.StepOverResponse; + "Debugger.stepInto": Debugger.StepIntoResponse; + "Debugger.stepOut": Debugger.StepOutResponse; + "Debugger.pause": Debugger.PauseResponse; + "Debugger.resume": Debugger.ResumeResponse; + "Debugger.searchInContent": Debugger.SearchInContentResponse; + "Debugger.getScriptSource": Debugger.GetScriptSourceResponse; + "Debugger.getFunctionDetails": Debugger.GetFunctionDetailsResponse; + "Debugger.getBreakpointLocations": Debugger.GetBreakpointLocationsResponse; + "Debugger.setPauseOnDebuggerStatements": Debugger.SetPauseOnDebuggerStatementsResponse; + "Debugger.setPauseOnExceptions": Debugger.SetPauseOnExceptionsResponse; + "Debugger.setPauseOnAssertions": Debugger.SetPauseOnAssertionsResponse; + "Debugger.setPauseOnMicrotasks": Debugger.SetPauseOnMicrotasksResponse; + "Debugger.setPauseForInternalScripts": Debugger.SetPauseForInternalScriptsResponse; + "Debugger.evaluateOnCallFrame": Debugger.EvaluateOnCallFrameResponse; + "Debugger.setShouldBlackboxURL": Debugger.SetShouldBlackboxURLResponse; + "Debugger.setBlackboxBreakpointEvaluations": Debugger.SetBlackboxBreakpointEvaluationsResponse; + "Heap.enable": Heap.EnableResponse; + "Heap.disable": Heap.DisableResponse; + "Heap.gc": Heap.GcResponse; + "Heap.snapshot": Heap.SnapshotResponse; + "Heap.startTracking": Heap.StartTrackingResponse; + "Heap.stopTracking": Heap.StopTrackingResponse; + "Heap.getPreview": Heap.GetPreviewResponse; + "Heap.getRemoteObject": Heap.GetRemoteObjectResponse; + "Inspector.enable": Inspector.EnableResponse; + "Inspector.disable": Inspector.DisableResponse; + "Inspector.initialized": Inspector.InitializedResponse; + "Network.enable": Network.EnableResponse; + "Network.disable": Network.DisableResponse; + "Network.setExtraHTTPHeaders": Network.SetExtraHTTPHeadersResponse; + "Network.getResponseBody": Network.GetResponseBodyResponse; + "Network.setResourceCachingDisabled": Network.SetResourceCachingDisabledResponse; + "Network.loadResource": Network.LoadResourceResponse; + "Network.getSerializedCertificate": Network.GetSerializedCertificateResponse; + "Network.resolveWebSocket": Network.ResolveWebSocketResponse; + "Network.setInterceptionEnabled": Network.SetInterceptionEnabledResponse; + "Network.addInterception": Network.AddInterceptionResponse; + "Network.removeInterception": Network.RemoveInterceptionResponse; + "Network.interceptContinue": Network.InterceptContinueResponse; + "Network.interceptWithRequest": Network.InterceptWithRequestResponse; + "Network.interceptWithResponse": Network.InterceptWithResponseResponse; + "Network.interceptRequestWithResponse": Network.InterceptRequestWithResponseResponse; + "Network.interceptRequestWithError": Network.InterceptRequestWithErrorResponse; + "Network.setEmulatedConditions": Network.SetEmulatedConditionsResponse; + "Runtime.parse": Runtime.ParseResponse; + "Runtime.evaluate": Runtime.EvaluateResponse; + "Runtime.awaitPromise": Runtime.AwaitPromiseResponse; + "Runtime.callFunctionOn": Runtime.CallFunctionOnResponse; + "Runtime.getPreview": Runtime.GetPreviewResponse; + "Runtime.getProperties": Runtime.GetPropertiesResponse; + "Runtime.getDisplayableProperties": Runtime.GetDisplayablePropertiesResponse; + "Runtime.getCollectionEntries": Runtime.GetCollectionEntriesResponse; + "Runtime.saveResult": Runtime.SaveResultResponse; + "Runtime.setSavedResultAlias": Runtime.SetSavedResultAliasResponse; + "Runtime.releaseObject": Runtime.ReleaseObjectResponse; + "Runtime.releaseObjectGroup": Runtime.ReleaseObjectGroupResponse; + "Runtime.enable": Runtime.EnableResponse; + "Runtime.disable": Runtime.DisableResponse; + "Runtime.getRuntimeTypesForVariablesAtOffsets": Runtime.GetRuntimeTypesForVariablesAtOffsetsResponse; + "Runtime.enableTypeProfiler": Runtime.EnableTypeProfilerResponse; + "Runtime.disableTypeProfiler": Runtime.DisableTypeProfilerResponse; + "Runtime.enableControlFlowProfiler": Runtime.EnableControlFlowProfilerResponse; + "Runtime.disableControlFlowProfiler": Runtime.DisableControlFlowProfilerResponse; + "Runtime.getBasicBlocks": Runtime.GetBasicBlocksResponse; + "ScriptProfiler.startTracking": ScriptProfiler.StartTrackingResponse; + "ScriptProfiler.stopTracking": ScriptProfiler.StopTrackingResponse; + }; + + export type Event<T extends keyof EventMap = keyof EventMap> = { + readonly method: T; + readonly params: EventMap[T]; + }; + + export type Request<T extends keyof RequestMap = keyof RequestMap> = { + readonly id: number; + readonly method: T; + readonly params: RequestMap[T]; + }; + + export type Response<T extends keyof ResponseMap = keyof ResponseMap> = { + readonly id: number; + } & ( + | { + readonly method?: T; + readonly result: ResponseMap[T]; + } + | { + readonly error: { + readonly code?: string; + readonly message: string; + }; + } + ); +} diff --git a/packages/bun-inspector-protocol/protocol/jsc/protocol.json b/packages/bun-inspector-protocol/protocol/jsc/protocol.json new file mode 100644 index 000000000..ed3bb67e6 --- /dev/null +++ b/packages/bun-inspector-protocol/protocol/jsc/protocol.json @@ -0,0 +1,3114 @@ +{ + "name": "JSC", + "version": { "major": 1, "minor": 3 }, + "domains": [ + { + "domain": "Console", + "description": "Console domain defines methods and events for interaction with the JavaScript console. Console collects messages created by means of the <a href='http://getfirebug.com/wiki/index.php/Console_API'>JavaScript Console API</a>. One needs to enable this domain using <code>enable</code> command in order to start receiving the console messages. Browser collects messages issued while console domain is not enabled as well and reports them using <code>messageAdded</code> notification upon enabling.", + "debuggableTypes": ["itml", "javascript", "page", "service-worker", "web-page"], + "targetTypes": ["itml", "javascript", "page", "service-worker", "worker"], + "types": [ + { + "id": "ChannelSource", + "type": "string", + "enum": [ + "xml", + "javascript", + "network", + "console-api", + "storage", + "appcache", + "rendering", + "css", + "security", + "content-blocker", + "media", + "mediasource", + "webrtc", + "itp-debug", + "private-click-measurement", + "payment-request", + "other" + ], + "description": "Channels for different types of log messages." + }, + { + "id": "ChannelLevel", + "type": "string", + "enum": ["off", "basic", "verbose"], + "description": "Level of logging." + }, + { + "id": "ClearReason", + "type": "string", + "enum": ["console-api", "main-frame-navigation"], + "description": "The reason the console is being cleared." + }, + { + "id": "Channel", + "description": "Logging channel.", + "type": "object", + "properties": [ + { "name": "source", "$ref": "ChannelSource" }, + { "name": "level", "$ref": "ChannelLevel" } + ] + }, + { + "id": "ConsoleMessage", + "type": "object", + "description": "Console message.", + "properties": [ + { "name": "source", "$ref": "ChannelSource" }, + { + "name": "level", + "type": "string", + "enum": ["log", "info", "warning", "error", "debug"], + "description": "Message severity." + }, + { "name": "text", "type": "string", "description": "Message text." }, + { + "name": "type", + "type": "string", + "optional": true, + "enum": [ + "log", + "dir", + "dirxml", + "table", + "trace", + "clear", + "startGroup", + "startGroupCollapsed", + "endGroup", + "assert", + "timing", + "profile", + "profileEnd", + "image" + ], + "description": "Console message type." + }, + { "name": "url", "type": "string", "optional": true, "description": "URL of the message origin." }, + { + "name": "line", + "type": "integer", + "optional": true, + "description": "Line number in the resource that generated this message." + }, + { + "name": "column", + "type": "integer", + "optional": true, + "description": "Column number on the line in the resource that generated this message." + }, + { + "name": "repeatCount", + "type": "integer", + "optional": true, + "description": "Repeat count for repeated messages." + }, + { + "name": "parameters", + "type": "array", + "items": { "$ref": "Runtime.RemoteObject" }, + "optional": true, + "description": "Message parameters in case of the formatted message." + }, + { + "name": "stackTrace", + "$ref": "StackTrace", + "optional": true, + "description": "JavaScript stack trace for assertions and error messages." + }, + { + "name": "networkRequestId", + "$ref": "Network.RequestId", + "optional": true, + "description": "Identifier of the network request associated with this message." + }, + { + "name": "timestamp", + "type": "number", + "optional": true, + "description": "Time when this message was added. Currently only used when an expensive operation happens to make sure that the frontend can account for it." + } + ] + }, + { + "id": "CallFrame", + "type": "object", + "description": "Stack entry for console errors and assertions.", + "properties": [ + { "name": "functionName", "type": "string", "description": "JavaScript function name." }, + { "name": "url", "type": "string", "description": "JavaScript script name or url." }, + { "name": "scriptId", "$ref": "Debugger.ScriptId", "description": "Script identifier." }, + { "name": "lineNumber", "type": "integer", "description": "JavaScript script line number." }, + { "name": "columnNumber", "type": "integer", "description": "JavaScript script column number." } + ] + }, + { + "id": "StackTrace", + "description": "Call frames for async function calls, console assertions, and error messages.", + "type": "object", + "properties": [ + { "name": "callFrames", "type": "array", "items": { "$ref": "CallFrame" } }, + { + "name": "topCallFrameIsBoundary", + "type": "boolean", + "optional": true, + "description": "Whether the first item in <code>callFrames</code> is the native function that scheduled the asynchronous operation (e.g. setTimeout)." + }, + { + "name": "truncated", + "type": "boolean", + "optional": true, + "description": "Whether one or more frames have been truncated from the bottom of the stack." + }, + { "name": "parentStackTrace", "$ref": "StackTrace", "optional": true, "description": "Parent StackTrace." } + ] + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables console domain, sends the messages collected so far to the client by means of the <code>messageAdded</code> notification." + }, + { + "name": "disable", + "description": "Disables console domain, prevents further console messages from being reported to the client." + }, + { "name": "clearMessages", "description": "Clears console messages collected in the browser." }, + { + "name": "getLoggingChannels", + "description": "List of the different message sources that are non-default logging channels.", + "returns": [ + { "name": "channels", "type": "array", "items": { "$ref": "Channel" }, "description": "Logging channels." } + ] + }, + { + "name": "setLoggingChannelLevel", + "description": "Modify the level of a channel.", + "parameters": [ + { "name": "source", "$ref": "ChannelSource", "description": "Logging channel to modify." }, + { "name": "level", "$ref": "ChannelLevel", "description": "New level." } + ] + } + ], + "events": [ + { + "name": "messageAdded", + "description": "Issued when new console message is added.", + "parameters": [ + { "name": "message", "$ref": "ConsoleMessage", "description": "Console message that has been added." } + ] + }, + { + "name": "messageRepeatCountUpdated", + "description": "Issued when subsequent message(s) are equal to the previous one(s).", + "parameters": [ + { "name": "count", "type": "integer", "description": "New repeat count value." }, + { + "name": "timestamp", + "type": "number", + "optional": true, + "description": "Timestamp of the latest message." + } + ] + }, + { + "name": "messagesCleared", + "description": "Issued when console is cleared. This happens either upon <code>clearMessages</code> command or after page navigation.", + "parameters": [ + { "name": "reason", "$ref": "ClearReason", "description": "The reason the console is being cleared." } + ] + }, + { + "name": "heapSnapshot", + "description": "Issued from console.takeHeapSnapshot.", + "parameters": [ + { "name": "timestamp", "type": "number" }, + { + "name": "snapshotData", + "$ref": "Heap.HeapSnapshotData", + "description": "Snapshot at the end of tracking." + }, + { + "name": "title", + "type": "string", + "optional": true, + "description": "Optional title provided to console.takeHeapSnapshot." + } + ] + } + ] + }, + { + "domain": "CPUProfiler", + "description": "CPUProfiler domain exposes cpu usage tracking.", + "condition": "defined(ENABLE_RESOURCE_USAGE) && ENABLE_RESOURCE_USAGE", + "debuggableTypes": ["page", "web-page"], + "targetTypes": ["page"], + "types": [ + { + "id": "ThreadInfo", + "description": "CPU usage for an individual thread.", + "type": "object", + "properties": [ + { "name": "name", "type": "string", "description": "Some thread identification information." }, + { + "name": "usage", + "type": "number", + "description": "CPU usage for this thread. This should not exceed 100% for an individual thread." + }, + { + "name": "type", + "type": "string", + "enum": ["main", "webkit"], + "optional": true, + "description": "Type of thread. There should be a single main thread." + }, + { + "name": "targetId", + "type": "string", + "optional": true, + "description": "A thread may be associated with a target, such as a Worker, in the process." + } + ] + }, + { + "id": "Event", + "type": "object", + "properties": [ + { "name": "timestamp", "type": "number" }, + { + "name": "usage", + "type": "number", + "description": "Percent of total cpu usage. If there are multiple cores the usage may be greater than 100%." + }, + { + "name": "threads", + "type": "array", + "items": { "$ref": "ThreadInfo" }, + "optional": true, + "description": "Per-thread CPU usage information. Does not include the main thread." + } + ] + } + ], + "commands": [ + { "name": "startTracking", "description": "Start tracking cpu usage." }, + { + "name": "stopTracking", + "description": "Stop tracking cpu usage. This will produce a `trackingComplete` event." + } + ], + "events": [ + { + "name": "trackingStart", + "description": "Tracking started.", + "parameters": [{ "name": "timestamp", "type": "number" }] + }, + { + "name": "trackingUpdate", + "description": "Periodic tracking updates with event data.", + "parameters": [{ "name": "event", "$ref": "Event" }] + }, + { + "name": "trackingComplete", + "description": "Tracking stopped.", + "parameters": [{ "name": "timestamp", "type": "number" }] + } + ] + }, + { + "domain": "Debugger", + "description": "Debugger domain exposes JavaScript debugging capabilities. It allows setting and removing breakpoints, stepping through execution, exploring stack traces, etc.", + "debuggableTypes": ["itml", "javascript", "page", "service-worker", "web-page"], + "targetTypes": ["itml", "javascript", "page", "service-worker", "worker"], + "types": [ + { "id": "BreakpointId", "type": "string", "description": "Breakpoint identifier." }, + { "id": "BreakpointActionIdentifier", "type": "integer", "description": "Breakpoint action identifier." }, + { "id": "ScriptId", "type": "string", "description": "Unique script identifier." }, + { "id": "CallFrameId", "type": "string", "description": "Call frame identifier." }, + { + "id": "Location", + "type": "object", + "description": "Location in the source code.", + "properties": [ + { + "name": "scriptId", + "$ref": "ScriptId", + "description": "Script identifier as reported in the <code>Debugger.scriptParsed</code>." + }, + { "name": "lineNumber", "type": "integer", "description": "Line number in the script (0-based)." }, + { + "name": "columnNumber", + "type": "integer", + "optional": true, + "description": "Column number in the script (0-based)." + } + ] + }, + { + "id": "BreakpointAction", + "type": "object", + "description": "Action to perform when a breakpoint is triggered.", + "properties": [ + { + "name": "type", + "type": "string", + "enum": ["log", "evaluate", "sound", "probe"], + "description": "Different kinds of breakpoint actions." + }, + { + "name": "data", + "type": "string", + "optional": true, + "description": "Data associated with this breakpoint type (e.g. for type \"eval\" this is the JavaScript string to evaluate)." + }, + { + "name": "id", + "$ref": "BreakpointActionIdentifier", + "optional": true, + "description": "A frontend-assigned identifier for this breakpoint action." + }, + { + "name": "emulateUserGesture", + "type": "boolean", + "optional": true, + "description": "Indicates whether this action should be executed with a user gesture or not. Defaults to <code>false<code>." + } + ] + }, + { + "id": "BreakpointOptions", + "type": "object", + "description": "Extra options that modify breakpoint behavior.", + "properties": [ + { + "name": "condition", + "type": "string", + "optional": true, + "description": "Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true." + }, + { + "name": "actions", + "type": "array", + "optional": true, + "items": { "$ref": "BreakpointAction" }, + "description": "Actions to perform automatically when the breakpoint is triggered." + }, + { + "name": "autoContinue", + "type": "boolean", + "optional": true, + "description": "Automatically continue after hitting this breakpoint and running actions." + }, + { + "name": "ignoreCount", + "type": "integer", + "optional": true, + "description": "Number of times to ignore this breakpoint, before stopping on the breakpoint and running actions." + } + ] + }, + { + "id": "FunctionDetails", + "type": "object", + "description": "Information about the function.", + "properties": [ + { "name": "location", "$ref": "Location", "description": "Location of the function." }, + { + "name": "name", + "type": "string", + "optional": true, + "description": "Name of the function. Not present for anonymous functions." + }, + { + "name": "displayName", + "type": "string", + "optional": true, + "description": "Display name of the function(specified in 'displayName' property on the function object)." + }, + { + "name": "scopeChain", + "type": "array", + "optional": true, + "items": { "$ref": "Scope" }, + "description": "Scope chain for this closure." + } + ] + }, + { + "id": "CallFrame", + "type": "object", + "description": "JavaScript call frame. Array of call frames form the call stack.", + "properties": [ + { + "name": "callFrameId", + "$ref": "CallFrameId", + "description": "Call frame identifier. This identifier is only valid while the virtual machine is paused." + }, + { + "name": "functionName", + "type": "string", + "description": "Name of the JavaScript function called on this call frame." + }, + { "name": "location", "$ref": "Location", "description": "Location in the source code." }, + { + "name": "scopeChain", + "type": "array", + "items": { "$ref": "Scope" }, + "description": "Scope chain for this call frame." + }, + { + "name": "this", + "$ref": "Runtime.RemoteObject", + "description": "<code>this</code> object for this call frame." + }, + { + "name": "isTailDeleted", + "type": "boolean", + "description": "Is the current frame tail deleted from a tail call." + } + ] + }, + { + "id": "Scope", + "type": "object", + "description": "Scope description.", + "properties": [ + { + "name": "object", + "$ref": "Runtime.RemoteObject", + "description": "Object representing the scope. For <code>global</code> and <code>with</code> scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties." + }, + { + "name": "type", + "type": "string", + "enum": [ + "global", + "with", + "closure", + "catch", + "functionName", + "globalLexicalEnvironment", + "nestedLexical" + ], + "description": "Scope type." + }, + { "name": "name", "type": "string", "optional": true, "description": "Name associated with the scope." }, + { + "name": "location", + "$ref": "Location", + "optional": true, + "description": "Location if available of the scope definition." + }, + { + "name": "empty", + "type": "boolean", + "optional": true, + "description": "Whether the scope has any variables." + } + ] + }, + { + "id": "ProbeSample", + "description": "A sample collected by evaluating a probe breakpoint action.", + "type": "object", + "properties": [ + { + "name": "probeId", + "$ref": "BreakpointActionIdentifier", + "description": "Identifier of the probe breakpoint action that created the sample." + }, + { "name": "sampleId", "type": "integer", "description": "Unique identifier for this sample." }, + { + "name": "batchId", + "type": "integer", + "description": "A batch identifier which is the same for all samples taken at the same breakpoint hit." + }, + { "name": "timestamp", "type": "number", "description": "Timestamp of when the sample was taken." }, + { "name": "payload", "$ref": "Runtime.RemoteObject", "description": "Contents of the sample." } + ] + }, + { + "id": "AssertPauseReason", + "type": "object", + "description": "The pause reason auxiliary data when paused because of an assertion.", + "properties": [ + { + "name": "message", + "type": "string", + "optional": true, + "description": "The console.assert message string if provided." + } + ] + }, + { + "id": "BreakpointPauseReason", + "type": "object", + "description": "The pause reason auxiliary data when paused because of hitting a breakpoint.", + "properties": [ + { + "name": "breakpointId", + "type": "string", + "description": "The identifier of the breakpoint causing the pause." + } + ] + }, + { + "id": "CSPViolationPauseReason", + "type": "object", + "description": "The pause reason auxiliary data when paused because of a Content Security Policy directive.", + "properties": [ + { "name": "directive", "type": "string", "description": "The CSP directive that blocked script execution." } + ] + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received." + }, + { "name": "disable", "description": "Disables debugger for given page." }, + { + "name": "setAsyncStackTraceDepth", + "description": "Set the async stack trace depth for the page. A value of zero disables recording of async stack traces.", + "parameters": [{ "name": "depth", "type": "integer", "description": "Async stack trace depth." }] + }, + { + "name": "setBreakpointsActive", + "description": "Activates / deactivates all breakpoints on the page.", + "parameters": [ + { "name": "active", "type": "boolean", "description": "New value for breakpoints active state." } + ] + }, + { + "name": "setBreakpointByUrl", + "description": "Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in <code>locations</code> property. Further matching script parsing will result in subsequent <code>breakpointResolved</code> events issued. This logical breakpoint will survive page reloads.", + "parameters": [ + { "name": "lineNumber", "type": "integer", "description": "Line number to set breakpoint at." }, + { + "name": "url", + "type": "string", + "optional": true, + "description": "URL of the resources to set breakpoint on." + }, + { + "name": "urlRegex", + "type": "string", + "optional": true, + "description": "Regex pattern for the URLs of the resources to set breakpoints on. Either <code>url</code> or <code>urlRegex</code> must be specified." + }, + { + "name": "columnNumber", + "type": "integer", + "optional": true, + "description": "Offset in the line to set breakpoint at." + }, + { + "name": "options", + "$ref": "BreakpointOptions", + "optional": true, + "description": "Options to apply to this breakpoint to modify its behavior." + } + ], + "returns": [ + { + "name": "breakpointId", + "$ref": "BreakpointId", + "description": "Id of the created breakpoint for further reference." + }, + { + "name": "locations", + "type": "array", + "items": { "$ref": "Location" }, + "description": "List of the locations this breakpoint resolved into upon addition." + } + ] + }, + { + "name": "setBreakpoint", + "description": "Sets JavaScript breakpoint at a given location.", + "parameters": [ + { "name": "location", "$ref": "Location", "description": "Location to set breakpoint in." }, + { + "name": "options", + "$ref": "BreakpointOptions", + "optional": true, + "description": "Options to apply to this breakpoint to modify its behavior." + } + ], + "returns": [ + { + "name": "breakpointId", + "$ref": "BreakpointId", + "description": "Id of the created breakpoint for further reference." + }, + { "name": "actualLocation", "$ref": "Location", "description": "Location this breakpoint resolved into." } + ] + }, + { + "name": "removeBreakpoint", + "description": "Removes JavaScript breakpoint.", + "parameters": [{ "name": "breakpointId", "$ref": "BreakpointId" }] + }, + { + "name": "addSymbolicBreakpoint", + "description": "Adds a JavaScript breakpoint that pauses execution whenever a function with the given name is about to be called.", + "parameters": [ + { "name": "symbol", "type": "string", "description": "The name of the function to pause in when called." }, + { + "name": "caseSensitive", + "type": "boolean", + "optional": true, + "description": "If true, symbol is case sensitive. Defaults to true." + }, + { + "name": "isRegex", + "type": "boolean", + "optional": true, + "description": "If true, treats symbol as a regex. Defaults to false." + }, + { + "name": "options", + "$ref": "BreakpointOptions", + "optional": true, + "description": "Options to apply to this breakpoint to modify its behavior." + } + ] + }, + { + "name": "removeSymbolicBreakpoint", + "description": "Removes a previously added symbolic breakpoint.", + "parameters": [ + { "name": "symbol", "type": "string", "description": "The name of the function to pause in when called." }, + { + "name": "caseSensitive", + "type": "boolean", + "optional": true, + "description": "If true, symbol is case sensitive. Defaults to true." + }, + { + "name": "isRegex", + "type": "boolean", + "optional": true, + "description": "If true, treats symbol as a regex. Defaults to false." + } + ] + }, + { + "name": "continueUntilNextRunLoop", + "description": "Continues execution until the current evaluation completes. This will trigger either a Debugger.paused or Debugger.resumed event." + }, + { + "name": "continueToLocation", + "description": "Continues execution until specific location is reached. This will trigger either a Debugger.paused or Debugger.resumed event.", + "parameters": [{ "name": "location", "$ref": "Location", "description": "Location to continue to." }] + }, + { + "name": "stepNext", + "description": "Steps over the expression. This will trigger either a Debugger.paused or Debugger.resumed event." + }, + { + "name": "stepOver", + "description": "Steps over the statement. This will trigger either a Debugger.paused or Debugger.resumed event." + }, + { + "name": "stepInto", + "description": "Steps into the function call. This will trigger either a Debugger.paused or Debugger.resumed event." + }, + { + "name": "stepOut", + "description": "Steps out of the function call. This will trigger either a Debugger.paused or Debugger.resumed event." + }, + { "name": "pause", "description": "Stops on the next JavaScript statement." }, + { + "name": "resume", + "description": "Resumes JavaScript execution. This will trigger a Debugger.resumed event." + }, + { + "name": "searchInContent", + "description": "Searches for given string in script content.", + "parameters": [ + { "name": "scriptId", "$ref": "ScriptId", "description": "Id of the script to search in." }, + { "name": "query", "type": "string", "description": "String to search for." }, + { + "name": "caseSensitive", + "type": "boolean", + "optional": true, + "description": "If true, search is case sensitive." + }, + { + "name": "isRegex", + "type": "boolean", + "optional": true, + "description": "If true, treats string parameter as regex." + } + ], + "returns": [ + { + "name": "result", + "type": "array", + "items": { "$ref": "GenericTypes.SearchMatch" }, + "description": "List of search matches." + } + ] + }, + { + "name": "getScriptSource", + "description": "Returns source for the script with given id.", + "parameters": [ + { "name": "scriptId", "$ref": "ScriptId", "description": "Id of the script to get source for." } + ], + "returns": [{ "name": "scriptSource", "type": "string", "description": "Script source." }] + }, + { + "name": "getFunctionDetails", + "description": "Returns detailed information on given function.", + "parameters": [ + { + "name": "functionId", + "$ref": "Runtime.RemoteObjectId", + "description": "Id of the function to get location for." + } + ], + "returns": [ + { "name": "details", "$ref": "FunctionDetails", "description": "Information about the function." } + ] + }, + { + "name": "getBreakpointLocations", + "description": "Returns a list of valid breakpoint locations within the given location range.", + "parameters": [ + { + "name": "start", + "$ref": "Location", + "description": "Starting location to look for breakpoint locations after (inclusive). Must have same scriptId as end." + }, + { + "name": "end", + "$ref": "Location", + "description": "Ending location to look for breakpoint locations before (exclusive). Must have same scriptId as start." + } + ], + "returns": [ + { + "name": "locations", + "type": "array", + "items": { "$ref": "Location" }, + "description": "List of resolved breakpoint locations." + } + ] + }, + { + "name": "setPauseOnDebuggerStatements", + "description": "Control whether the debugger pauses execution before `debugger` statements.", + "parameters": [ + { "name": "enabled", "type": "boolean" }, + { + "name": "options", + "$ref": "BreakpointOptions", + "optional": true, + "description": "Options to apply to this breakpoint to modify its behavior." + } + ] + }, + { + "name": "setPauseOnExceptions", + "description": "Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is <code>none</code>.", + "parameters": [ + { + "name": "state", + "type": "string", + "enum": ["none", "uncaught", "all"], + "description": "Pause on exceptions mode." + }, + { + "name": "options", + "$ref": "BreakpointOptions", + "optional": true, + "description": "Options to apply to this breakpoint to modify its behavior." + } + ] + }, + { + "name": "setPauseOnAssertions", + "description": "Set pause on assertions state. Assertions are console.assert assertions.", + "parameters": [ + { "name": "enabled", "type": "boolean" }, + { + "name": "options", + "$ref": "BreakpointOptions", + "optional": true, + "description": "Options to apply to this breakpoint to modify its behavior." + } + ] + }, + { + "name": "setPauseOnMicrotasks", + "description": "Pause when running the next JavaScript microtask.", + "parameters": [ + { "name": "enabled", "type": "boolean" }, + { + "name": "options", + "$ref": "BreakpointOptions", + "optional": true, + "description": "Options to apply to this breakpoint to modify its behavior." + } + ] + }, + { + "name": "setPauseForInternalScripts", + "description": "Change whether to pause in the debugger for internal scripts. The default value is false.", + "parameters": [{ "name": "shouldPause", "type": "boolean" }] + }, + { + "name": "evaluateOnCallFrame", + "description": "Evaluates expression on a given call frame.", + "parameters": [ + { "name": "callFrameId", "$ref": "CallFrameId", "description": "Call frame identifier to evaluate on." }, + { "name": "expression", "type": "string", "description": "Expression to evaluate." }, + { + "name": "objectGroup", + "type": "string", + "optional": true, + "description": "String object group name to put result into (allows rapid releasing resulting object handles using <code>releaseObjectGroup</code>)." + }, + { + "name": "includeCommandLineAPI", + "type": "boolean", + "optional": true, + "description": "Specifies whether command line API should be available to the evaluated expression, defaults to false." + }, + { + "name": "doNotPauseOnExceptionsAndMuteConsole", + "type": "boolean", + "optional": true, + "description": "Specifies whether evaluation should stop on exceptions and mute console. Overrides setPauseOnException state." + }, + { + "name": "returnByValue", + "type": "boolean", + "optional": true, + "description": "Whether the result is expected to be a JSON object that should be sent by value." + }, + { + "name": "generatePreview", + "type": "boolean", + "optional": true, + "description": "Whether preview should be generated for the result." + }, + { + "name": "saveResult", + "type": "boolean", + "optional": true, + "description": "Whether the resulting value should be considered for saving in the $n history." + }, + { + "name": "emulateUserGesture", + "type": "boolean", + "optional": true, + "description": "Whether the expression should be considered to be in a user gesture or not." + } + ], + "returns": [ + { + "name": "result", + "$ref": "Runtime.RemoteObject", + "description": "Object wrapper for the evaluation result." + }, + { + "name": "wasThrown", + "type": "boolean", + "optional": true, + "description": "True if the result was thrown during the evaluation." + }, + { + "name": "savedResultIndex", + "type": "integer", + "optional": true, + "description": "If the result was saved, this is the $n index that can be used to access the value." + } + ] + }, + { + "name": "setShouldBlackboxURL", + "description": "Sets whether the given URL should be in the list of blackboxed scripts, which are ignored when pausing/stepping/debugging.", + "parameters": [ + { "name": "url", "type": "string" }, + { "name": "shouldBlackbox", "type": "boolean" }, + { + "name": "caseSensitive", + "type": "boolean", + "optional": true, + "description": "If true, <code>url</code> is case sensitive." + }, + { + "name": "isRegex", + "type": "boolean", + "optional": true, + "description": "If true, treat <code>url</code> as regular expression." + } + ] + }, + { + "name": "setBlackboxBreakpointEvaluations", + "description": "Sets whether evaluation of breakpoint conditions, ignore counts, and actions happen at the location of the breakpoint or are deferred due to blackboxing.", + "parameters": [{ "name": "blackboxBreakpointEvaluations", "type": "boolean" }] + } + ], + "events": [ + { + "name": "globalObjectCleared", + "description": "Called when global has been cleared and debugger client should reset its state. Happens upon navigation or reload." + }, + { + "name": "scriptParsed", + "description": "Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger.", + "parameters": [ + { "name": "scriptId", "$ref": "ScriptId", "description": "Identifier of the script parsed." }, + { "name": "url", "type": "string", "description": "URL of the script parsed (if any)." }, + { + "name": "startLine", + "type": "integer", + "description": "Line offset of the script within the resource with given URL (for script tags)." + }, + { + "name": "startColumn", + "type": "integer", + "description": "Column offset of the script within the resource with given URL." + }, + { "name": "endLine", "type": "integer", "description": "Last line of the script." }, + { "name": "endColumn", "type": "integer", "description": "Length of the last line of the script." }, + { + "name": "isContentScript", + "type": "boolean", + "optional": true, + "description": "Determines whether this script is a user extension script." + }, + { + "name": "sourceURL", + "type": "string", + "optional": true, + "description": "sourceURL name of the script (if any)." + }, + { + "name": "sourceMapURL", + "type": "string", + "optional": true, + "description": "URL of source map associated with script (if any)." + }, + { + "name": "module", + "type": "boolean", + "optional": true, + "description": "True if this script was parsed as a module." + } + ] + }, + { + "name": "scriptFailedToParse", + "description": "Fired when virtual machine fails to parse the script.", + "parameters": [ + { "name": "url", "type": "string", "description": "URL of the script that failed to parse." }, + { + "name": "scriptSource", + "type": "string", + "description": "Source text of the script that failed to parse." + }, + { "name": "startLine", "type": "integer", "description": "Line offset of the script within the resource." }, + { "name": "errorLine", "type": "integer", "description": "Line with error." }, + { "name": "errorMessage", "type": "string", "description": "Parse error message." } + ] + }, + { + "name": "breakpointResolved", + "description": "Fired when breakpoint is resolved to an actual script and location.", + "parameters": [ + { "name": "breakpointId", "$ref": "BreakpointId", "description": "Breakpoint unique identifier." }, + { "name": "location", "$ref": "Location", "description": "Actual breakpoint location." } + ] + }, + { + "name": "paused", + "description": "Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria.", + "parameters": [ + { + "name": "callFrames", + "type": "array", + "items": { "$ref": "CallFrame" }, + "description": "Call stack the virtual machine stopped on." + }, + { + "name": "reason", + "type": "string", + "enum": [ + "URL", + "DOM", + "AnimationFrame", + "Interval", + "Listener", + "Timeout", + "exception", + "assert", + "CSPViolation", + "DebuggerStatement", + "Breakpoint", + "PauseOnNextStatement", + "Microtask", + "FunctionCall", + "BlackboxedScript", + "other" + ], + "description": "Pause reason." + }, + { + "name": "data", + "type": "object", + "optional": true, + "description": "Object containing break-specific auxiliary properties." + }, + { + "name": "asyncStackTrace", + "$ref": "Console.StackTrace", + "optional": true, + "description": "Linked list of asynchronous StackTraces." + } + ] + }, + { "name": "resumed", "description": "Fired when the virtual machine resumed execution." }, + { + "name": "didSampleProbe", + "description": "Fires when a new probe sample is collected.", + "parameters": [{ "name": "sample", "$ref": "ProbeSample", "description": "A collected probe sample." }] + }, + { + "name": "playBreakpointActionSound", + "description": "Fired when a \"sound\" breakpoint action is triggered on a breakpoint.", + "parameters": [ + { + "name": "breakpointActionId", + "$ref": "BreakpointActionIdentifier", + "description": "Breakpoint action identifier." + } + ] + } + ] + }, + { + "domain": "GenericTypes", + "description": "Exposes generic types to be used by any domain.", + "types": [ + { + "id": "SearchMatch", + "type": "object", + "description": "Search match in a resource.", + "properties": [ + { "name": "lineNumber", "type": "number", "description": "Line number in resource content." }, + { "name": "lineContent", "type": "string", "description": "Line with match content." } + ] + } + ] + }, + { + "domain": "Heap", + "description": "Heap domain exposes JavaScript heap attributes and capabilities.", + "debuggableTypes": ["itml", "javascript", "page", "service-worker", "web-page"], + "targetTypes": ["itml", "javascript", "page", "service-worker", "worker"], + "types": [ + { + "id": "GarbageCollection", + "description": "Information about a garbage collection.", + "type": "object", + "properties": [ + { + "name": "type", + "type": "string", + "enum": ["full", "partial"], + "description": "The type of garbage collection." + }, + { "name": "startTime", "type": "number" }, + { "name": "endTime", "type": "number" } + ] + }, + { "id": "HeapSnapshotData", "description": "JavaScriptCore HeapSnapshot JSON data.", "type": "string" } + ], + "commands": [ + { "name": "enable", "description": "Enables Heap domain events." }, + { "name": "disable", "description": "Disables Heap domain events." }, + { "name": "gc", "description": "Trigger a full garbage collection." }, + { + "name": "snapshot", + "description": "Take a heap snapshot.", + "returns": [ + { "name": "timestamp", "type": "number" }, + { "name": "snapshotData", "$ref": "HeapSnapshotData" } + ] + }, + { + "name": "startTracking", + "description": "Start tracking heap changes. This will produce a `trackingStart` event." + }, + { + "name": "stopTracking", + "description": "Stop tracking heap changes. This will produce a `trackingComplete` event." + }, + { + "name": "getPreview", + "description": "Returns a preview (string, Debugger.FunctionDetails, or Runtime.ObjectPreview) for a Heap.HeapObjectId.", + "parameters": [ + { + "name": "heapObjectId", + "type": "integer", + "description": "Identifier of the heap object within the snapshot." + } + ], + "returns": [ + { "name": "string", "type": "string", "optional": true, "description": "String value." }, + { + "name": "functionDetails", + "$ref": "Debugger.FunctionDetails", + "optional": true, + "description": "Function details." + }, + { "name": "preview", "$ref": "Runtime.ObjectPreview", "optional": true, "description": "Object preview." } + ] + }, + { + "name": "getRemoteObject", + "description": "Returns the strongly referenced Runtime.RemoteObject for a Heap.HeapObjectId.", + "parameters": [ + { + "name": "heapObjectId", + "type": "integer", + "description": "Identifier of the heap object within the snapshot." + }, + { + "name": "objectGroup", + "type": "string", + "optional": true, + "description": "Symbolic group name that can be used to release multiple objects." + } + ], + "returns": [{ "name": "result", "$ref": "Runtime.RemoteObject", "description": "Resulting object." }] + } + ], + "events": [ + { + "name": "garbageCollected", + "description": "Information about the garbage collection.", + "parameters": [{ "name": "collection", "$ref": "GarbageCollection" }] + }, + { + "name": "trackingStart", + "description": "Tracking started.", + "parameters": [ + { "name": "timestamp", "type": "number" }, + { "name": "snapshotData", "$ref": "HeapSnapshotData", "description": "Snapshot at the start of tracking." } + ] + }, + { + "name": "trackingComplete", + "description": "Tracking stopped.", + "parameters": [ + { "name": "timestamp", "type": "number" }, + { "name": "snapshotData", "$ref": "HeapSnapshotData", "description": "Snapshot at the end of tracking." } + ] + } + ] + }, + { + "domain": "Inspector", + "debuggableTypes": ["itml", "javascript", "page", "web-page"], + "targetTypes": ["itml", "javascript", "page"], + "commands": [ + { "name": "enable", "description": "Enables inspector domain notifications." }, + { "name": "disable", "description": "Disables inspector domain notifications." }, + { + "name": "initialized", + "description": "Sent by the frontend after all initialization messages have been sent." + } + ], + "events": [ + { "name": "evaluateForTestInFrontend", "parameters": [{ "name": "script", "type": "string" }] }, + { + "name": "inspect", + "parameters": [ + { "name": "object", "$ref": "Runtime.RemoteObject" }, + { "name": "hints", "type": "object" } + ] + } + ] + }, + { + "domain": "Network", + "description": "Network domain allows tracking network activities of the page. It exposes information about http, file, data and other requests and responses, their headers, bodies, timing, etc.", + "debuggableTypes": ["itml", "page", "service-worker", "web-page"], + "targetTypes": ["itml", "page", "service-worker"], + "types": [ + { "id": "LoaderId", "type": "string", "description": "Unique loader identifier." }, + { "id": "FrameId", "type": "string", "description": "Unique frame identifier." }, + { "id": "RequestId", "type": "string", "description": "Unique request identifier." }, + { "id": "Timestamp", "type": "number", "description": "Elapsed seconds since frontend connected." }, + { "id": "Walltime", "type": "number", "description": "Number of seconds since epoch." }, + { + "id": "ReferrerPolicy", + "type": "string", + "description": "Controls how much referrer information is sent with the request", + "enum": [ + "empty-string", + "no-referrer", + "no-referrer-when-downgrade", + "same-origin", + "origin", + "strict-origin", + "origin-when-cross-origin", + "strict-origin-when-cross-origin", + "unsafe-url" + ] + }, + { + "id": "Headers", + "type": "object", + "description": "Request / response headers as keys / values of JSON object." + }, + { + "id": "ResourceTiming", + "type": "object", + "description": "Timing information for the request.", + "properties": [ + { "name": "startTime", "$ref": "Timestamp", "description": "Request is initiated" }, + { "name": "redirectStart", "$ref": "Timestamp", "description": "Started redirect resolution." }, + { "name": "redirectEnd", "$ref": "Timestamp", "description": "Finished redirect resolution." }, + { "name": "fetchStart", "$ref": "Timestamp", "description": "Resource fetching started." }, + { + "name": "domainLookupStart", + "type": "number", + "description": "Started DNS address resolve in milliseconds relative to fetchStart." + }, + { + "name": "domainLookupEnd", + "type": "number", + "description": "Finished DNS address resolve in milliseconds relative to fetchStart." + }, + { + "name": "connectStart", + "type": "number", + "description": "Started connecting to the remote host in milliseconds relative to fetchStart." + }, + { + "name": "connectEnd", + "type": "number", + "description": "Connected to the remote host in milliseconds relative to fetchStart." + }, + { + "name": "secureConnectionStart", + "type": "number", + "description": "Started SSL handshake in milliseconds relative to fetchStart." + }, + { + "name": "requestStart", + "type": "number", + "description": "Started sending request in milliseconds relative to fetchStart." + }, + { + "name": "responseStart", + "type": "number", + "description": "Started receiving response headers in milliseconds relative to fetchStart." + }, + { + "name": "responseEnd", + "type": "number", + "description": "Finished receiving response headers in milliseconds relative to fetchStart." + } + ] + }, + { + "id": "Request", + "type": "object", + "description": "HTTP request data.", + "properties": [ + { "name": "url", "type": "string", "description": "Request URL." }, + { "name": "method", "type": "string", "description": "HTTP request method." }, + { "name": "headers", "$ref": "Headers", "description": "HTTP request headers." }, + { "name": "postData", "type": "string", "optional": true, "description": "HTTP POST request data." }, + { + "name": "referrerPolicy", + "$ref": "ReferrerPolicy", + "optional": true, + "description": "The level of included referrer information." + }, + { + "name": "integrity", + "type": "string", + "optional": true, + "description": "The base64 cryptographic hash of the resource." + } + ] + }, + { + "id": "Response", + "type": "object", + "description": "HTTP response data.", + "properties": [ + { + "name": "url", + "type": "string", + "description": "Response URL. This URL can be different from CachedResource.url in case of redirect." + }, + { "name": "status", "type": "integer", "description": "HTTP response status code." }, + { "name": "statusText", "type": "string", "description": "HTTP response status text." }, + { "name": "headers", "$ref": "Headers", "description": "HTTP response headers." }, + { "name": "mimeType", "type": "string", "description": "Resource mimeType as determined by the browser." }, + { + "name": "source", + "type": "string", + "enum": ["unknown", "network", "memory-cache", "disk-cache", "service-worker", "inspector-override"], + "description": "Specifies where the response came from." + }, + { + "name": "requestHeaders", + "$ref": "Headers", + "optional": true, + "description": "Refined HTTP request headers that were actually transmitted over the network." + }, + { + "name": "timing", + "$ref": "ResourceTiming", + "optional": true, + "description": "Timing information for the given request." + }, + { + "name": "security", + "$ref": "Security.Security", + "optional": true, + "description": "The security information for the given request." + } + ] + }, + { + "id": "Metrics", + "type": "object", + "description": "Network load metrics.", + "properties": [ + { + "name": "protocol", + "type": "string", + "optional": true, + "description": "Network protocol. ALPN Protocol ID Identification Sequence, as per RFC 7301 (for example, http/2, http/1.1, spdy/3.1)" + }, + { + "name": "priority", + "type": "string", + "enum": ["low", "medium", "high"], + "optional": true, + "description": "Network priority." + }, + { + "name": "connectionIdentifier", + "type": "string", + "optional": true, + "description": "Connection identifier." + }, + { "name": "remoteAddress", "type": "string", "optional": true, "description": "Remote IP address." }, + { + "name": "requestHeaders", + "$ref": "Headers", + "optional": true, + "description": "Refined HTTP request headers that were actually transmitted over the network." + }, + { + "name": "requestHeaderBytesSent", + "type": "number", + "optional": true, + "description": "Total HTTP request header bytes sent over the network." + }, + { + "name": "requestBodyBytesSent", + "type": "number", + "optional": true, + "description": "Total HTTP request body bytes sent over the network." + }, + { + "name": "responseHeaderBytesReceived", + "type": "number", + "optional": true, + "description": "Total HTTP response header bytes received over the network." + }, + { + "name": "responseBodyBytesReceived", + "type": "number", + "optional": true, + "description": "Total HTTP response body bytes received over the network." + }, + { + "name": "responseBodyDecodedSize", + "type": "number", + "optional": true, + "description": "Total decoded response body size in bytes." + }, + { + "name": "securityConnection", + "$ref": "Security.Connection", + "optional": true, + "description": "Connection information for the completed request." + }, + { + "name": "isProxyConnection", + "type": "boolean", + "optional": true, + "description": "Whether or not the connection was proxied through a server. If <code>true</code>, the <code>remoteAddress</code> will be for the proxy server, not the server that provided the resource to the proxy server." + } + ] + }, + { + "id": "WebSocketRequest", + "type": "object", + "description": "WebSocket request data.", + "properties": [{ "name": "headers", "$ref": "Headers", "description": "HTTP response headers." }] + }, + { + "id": "WebSocketResponse", + "type": "object", + "description": "WebSocket response data.", + "properties": [ + { "name": "status", "type": "integer", "description": "HTTP response status code." }, + { "name": "statusText", "type": "string", "description": "HTTP response status text." }, + { "name": "headers", "$ref": "Headers", "description": "HTTP response headers." } + ] + }, + { + "id": "WebSocketFrame", + "type": "object", + "description": "WebSocket frame data.", + "properties": [ + { "name": "opcode", "type": "number", "description": "WebSocket frame opcode." }, + { "name": "mask", "type": "boolean", "description": "WebSocket frame mask." }, + { + "name": "payloadData", + "type": "string", + "description": "WebSocket frame payload data, binary frames (opcode = 2) are base64-encoded." + }, + { "name": "payloadLength", "type": "number", "description": "WebSocket frame payload length in bytes." } + ] + }, + { + "id": "CachedResource", + "type": "object", + "description": "Information about the cached resource.", + "properties": [ + { + "name": "url", + "type": "string", + "description": "Resource URL. This is the url of the original network request." + }, + { "name": "type", "$ref": "Page.ResourceType", "description": "Type of this resource." }, + { "name": "response", "$ref": "Response", "optional": true, "description": "Cached response data." }, + { "name": "bodySize", "type": "number", "description": "Cached response body size." }, + { + "name": "sourceMapURL", + "type": "string", + "optional": true, + "description": "URL of source map associated with this resource (if any)." + } + ] + }, + { + "id": "Initiator", + "type": "object", + "description": "Information about the request initiator.", + "properties": [ + { + "name": "type", + "type": "string", + "enum": ["parser", "script", "other"], + "description": "Type of this initiator." + }, + { + "name": "stackTrace", + "$ref": "Console.StackTrace", + "optional": true, + "description": "Initiator JavaScript stack trace, set for Script only." + }, + { + "name": "url", + "type": "string", + "optional": true, + "description": "Initiator URL, set for Parser type only." + }, + { + "name": "lineNumber", + "type": "number", + "optional": true, + "description": "Initiator line number, set for Parser type only." + }, + { + "name": "nodeId", + "$ref": "DOM.NodeId", + "optional": true, + "description": "Set if the load was triggered by a DOM node, in addition to the other initiator information." + } + ] + }, + { + "id": "NetworkStage", + "type": "string", + "description": "Different stages of a network request.", + "enum": ["request", "response"] + }, + { + "id": "ResourceErrorType", + "type": "string", + "description": "Different stages of a network request.", + "enum": ["General", "AccessControl", "Cancellation", "Timeout"] + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables network tracking, network events will now be delivered to the client." + }, + { + "name": "disable", + "description": "Disables network tracking, prevents network events from being sent to the client." + }, + { + "name": "setExtraHTTPHeaders", + "description": "Specifies whether to always send extra HTTP headers with the requests from this page.", + "targetTypes": ["page"], + "parameters": [{ "name": "headers", "$ref": "Headers", "description": "Map with extra HTTP headers." }] + }, + { + "name": "getResponseBody", + "description": "Returns content served for the given request.", + "parameters": [ + { + "name": "requestId", + "$ref": "RequestId", + "description": "Identifier of the network request to get content for." + } + ], + "returns": [ + { "name": "body", "type": "string", "description": "Response body." }, + { "name": "base64Encoded", "type": "boolean", "description": "True, if content was sent as base64." } + ] + }, + { + "name": "setResourceCachingDisabled", + "description": "Toggles whether the resource cache may be used when loading resources in the inspected page. If <code>true</code>, the resource cache will not be used when loading resources.", + "parameters": [ + { "name": "disabled", "type": "boolean", "description": "Whether to prevent usage of the resource cache." } + ] + }, + { + "name": "loadResource", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks.", + "targetTypes": ["page"], + "async": true, + "parameters": [ + { "name": "frameId", "$ref": "FrameId", "description": "Frame to load the resource from." }, + { "name": "url", "type": "string", "description": "URL of the resource to load." } + ], + "returns": [ + { "name": "content", "type": "string", "description": "Resource content." }, + { "name": "mimeType", "type": "string", "description": "Resource mimeType." }, + { "name": "status", "type": "integer", "description": "HTTP response status code." } + ] + }, + { + "name": "getSerializedCertificate", + "description": "Fetches a serialized secure certificate for the given requestId to be displayed via InspectorFrontendHost.showCertificate.", + "targetTypes": ["page"], + "parameters": [{ "name": "requestId", "$ref": "RequestId" }], + "returns": [ + { + "name": "serializedCertificate", + "type": "string", + "description": "Represents a base64 encoded WebCore::CertificateInfo object." + } + ] + }, + { + "name": "resolveWebSocket", + "description": "Resolves JavaScript WebSocket object for given request id.", + "targetTypes": ["page"], + "parameters": [ + { + "name": "requestId", + "$ref": "RequestId", + "description": "Identifier of the WebSocket resource to resolve." + }, + { + "name": "objectGroup", + "type": "string", + "optional": true, + "description": "Symbolic group name that can be used to release multiple objects." + } + ], + "returns": [ + { + "name": "object", + "$ref": "Runtime.RemoteObject", + "description": "JavaScript object wrapper for given node." + } + ] + }, + { + "name": "setInterceptionEnabled", + "description": "Enable interception of network requests.", + "targetTypes": ["page"], + "parameters": [{ "name": "enabled", "type": "boolean" }] + }, + { + "name": "addInterception", + "description": "Add an interception.", + "targetTypes": ["page"], + "parameters": [ + { + "name": "url", + "type": "string", + "description": "URL pattern to intercept, intercept everything if not specified or empty" + }, + { "name": "stage", "$ref": "NetworkStage", "description": "Stage to intercept." }, + { + "name": "caseSensitive", + "type": "boolean", + "optional": true, + "description": "If false, ignores letter casing of `url` parameter." + }, + { + "name": "isRegex", + "type": "boolean", + "optional": true, + "description": "If true, treats `url` parameter as a regular expression." + } + ] + }, + { + "name": "removeInterception", + "description": "Remove an interception.", + "targetTypes": ["page"], + "parameters": [ + { "name": "url", "type": "string" }, + { "name": "stage", "$ref": "NetworkStage", "description": "Stage to intercept." }, + { + "name": "caseSensitive", + "type": "boolean", + "optional": true, + "description": "If false, ignores letter casing of `url` parameter." + }, + { + "name": "isRegex", + "type": "boolean", + "optional": true, + "description": "If true, treats `url` parameter as a regular expression." + } + ] + }, + { + "name": "interceptContinue", + "description": "Continue request or response without modifications.", + "targetTypes": ["page"], + "parameters": [ + { + "name": "requestId", + "$ref": "RequestId", + "description": "Identifier for the intercepted Network request or response to continue." + }, + { "name": "stage", "$ref": "NetworkStage", "description": "Stage to continue." } + ] + }, + { + "name": "interceptWithRequest", + "description": "Replace intercepted request with the provided one.", + "targetTypes": ["page"], + "parameters": [ + { + "name": "requestId", + "$ref": "RequestId", + "description": "Identifier for the intercepted Network request or response to continue." + }, + { "name": "url", "type": "string", "optional": true, "description": "HTTP request url." }, + { "name": "method", "type": "string", "optional": true, "description": "HTTP request method." }, + { + "name": "headers", + "$ref": "Headers", + "optional": true, + "description": "HTTP response headers. Pass through original values if unmodified." + }, + { + "name": "postData", + "type": "string", + "optional": true, + "description": "HTTP POST request data, base64-encoded." + } + ] + }, + { + "name": "interceptWithResponse", + "description": "Provide response content for an intercepted response.", + "targetTypes": ["page"], + "parameters": [ + { + "name": "requestId", + "$ref": "RequestId", + "description": "Identifier for the intercepted Network response to modify." + }, + { "name": "content", "type": "string" }, + { "name": "base64Encoded", "type": "boolean", "description": "True, if content was sent as base64." }, + { "name": "mimeType", "type": "string", "optional": true, "description": "MIME Type for the data." }, + { + "name": "status", + "type": "integer", + "optional": true, + "description": "HTTP response status code. Pass through original values if unmodified." + }, + { + "name": "statusText", + "type": "string", + "optional": true, + "description": "HTTP response status text. Pass through original values if unmodified." + }, + { + "name": "headers", + "$ref": "Headers", + "optional": true, + "description": "HTTP response headers. Pass through original values if unmodified." + } + ] + }, + { + "name": "interceptRequestWithResponse", + "description": "Provide response for an intercepted request. Request completely bypasses the network in this case and is immediately fulfilled with the provided data.", + "targetTypes": ["page"], + "parameters": [ + { + "name": "requestId", + "$ref": "RequestId", + "description": "Identifier for the intercepted Network response to modify." + }, + { "name": "content", "type": "string" }, + { "name": "base64Encoded", "type": "boolean", "description": "True, if content was sent as base64." }, + { "name": "mimeType", "type": "string", "description": "MIME Type for the data." }, + { "name": "status", "type": "integer", "description": "HTTP response status code." }, + { "name": "statusText", "type": "string", "description": "HTTP response status text." }, + { "name": "headers", "$ref": "Headers", "description": "HTTP response headers." } + ] + }, + { + "name": "interceptRequestWithError", + "description": "Fail request with given error type.", + "targetTypes": ["page"], + "parameters": [ + { + "name": "requestId", + "$ref": "RequestId", + "description": "Identifier for the intercepted Network request to fail." + }, + { + "name": "errorType", + "$ref": "ResourceErrorType", + "description": "Deliver error reason for the request failure." + } + ] + }, + { + "name": "setEmulatedConditions", + "description": "Emulate various network conditions (e.g. bytes per second, latency, etc.).", + "targetTypes": ["page"], + "condition": "defined(ENABLE_INSPECTOR_NETWORK_THROTTLING) && ENABLE_INSPECTOR_NETWORK_THROTTLING", + "parameters": [ + { + "name": "bytesPerSecondLimit", + "type": "integer", + "optional": true, + "description": "Limits the bytes per second of requests if positive. Removes any limits if zero or not provided." + } + ] + } + ], + "events": [ + { + "name": "requestWillBeSent", + "description": "Fired when page is about to send HTTP request.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "frameId", "$ref": "FrameId", "description": "Frame identifier." }, + { "name": "loaderId", "$ref": "LoaderId", "description": "Loader identifier." }, + { + "name": "documentURL", + "type": "string", + "description": "URL of the document this request is loaded for." + }, + { "name": "request", "$ref": "Request", "description": "Request data." }, + { "name": "timestamp", "$ref": "Timestamp" }, + { "name": "walltime", "$ref": "Walltime" }, + { "name": "initiator", "$ref": "Initiator", "description": "Request initiator." }, + { + "name": "redirectResponse", + "optional": true, + "$ref": "Response", + "description": "Redirect response data." + }, + { "name": "type", "$ref": "Page.ResourceType", "optional": true, "description": "Resource type." }, + { + "name": "targetId", + "type": "string", + "optional": true, + "description": "Identifier for the context of where the load originated. In general this is the target identifier. For Workers this will be the workerId." + } + ] + }, + { + "name": "responseReceived", + "description": "Fired when HTTP response is available.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "frameId", "$ref": "FrameId", "description": "Frame identifier." }, + { "name": "loaderId", "$ref": "LoaderId", "description": "Loader identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "type", "$ref": "Page.ResourceType", "description": "Resource type." }, + { "name": "response", "$ref": "Response", "description": "Response data." } + ] + }, + { + "name": "dataReceived", + "description": "Fired when data chunk was received over the network.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "dataLength", "type": "integer", "description": "Data chunk length." }, + { + "name": "encodedDataLength", + "type": "integer", + "description": "Actual bytes received (might be less than dataLength for compressed encodings)." + } + ] + }, + { + "name": "loadingFinished", + "description": "Fired when HTTP request has finished loading.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { + "name": "sourceMapURL", + "type": "string", + "optional": true, + "description": "URL of source map associated with this resource (if any)." + }, + { "name": "metrics", "$ref": "Metrics", "optional": true, "description": "Network metrics." } + ] + }, + { + "name": "loadingFailed", + "description": "Fired when HTTP request has failed to load.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "errorText", "type": "string", "description": "User friendly error message." }, + { "name": "canceled", "type": "boolean", "optional": true, "description": "True if loading was canceled." } + ] + }, + { + "name": "requestServedFromMemoryCache", + "description": "Fired when HTTP request has been served from memory cache.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "frameId", "$ref": "FrameId", "description": "Frame identifier." }, + { "name": "loaderId", "$ref": "LoaderId", "description": "Loader identifier." }, + { + "name": "documentURL", + "type": "string", + "description": "URL of the document this request is loaded for." + }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "initiator", "$ref": "Initiator", "description": "Request initiator." }, + { "name": "resource", "$ref": "CachedResource", "description": "Cached resource data." } + ] + }, + { + "name": "requestIntercepted", + "description": "Fired when HTTP request has been intercepted. The frontend must respond with <code>Network.interceptContinue</code>, <code>Network.interceptWithRequest</code>` or <code>Network.interceptWithResponse</code>` to resolve this request.", + "targetTypes": ["page"], + "parameters": [ + { + "name": "requestId", + "$ref": "RequestId", + "description": "Identifier for this intercepted network. Corresponds with an earlier <code>Network.requestWillBeSent</code>." + }, + { + "name": "request", + "$ref": "Request", + "description": "Original request content that would proceed if this is continued." + } + ] + }, + { + "name": "responseIntercepted", + "description": "Fired when HTTP response has been intercepted. The frontend must response with <code>Network.interceptContinue</code> or <code>Network.interceptWithResponse</code>` to continue this response.", + "targetTypes": ["page"], + "parameters": [ + { + "name": "requestId", + "$ref": "RequestId", + "description": "Identifier for this intercepted network. Corresponds with an earlier <code>Network.requestWillBeSent</code>." + }, + { + "name": "response", + "$ref": "Response", + "description": "Original response content that would proceed if this is continued." + } + ] + }, + { + "name": "webSocketWillSendHandshakeRequest", + "description": "Fired when WebSocket is about to initiate handshake.", + "targetTypes": ["page"], + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp" }, + { "name": "walltime", "$ref": "Walltime" }, + { "name": "request", "$ref": "WebSocketRequest", "description": "WebSocket request data." } + ] + }, + { + "name": "webSocketHandshakeResponseReceived", + "description": "Fired when WebSocket handshake response becomes available.", + "targetTypes": ["page"], + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp" }, + { "name": "response", "$ref": "WebSocketResponse", "description": "WebSocket response data." } + ] + }, + { + "name": "webSocketCreated", + "description": "Fired upon WebSocket creation.", + "targetTypes": ["page"], + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "url", "type": "string", "description": "WebSocket request URL." } + ] + }, + { + "name": "webSocketClosed", + "description": "Fired when WebSocket is closed.", + "targetTypes": ["page"], + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." } + ] + }, + { + "name": "webSocketFrameReceived", + "description": "Fired when WebSocket frame is received.", + "targetTypes": ["page"], + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "response", "$ref": "WebSocketFrame", "description": "WebSocket response data." } + ] + }, + { + "name": "webSocketFrameError", + "description": "Fired when WebSocket frame error occurs.", + "targetTypes": ["page"], + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "errorMessage", "type": "string", "description": "WebSocket frame error message." } + ] + }, + { + "name": "webSocketFrameSent", + "description": "Fired when WebSocket frame is sent.", + "targetTypes": ["page"], + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "response", "$ref": "WebSocketFrame", "description": "WebSocket response data." } + ] + } + ] + }, + { + "domain": "Runtime", + "description": "Runtime domain exposes JavaScript runtime by means of remote evaluation and mirror objects. Evaluation results are returned as mirror object that expose object type, string representation and unique identifier that can be used for further object reference. Original objects are maintained in memory unless they are either explicitly released or are released along with the other objects in their object group.", + "debuggableTypes": ["itml", "javascript", "page", "service-worker", "web-page"], + "targetTypes": ["itml", "javascript", "page", "service-worker", "worker"], + "types": [ + { "id": "RemoteObjectId", "type": "string", "description": "Unique object identifier." }, + { + "id": "RemoteObject", + "type": "object", + "description": "Mirror object referencing original JavaScript object.", + "properties": [ + { + "name": "type", + "type": "string", + "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol", "bigint"], + "description": "Object type." + }, + { + "name": "subtype", + "type": "string", + "optional": true, + "enum": [ + "array", + "null", + "node", + "regexp", + "date", + "error", + "map", + "set", + "weakmap", + "weakset", + "iterator", + "class", + "proxy", + "weakref" + ], + "description": "Object subtype hint. Specified for <code>object</code> <code>function</code> (for class) type values only." + }, + { + "name": "className", + "type": "string", + "optional": true, + "description": "Object class (constructor) name. Specified for <code>object</code> type values only." + }, + { + "name": "value", + "type": "any", + "optional": true, + "description": "Remote object value (in case of primitive values or JSON values if it was requested)." + }, + { + "name": "description", + "type": "string", + "optional": true, + "description": "String representation of the object." + }, + { + "name": "objectId", + "$ref": "RemoteObjectId", + "optional": true, + "description": "Unique object identifier (for non-primitive values)." + }, + { + "name": "size", + "type": "integer", + "optional": true, + "description": "Size of the array/collection. Specified for array/map/set/weakmap/weakset object type values only." + }, + { + "name": "classPrototype", + "$ref": "RemoteObject", + "optional": true, + "description": "Remote object for the class prototype. Specified for class object type values only." + }, + { + "name": "preview", + "$ref": "ObjectPreview", + "optional": true, + "description": "Preview containing abbreviated property values. Specified for <code>object</code> type values only." + } + ] + }, + { + "id": "ObjectPreview", + "type": "object", + "description": "Object containing abbreviated remote object value.", + "properties": [ + { + "name": "type", + "type": "string", + "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol", "bigint"], + "description": "Object type." + }, + { + "name": "subtype", + "type": "string", + "optional": true, + "enum": [ + "array", + "null", + "node", + "regexp", + "date", + "error", + "map", + "set", + "weakmap", + "weakset", + "iterator", + "class", + "proxy", + "weakref" + ], + "description": "Object subtype hint. Specified for <code>object</code> type values only." + }, + { + "name": "description", + "type": "string", + "optional": true, + "description": "String representation of the object." + }, + { + "name": "lossless", + "type": "boolean", + "description": "Determines whether preview is lossless (contains all information of the original object)." + }, + { + "name": "overflow", + "type": "boolean", + "optional": true, + "description": "True iff some of the properties of the original did not fit." + }, + { + "name": "properties", + "type": "array", + "items": { "$ref": "PropertyPreview" }, + "optional": true, + "description": "List of the properties." + }, + { + "name": "entries", + "type": "array", + "items": { "$ref": "EntryPreview" }, + "optional": true, + "description": "List of the entries. Specified for <code>map</code> and <code>set</code> subtype values only." + }, + { + "name": "size", + "type": "integer", + "optional": true, + "description": "Size of the array/collection. Specified for array/map/set/weakmap/weakset object type values only." + } + ] + }, + { + "id": "PropertyPreview", + "type": "object", + "properties": [ + { "name": "name", "type": "string", "description": "Property name." }, + { + "name": "type", + "type": "string", + "enum": [ + "object", + "function", + "undefined", + "string", + "number", + "boolean", + "symbol", + "bigint", + "accessor" + ], + "description": "Object type." + }, + { + "name": "subtype", + "type": "string", + "optional": true, + "enum": [ + "array", + "null", + "node", + "regexp", + "date", + "error", + "map", + "set", + "weakmap", + "weakset", + "iterator", + "class", + "proxy", + "weakref" + ], + "description": "Object subtype hint. Specified for <code>object</code> type values only." + }, + { + "name": "value", + "type": "string", + "optional": true, + "description": "User-friendly property value string." + }, + { + "name": "valuePreview", + "$ref": "ObjectPreview", + "optional": true, + "description": "Nested value preview." + }, + { + "name": "isPrivate", + "type": "boolean", + "optional": true, + "description": "True if this is a private field." + }, + { + "name": "internal", + "type": "boolean", + "optional": true, + "description": "True if this is an internal property." + } + ] + }, + { + "id": "EntryPreview", + "type": "object", + "properties": [ + { + "name": "key", + "$ref": "ObjectPreview", + "optional": true, + "description": "Entry key. Specified for map-like collection entries." + }, + { "name": "value", "$ref": "ObjectPreview", "description": "Entry value." } + ] + }, + { + "id": "CollectionEntry", + "type": "object", + "properties": [ + { + "name": "key", + "$ref": "Runtime.RemoteObject", + "optional": true, + "description": "Entry key of a map-like collection, otherwise not provided." + }, + { "name": "value", "$ref": "Runtime.RemoteObject", "description": "Entry value." } + ] + }, + { + "id": "PropertyDescriptor", + "type": "object", + "description": "Object property descriptor.", + "properties": [ + { "name": "name", "type": "string", "description": "Property name or symbol description." }, + { + "name": "value", + "$ref": "RemoteObject", + "optional": true, + "description": "The value associated with the property." + }, + { + "name": "writable", + "type": "boolean", + "optional": true, + "description": "True if the value associated with the property may be changed (data descriptors only)." + }, + { + "name": "get", + "$ref": "RemoteObject", + "optional": true, + "description": "A function which serves as a getter for the property, or <code>undefined</code> if there is no getter (accessor descriptors only)." + }, + { + "name": "set", + "$ref": "RemoteObject", + "optional": true, + "description": "A function which serves as a setter for the property, or <code>undefined</code> if there is no setter (accessor descriptors only)." + }, + { + "name": "wasThrown", + "type": "boolean", + "optional": true, + "description": "True if the result was thrown during the evaluation." + }, + { + "name": "configurable", + "type": "boolean", + "optional": true, + "description": "True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object." + }, + { + "name": "enumerable", + "type": "boolean", + "optional": true, + "description": "True if this property shows up during enumeration of the properties on the corresponding object." + }, + { + "name": "isOwn", + "optional": true, + "type": "boolean", + "description": "True if the property is owned for the object." + }, + { + "name": "symbol", + "optional": true, + "$ref": "Runtime.RemoteObject", + "description": "Property symbol object, if the property is a symbol." + }, + { + "name": "isPrivate", + "optional": true, + "$ref": "boolean", + "description": "True if the property is a private field." + }, + { + "name": "nativeGetter", + "optional": true, + "type": "boolean", + "description": "True if the property value came from a native getter." + } + ] + }, + { + "id": "InternalPropertyDescriptor", + "type": "object", + "description": "Object internal property descriptor. This property isn't normally visible in JavaScript code.", + "properties": [ + { "name": "name", "type": "string", "description": "Conventional property name." }, + { + "name": "value", + "$ref": "RemoteObject", + "optional": true, + "description": "The value associated with the property." + } + ] + }, + { + "id": "CallArgument", + "type": "object", + "description": "Represents function call argument. Either remote object id <code>objectId</code> or primitive <code>value</code> or neither of (for undefined) them should be specified.", + "properties": [ + { "name": "value", "type": "any", "optional": true, "description": "Primitive value." }, + { "name": "objectId", "$ref": "RemoteObjectId", "optional": true, "description": "Remote object handle." } + ] + }, + { "id": "ExecutionContextId", "type": "integer", "description": "Id of an execution context." }, + { + "id": "ExecutionContextType", + "type": "string", + "enum": ["normal", "user", "internal"], + "description": "Type of the execution context." + }, + { + "id": "ExecutionContextDescription", + "type": "object", + "description": "Description of an isolated world.", + "properties": [ + { + "name": "id", + "$ref": "ExecutionContextId", + "description": "Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed." + }, + { "name": "type", "$ref": "ExecutionContextType" }, + { "name": "name", "type": "string", "description": "Human readable name describing given context." }, + { "name": "frameId", "$ref": "Network.FrameId", "description": "Id of the owning frame." } + ] + }, + { + "id": "SyntaxErrorType", + "type": "string", + "enum": ["none", "irrecoverable", "unterminated-literal", "recoverable"], + "description": "Syntax error type: \"none\" for no error, \"irrecoverable\" for unrecoverable errors, \"unterminated-literal\" for when there is an unterminated literal, \"recoverable\" for when the expression is unfinished but valid so far." + }, + { + "id": "ErrorRange", + "type": "object", + "description": "Range of an error in source code.", + "properties": [ + { "name": "startOffset", "type": "integer", "description": "Start offset of range (inclusive)." }, + { "name": "endOffset", "type": "integer", "description": "End offset of range (exclusive)." } + ] + }, + { + "id": "StructureDescription", + "type": "object", + "properties": [ + { + "name": "fields", + "type": "array", + "items": { "type": "string" }, + "optional": true, + "description": "Array of strings, where the strings represent object properties." + }, + { + "name": "optionalFields", + "type": "array", + "items": { "type": "string" }, + "optional": true, + "description": "Array of strings, where the strings represent optional object properties." + }, + { + "name": "constructorName", + "type": "string", + "optional": true, + "description": "Name of the constructor." + }, + { + "name": "prototypeStructure", + "$ref": "StructureDescription", + "optional": true, + "description": "Pointer to the StructureRepresentation of the protoype if one exists." + }, + { + "name": "isImprecise", + "type": "boolean", + "optional": true, + "description": "If true, it indicates that the fields in this StructureDescription may be inaccurate. I.e, there might have been fields that have been deleted before it was profiled or it has fields we haven't profiled." + } + ] + }, + { + "id": "TypeSet", + "type": "object", + "properties": [ + { + "name": "isFunction", + "type": "boolean", + "description": "Indicates if this type description has been type Function." + }, + { + "name": "isUndefined", + "type": "boolean", + "description": "Indicates if this type description has been type Undefined." + }, + { + "name": "isNull", + "type": "boolean", + "description": "Indicates if this type description has been type Null." + }, + { + "name": "isBoolean", + "type": "boolean", + "description": "Indicates if this type description has been type Boolean." + }, + { + "name": "isInteger", + "type": "boolean", + "description": "Indicates if this type description has been type Integer." + }, + { + "name": "isNumber", + "type": "boolean", + "description": "Indicates if this type description has been type Number." + }, + { + "name": "isString", + "type": "boolean", + "description": "Indicates if this type description has been type String." + }, + { + "name": "isObject", + "type": "boolean", + "description": "Indicates if this type description has been type Object." + }, + { + "name": "isSymbol", + "type": "boolean", + "description": "Indicates if this type description has been type Symbol." + }, + { + "name": "isBigInt", + "type": "boolean", + "description": "Indicates if this type description has been type BigInt." + } + ] + }, + { + "id": "TypeDescription", + "type": "object", + "description": "Container for type information that has been gathered.", + "properties": [ + { + "name": "isValid", + "type": "boolean", + "description": "If true, we were able to correlate the offset successfuly with a program location. If false, the offset may be bogus or the offset may be from a CodeBlock that hasn't executed." + }, + { + "name": "leastCommonAncestor", + "type": "string", + "optional": true, + "description": "Least common ancestor of all Constructors if the TypeDescription has seen any structures. This string is the display name of the shared constructor function." + }, + { + "name": "typeSet", + "$ref": "TypeSet", + "optional": true, + "description": "Set of booleans for determining the aggregate type of this type description." + }, + { + "name": "structures", + "type": "array", + "items": { "$ref": "StructureDescription" }, + "optional": true, + "description": "Array of descriptions for all structures seen for this variable." + }, + { + "name": "isTruncated", + "type": "boolean", + "optional": true, + "description": "If true, this indicates that no more structures are being profiled because some maximum threshold has been reached and profiling has stopped because of memory pressure." + } + ] + }, + { + "id": "TypeLocation", + "type": "object", + "description": "Describes the location of an expression we want type information for.", + "properties": [ + { + "name": "typeInformationDescriptor", + "type": "integer", + "description": "What kind of type information do we want (normal, function return values, 'this' statement)." + }, + { "name": "sourceID", "type": "string", "description": "sourceID uniquely identifying a script" }, + { "name": "divot", "type": "integer", "description": "character offset for assignment range" } + ] + }, + { + "id": "BasicBlock", + "type": "object", + "description": "From Wikipedia: a basic block is a portion of the code within a program with only one entry point and only one exit point. This type gives the location of a basic block and if that basic block has executed.", + "properties": [ + { "name": "startOffset", "type": "integer", "description": "Start offset of the basic block." }, + { "name": "endOffset", "type": "integer", "description": "End offset of the basic block." }, + { + "name": "hasExecuted", + "type": "boolean", + "description": "Indicates if the basic block has executed before." + }, + { + "name": "executionCount", + "type": "integer", + "description": "Indicates how many times the basic block has executed." + } + ] + } + ], + "commands": [ + { + "name": "parse", + "description": "Parses JavaScript source code for errors.", + "parameters": [{ "name": "source", "type": "string", "description": "Source code to parse." }], + "returns": [ + { "name": "result", "$ref": "SyntaxErrorType", "description": "Parse result." }, + { "name": "message", "type": "string", "optional": true, "description": "Parse error message." }, + { + "name": "range", + "$ref": "ErrorRange", + "optional": true, + "description": "Range in the source where the error occurred." + } + ] + }, + { + "name": "evaluate", + "description": "Evaluates expression on global object.", + "parameters": [ + { "name": "expression", "type": "string", "description": "Expression to evaluate." }, + { + "name": "objectGroup", + "type": "string", + "optional": true, + "description": "Symbolic group name that can be used to release multiple objects." + }, + { + "name": "includeCommandLineAPI", + "type": "boolean", + "optional": true, + "description": "Determines whether Command Line API should be available during the evaluation." + }, + { + "name": "doNotPauseOnExceptionsAndMuteConsole", + "type": "boolean", + "optional": true, + "description": "Specifies whether evaluation should stop on exceptions and mute console. Overrides setPauseOnException state." + }, + { + "name": "contextId", + "$ref": "Runtime.ExecutionContextId", + "optional": true, + "description": "Specifies in which isolated context to perform evaluation. Each content script lives in an isolated context and this parameter may be used to specify one of those contexts. If the parameter is omitted or 0 the evaluation will be performed in the context of the inspected page." + }, + { + "name": "returnByValue", + "type": "boolean", + "optional": true, + "description": "Whether the result is expected to be a JSON object that should be sent by value." + }, + { + "name": "generatePreview", + "type": "boolean", + "optional": true, + "description": "Whether preview should be generated for the result." + }, + { + "name": "saveResult", + "type": "boolean", + "optional": true, + "description": "Whether the resulting value should be considered for saving in the $n history." + }, + { + "name": "emulateUserGesture", + "type": "boolean", + "optional": true, + "description": "Whether the expression should be considered to be in a user gesture or not." + } + ], + "returns": [ + { "name": "result", "$ref": "RemoteObject", "description": "Evaluation result." }, + { + "name": "wasThrown", + "type": "boolean", + "optional": true, + "description": "True if the result was thrown during the evaluation." + }, + { + "name": "savedResultIndex", + "type": "integer", + "optional": true, + "description": "If the result was saved, this is the $n index that can be used to access the value." + } + ] + }, + { + "name": "awaitPromise", + "description": "Calls the async callback when the promise with the given ID gets settled.", + "parameters": [ + { "name": "promiseObjectId", "$ref": "RemoteObjectId", "description": "Identifier of the promise." }, + { + "name": "returnByValue", + "type": "boolean", + "optional": true, + "description": "Whether the result is expected to be a JSON object that should be sent by value." + }, + { + "name": "generatePreview", + "type": "boolean", + "optional": true, + "description": "Whether preview should be generated for the result." + }, + { + "name": "saveResult", + "type": "boolean", + "optional": true, + "description": "Whether the resulting value should be considered for saving in the $n history." + } + ], + "returns": [ + { "name": "result", "$ref": "RemoteObject", "description": "Evaluation result." }, + { + "name": "wasThrown", + "type": "boolean", + "optional": true, + "description": "True if the result was thrown during the evaluation." + }, + { + "name": "savedResultIndex", + "type": "integer", + "optional": true, + "description": "If the result was saved, this is the $n index that can be used to access the value." + } + ], + "async": true + }, + { + "name": "callFunctionOn", + "description": "Calls function with given declaration on the given object. Object group of the result is inherited from the target object.", + "parameters": [ + { + "name": "objectId", + "$ref": "RemoteObjectId", + "description": "Identifier of the object to call function on." + }, + { "name": "functionDeclaration", "type": "string", "description": "Declaration of the function to call." }, + { + "name": "arguments", + "type": "array", + "items": { "$ref": "CallArgument", "description": "Call argument." }, + "optional": true, + "description": "Call arguments. All call arguments must belong to the same JavaScript world as the target object." + }, + { + "name": "doNotPauseOnExceptionsAndMuteConsole", + "type": "boolean", + "optional": true, + "description": "Specifies whether function call should stop on exceptions and mute console. Overrides setPauseOnException state." + }, + { + "name": "returnByValue", + "type": "boolean", + "optional": true, + "description": "Whether the result is expected to be a JSON object which should be sent by value." + }, + { + "name": "generatePreview", + "type": "boolean", + "optional": true, + "description": "Whether preview should be generated for the result." + }, + { + "name": "emulateUserGesture", + "type": "boolean", + "optional": true, + "description": "Whether the expression should be considered to be in a user gesture or not." + } + ], + "returns": [ + { "name": "result", "$ref": "RemoteObject", "description": "Call result." }, + { + "name": "wasThrown", + "type": "boolean", + "optional": true, + "description": "True if the result was thrown during the evaluation." + } + ] + }, + { + "name": "getPreview", + "description": "Returns a preview for the given object.", + "parameters": [ + { + "name": "objectId", + "$ref": "RemoteObjectId", + "description": "Identifier of the object to return a preview for." + } + ], + "returns": [{ "name": "preview", "$ref": "ObjectPreview" }] + }, + { + "name": "getProperties", + "description": "Returns properties of a given object. Object group of the result is inherited from the target object.", + "parameters": [ + { + "name": "objectId", + "$ref": "RemoteObjectId", + "description": "Identifier of the object to return properties for." + }, + { + "name": "ownProperties", + "optional": true, + "type": "boolean", + "description": "If true, returns properties belonging only to the object itself, not to its prototype chain." + }, + { + "name": "fetchStart", + "optional": true, + "type": "integer", + "description": "If provided skip to this value before collecting values. Otherwise, start at the beginning. Has no effect when the `objectId` is for a `iterator`/`WeakMap`/`WeakSet` object." + }, + { + "name": "fetchCount", + "optional": true, + "type": "integer", + "description": "If provided only return `fetchCount` values. Otherwise, return values all the way to the end." + }, + { + "name": "generatePreview", + "type": "boolean", + "optional": true, + "description": "Whether preview should be generated for property values." + } + ], + "returns": [ + { + "name": "properties", + "type": "array", + "items": { "$ref": "PropertyDescriptor" }, + "description": "Object properties." + }, + { + "name": "internalProperties", + "optional": true, + "type": "array", + "items": { "$ref": "InternalPropertyDescriptor" }, + "description": "Internal object properties. Only included if `fetchStart` is 0." + } + ] + }, + { + "name": "getDisplayableProperties", + "description": "Returns displayable properties of a given object. Object group of the result is inherited from the target object. Displayable properties are own properties, internal properties, and native getters in the prototype chain (assumed to be bindings and treated like own properties for the frontend).", + "parameters": [ + { + "name": "objectId", + "$ref": "RemoteObjectId", + "description": "Identifier of the object to return properties for." + }, + { + "name": "fetchStart", + "optional": true, + "type": "integer", + "description": "If provided skip to this value before collecting values. Otherwise, start at the beginning. Has no effect when the `objectId` is for a `iterator`/`WeakMap`/`WeakSet` object." + }, + { + "name": "fetchCount", + "optional": true, + "type": "integer", + "description": "If provided only return `fetchCount` values. Otherwise, return values all the way to the end." + }, + { + "name": "generatePreview", + "type": "boolean", + "optional": true, + "description": "Whether preview should be generated for property values." + } + ], + "returns": [ + { + "name": "properties", + "type": "array", + "items": { "$ref": "PropertyDescriptor" }, + "description": "Object properties." + }, + { + "name": "internalProperties", + "optional": true, + "type": "array", + "items": { "$ref": "InternalPropertyDescriptor" }, + "description": "Internal object properties. Only included if `fetchStart` is 0." + } + ] + }, + { + "name": "getCollectionEntries", + "description": "Returns entries of given Map / Set collection.", + "parameters": [ + { + "name": "objectId", + "$ref": "Runtime.RemoteObjectId", + "description": "Id of the collection to get entries for." + }, + { + "name": "objectGroup", + "optional": true, + "type": "string", + "description": "Symbolic group name that can be used to release multiple. If not provided, it will be the same objectGroup as the RemoteObject determined from <code>objectId</code>. This is useful for WeakMap to release the collection entries." + }, + { + "name": "fetchStart", + "optional": true, + "type": "integer", + "description": "If provided skip to this value before collecting values. Otherwise, start at the beginning. Has no effect when the `objectId<` is for a `iterator<`/`WeakMap<`/`WeakSet<` object." + }, + { + "name": "fetchCount", + "optional": true, + "type": "integer", + "description": "If provided only return `fetchCount` values. Otherwise, return values all the way to the end." + } + ], + "returns": [ + { + "name": "entries", + "type": "array", + "items": { "$ref": "CollectionEntry" }, + "description": "Array of collection entries." + } + ] + }, + { + "name": "saveResult", + "description": "Assign a saved result index to this value.", + "parameters": [ + { "name": "value", "$ref": "CallArgument", "description": "Id or value of the object to save." }, + { + "name": "contextId", + "optional": true, + "$ref": "ExecutionContextId", + "description": "Unique id of the execution context. To specify in which execution context script evaluation should be performed. If not provided, determine from the CallArgument's objectId." + } + ], + "returns": [ + { + "name": "savedResultIndex", + "type": "integer", + "optional": true, + "description": "If the value was saved, this is the $n index that can be used to access the value." + } + ] + }, + { + "name": "setSavedResultAlias", + "description": "Creates an additional reference to all saved values in the Console using the the given string as a prefix instead of $.", + "parameters": [ + { + "name": "alias", + "type": "string", + "optional": true, + "description": "Passing an empty/null string will clear the alias." + } + ] + }, + { + "name": "releaseObject", + "description": "Releases remote object with given id.", + "parameters": [ + { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to release." } + ] + }, + { + "name": "releaseObjectGroup", + "description": "Releases all remote objects that belong to a given group.", + "parameters": [{ "name": "objectGroup", "type": "string", "description": "Symbolic object group name." }] + }, + { + "name": "enable", + "description": "Enables reporting of execution contexts creation by means of <code>executionContextCreated</code> event. When the reporting gets enabled the event will be sent immediately for each existing execution context." + }, + { "name": "disable", "description": "Disables reporting of execution contexts creation." }, + { + "name": "getRuntimeTypesForVariablesAtOffsets", + "description": "Returns detailed information on the given function.", + "parameters": [ + { + "name": "locations", + "type": "array", + "items": { "$ref": "TypeLocation" }, + "description": "An array of type locations we're requesting information for. Results are expected in the same order they're sent in." + } + ], + "returns": [ + { + "name": "types", + "type": "array", + "items": { "$ref": "TypeDescription", "description": "Types for requested variable." } + } + ] + }, + { "name": "enableTypeProfiler", "description": "Enables type profiling on the VM." }, + { "name": "disableTypeProfiler", "description": "Disables type profiling on the VM." }, + { "name": "enableControlFlowProfiler", "description": "Enables control flow profiling on the VM." }, + { "name": "disableControlFlowProfiler", "description": "Disables control flow profiling on the VM." }, + { + "name": "getBasicBlocks", + "description": "Returns a list of basic blocks for the given sourceID with information about their text ranges and whether or not they have executed.", + "parameters": [ + { + "name": "sourceID", + "type": "string", + "description": "Indicates which sourceID information is requested for." + } + ], + "returns": [ + { + "name": "basicBlocks", + "type": "array", + "items": { "$ref": "BasicBlock", "description": "Array of basic blocks." } + } + ] + } + ], + "events": [ + { + "name": "executionContextCreated", + "description": "Issued when new execution context is created.", + "parameters": [ + { + "name": "context", + "$ref": "ExecutionContextDescription", + "description": "A newly created execution context." + } + ] + } + ] + }, + { + "domain": "ScriptProfiler", + "description": "Profiler domain exposes JavaScript evaluation timing and profiling.", + "debuggableTypes": ["itml", "javascript", "page", "web-page"], + "targetTypes": ["itml", "javascript", "page"], + "types": [ + { "id": "EventType", "type": "string", "enum": ["API", "Microtask", "Other"] }, + { + "id": "Event", + "type": "object", + "properties": [ + { "name": "startTime", "type": "number" }, + { "name": "endTime", "type": "number" }, + { "name": "type", "$ref": "EventType" } + ] + }, + { + "id": "ExpressionLocation", + "type": "object", + "properties": [ + { "name": "line", "type": "integer", "description": "1-based." }, + { "name": "column", "type": "integer", "description": "1-based." } + ] + }, + { + "id": "StackFrame", + "type": "object", + "properties": [ + { "name": "sourceID", "$ref": "Debugger.ScriptId", "description": "Unique script identifier." }, + { + "name": "name", + "type": "string", + "description": "A displayable name for the stack frame. i.e function name, (program), etc." + }, + { "name": "line", "type": "integer", "description": "-1 if unavailable. 1-based if available." }, + { "name": "column", "type": "integer", "description": "-1 if unavailable. 1-based if available." }, + { "name": "url", "type": "string" }, + { "name": "expressionLocation", "$ref": "ExpressionLocation", "optional": true } + ] + }, + { + "id": "StackTrace", + "type": "object", + "properties": [ + { "name": "timestamp", "type": "number" }, + { + "name": "stackFrames", + "type": "array", + "items": { "$ref": "StackFrame" }, + "description": "First array item is the bottom of the call stack and last array item is the top of the call stack." + } + ] + }, + { + "id": "Samples", + "type": "object", + "properties": [{ "name": "stackTraces", "type": "array", "items": { "$ref": "StackTrace" } }] + } + ], + "commands": [ + { + "name": "startTracking", + "description": "Start tracking script evaluations.", + "parameters": [ + { + "name": "includeSamples", + "type": "boolean", + "optional": true, + "description": "Start the sampling profiler, defaults to false." + } + ] + }, + { + "name": "stopTracking", + "description": "Stop tracking script evaluations. This will produce a `trackingComplete` event." + } + ], + "events": [ + { + "name": "trackingStart", + "description": "Tracking started.", + "parameters": [{ "name": "timestamp", "type": "number" }] + }, + { + "name": "trackingUpdate", + "description": "Periodic tracking updates with event data.", + "parameters": [{ "name": "event", "$ref": "Event" }] + }, + { + "name": "trackingComplete", + "description": "Tracking stopped. Includes any buffered data during tracking, such as profiling information.", + "parameters": [ + { "name": "timestamp", "type": "number" }, + { "name": "samples", "$ref": "Samples", "optional": true, "description": "Stack traces." } + ] + } + ] + } + ] +} diff --git a/packages/bun-inspector-protocol/protocol/protocol.d.ts b/packages/bun-inspector-protocol/protocol/protocol.d.ts new file mode 100644 index 000000000..eae326469 --- /dev/null +++ b/packages/bun-inspector-protocol/protocol/protocol.d.ts @@ -0,0 +1,28 @@ +// @ts-nocheck +// The content of this file is included in each generated protocol file. + +export type Event<T extends keyof EventMap = keyof EventMap> = { + readonly method: T; + readonly params: EventMap[T]; +}; + +export type Request<T extends keyof RequestMap = keyof RequestMap> = { + readonly id: number; + readonly method: T; + readonly params: RequestMap[T]; +}; + +export type Response<T extends keyof ResponseMap = keyof ResponseMap> = { + readonly id: number; +} & ( + | { + readonly method?: T; + readonly result: ResponseMap[T]; + } + | { + readonly error: { + readonly code?: string; + readonly message: string; + }; + } +); diff --git a/packages/bun-inspector-protocol/protocol/schema.d.ts b/packages/bun-inspector-protocol/protocol/schema.d.ts new file mode 100644 index 000000000..a92bea546 --- /dev/null +++ b/packages/bun-inspector-protocol/protocol/schema.d.ts @@ -0,0 +1,58 @@ +// Represents the schema of the protocol.json file. + +export type Protocol = { + readonly name: string; + readonly version: { + readonly major: number; + readonly minor: number; + }; + readonly domains: readonly Domain[]; +}; + +export type Domain = { + readonly domain: string; + readonly dependencies?: readonly string[]; + readonly types: readonly Property[]; + readonly commands?: readonly Command[]; + readonly events?: readonly Event[]; +}; + +export type Command = { + readonly name: string; + readonly description?: string; + readonly parameters?: readonly Property[]; + readonly returns?: readonly Property[]; +}; + +export type Event = { + readonly name: string; + readonly description?: string; + readonly parameters: readonly Property[]; +}; + +export type Property = { + readonly id?: string; + readonly name?: string; + readonly description?: string; + readonly optional?: boolean; +} & ( + | { + readonly type: "array"; + readonly items?: Property; + } + | { + readonly type: "object"; + readonly properties?: readonly Property[]; + } + | { + readonly type: "string"; + readonly enum?: readonly string[]; + } + | { + readonly type: "boolean" | "number" | "integer"; + } + | { + readonly type: undefined; + readonly $ref: string; + } +); diff --git a/packages/bun-inspector-protocol/scripts/generate-protocol.ts b/packages/bun-inspector-protocol/scripts/generate-protocol.ts new file mode 100644 index 000000000..8da5fe795 --- /dev/null +++ b/packages/bun-inspector-protocol/scripts/generate-protocol.ts @@ -0,0 +1,202 @@ +import type { Protocol, Domain, Property } from "../protocol/schema"; +import { readFileSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; + +run().catch(console.error); + +async function run() { + const cwd = new URL("../protocol/", import.meta.url); + const runner = "Bun" in globalThis ? "bunx" : "npx"; + const write = (name: string, data: string) => { + const path = new URL(name, cwd); + writeFileSync(path, data); + spawnSync(runner, ["prettier", "--write", path.pathname], { cwd, stdio: "ignore" }); + }; + const base = readFileSync(new URL("protocol.d.ts", cwd), "utf-8"); + const baseNoComments = base.replace(/\/\/.*/g, ""); + const jsc = await downloadJsc(); + write("jsc/protocol.json", JSON.stringify(jsc)); + write("jsc/index.d.ts", "// GENERATED - DO NOT EDIT\n" + formatProtocol(jsc, baseNoComments)); + const v8 = await downloadV8(); + write("v8/protocol.json", JSON.stringify(v8)); + write("v8/index.d.ts", "// GENERATED - DO NOT EDIT\n" + formatProtocol(v8, baseNoComments)); +} + +function formatProtocol(protocol: Protocol, extraTs?: string): string { + const { name, domains } = protocol; + const eventMap = new Map(); + const commandMap = new Map(); + let body = `export namespace ${name} {`; + for (const { domain, types = [], events = [], commands = [] } of domains) { + body += `export namespace ${domain} {`; + for (const type of types) { + body += formatProperty(type); + } + for (const { name, description, parameters = [] } of events) { + const symbol = `${domain}.${name}`; + const title = toTitle(name); + eventMap.set(symbol, `${domain}.${title}`); + body += formatProperty({ + id: `${title}Event`, + type: "object", + description: `${description}\n@event \`${symbol}\``, + properties: parameters, + }); + } + for (const { name, description, parameters = [], returns = [] } of commands) { + const symbol = `${domain}.${name}`; + const title = toTitle(name); + commandMap.set(symbol, `${domain}.${title}`); + body += formatProperty({ + id: `${title}Request`, + type: "object", + description: `${description}\n@request \`${symbol}\``, + properties: parameters, + }); + body += formatProperty({ + id: `${title}Response`, + type: "object", + description: `${description}\n@response \`${symbol}\``, + properties: returns, + }); + } + body += "};"; + } + for (const type of ["Event", "Request", "Response"]) { + const sourceMap = type === "Event" ? eventMap : commandMap; + body += formatProperty({ + id: `${type}Map`, + type: "object", + properties: [...sourceMap.entries()].map(([name, title]) => ({ + name: `"${name}"`, + type: undefined, + $ref: `${title}${type}`, + })), + }); + } + if (extraTs) { + body += extraTs; + } + return body + "};"; +} + +function formatProperty(property: Property): string { + const { id, description, type, optional } = property; + let body = ""; + if (id) { + if (description) { + body += `\n${toComment(description)}\n`; + } + body += `export type ${id}=`; + } + if (type === "boolean") { + body += "boolean"; + } else if (type === "number" || type === "integer") { + body += "number"; + } else if (type === "string") { + const { enum: choices } = property; + if (choices) { + body += choices.map(value => `"${value}"`).join("|"); + } else { + body += "string"; + } + } else if (type === "array") { + const { items } = property; + const itemType = items ? formatProperty(items) : "unknown"; + body += `${itemType}[]`; + } else if (type === "object") { + const { properties } = property; + if (!properties) { + body += "Record<string, unknown>"; + } else if (properties.length === 0) { + body += "{}"; + } else { + body += "{"; + for (const { name, description, ...property } of properties) { + if (description) { + body += `\n${toComment(description)}`; + } + const delimit = property.optional ? "?:" : ":"; + body += `\n${name}${delimit}${formatProperty({ ...property, id: undefined })};`; + } + body += "}"; + } + } else if ("$ref" in property) { + body += property.$ref; + } else { + body += "unknown"; + } + if (optional) { + body += "|undefined"; + } + if (id) { + body += ";"; + } + return body; +} + +/** + * @link https://github.com/ChromeDevTools/devtools-protocol/tree/master/json + */ +async function downloadV8(): Promise<Protocol> { + const baseUrl = "https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/json"; + const domains = ["Runtime", "Console", "Debugger", "Memory", "HeapProfiler", "Profiler", "Network", "Inspector"]; + return Promise.all([ + download<Protocol>(`${baseUrl}/js_protocol.json`), + download<Protocol>(`${baseUrl}/browser_protocol.json`), + ]).then(([js, browser]) => ({ + name: "V8", + version: js.version, + domains: [...js.domains, ...browser.domains] + .filter(domain => !domains.includes(domain.domain)) + .sort((a, b) => a.domain.localeCompare(b.domain)), + })); +} + +/** + * @link https://github.com/WebKit/WebKit/tree/main/Source/JavaScriptCore/inspector/protocol + */ +async function downloadJsc(): Promise<Protocol> { + const baseUrl = "https://raw.githubusercontent.com/WebKit/WebKit/main/Source/JavaScriptCore/inspector/protocol"; + const domains = [ + "Runtime", + "Console", + "Debugger", + "Heap", + "ScriptProfiler", + "CPUProfiler", + "GenericTypes", + "Network", + "Inspector", + ]; + return { + name: "JSC", + version: { + major: 1, + minor: 3, + }, + domains: await Promise.all(domains.map(domain => download<Domain>(`${baseUrl}/${domain}.json`))).then(domains => + domains.sort((a, b) => a.domain.localeCompare(b.domain)), + ), + }; +} + +async function download<V>(url: string): Promise<V> { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`${response.status}: ${url}`); + } + return response.json(); +} + +function toTitle(name: string): string { + return name.charAt(0).toUpperCase() + name.slice(1); +} + +function toComment(description?: string): string { + if (!description) { + return ""; + } + const lines = ["/**", ...description.split("\n").map(line => ` * ${line.trim()}`), "*/"]; + return lines.join("\n"); +} diff --git a/packages/bun-inspector-protocol/tsconfig.json b/packages/bun-inspector-protocol/tsconfig.json new file mode 100644 index 000000000..f954cc16f --- /dev/null +++ b/packages/bun-inspector-protocol/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "lib": ["ESNext"], + "module": "esnext", + "target": "esnext", + "moduleResolution": "nodenext", + "moduleDetection": "force", + "strict": true, + "downlevelIteration": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "inlineSourceMap": true, + "allowJs": true, + "outDir": "dist", + "types": ["node"] + }, + "include": [".", "../bun-types/index.d.ts"] +} diff --git a/packages/bun-lambda/package.json b/packages/bun-lambda/package.json index af3ece70b..f670787eb 100644 --- a/packages/bun-lambda/package.json +++ b/packages/bun-lambda/package.json @@ -1,4 +1,6 @@ { + "name": "bun-lambda", + "private": true, "devDependencies": { "bun-types": "^0.7.0", "jszip": "^3.10.1", diff --git a/packages/bun-release/package.json b/packages/bun-release/package.json index ccbf51aa1..c0ed4bad3 100644 --- a/packages/bun-release/package.json +++ b/packages/bun-release/package.json @@ -1,4 +1,5 @@ { + "name": "bun-release-action", "private": true, "dependencies": { "aws4fetch": "^1.0.17", diff --git a/packages/bun-vscode/.gitignore b/packages/bun-vscode/.gitignore new file mode 100644 index 000000000..9db2648e4 --- /dev/null +++ b/packages/bun-vscode/.gitignore @@ -0,0 +1,2 @@ +node_modules +extension diff --git a/packages/bun-vscode/.vscode/launch.json b/packages/bun-vscode/.vscode/launch.json index 264dbbdf2..3ec1574d3 100644 --- a/packages/bun-vscode/.vscode/launch.json +++ b/packages/bun-vscode/.vscode/launch.json @@ -5,10 +5,7 @@ "name": "Extension", "type": "extensionHost", "request": "launch", - "args": [ - "--extensionDevelopmentPath=${workspaceFolder}", - "${workspaceFolder}/example" - ], + "args": ["--extensionDevelopmentPath=${workspaceFolder}", "${workspaceFolder}/example"], "outFiles": ["${workspaceFolder}/dist/**/*.js"], "preLaunchTask": "Build (watch)" }, diff --git a/packages/bun-vscode/.vscode/settings.json b/packages/bun-vscode/.vscode/settings.json index f1a747121..feac1750e 100644 --- a/packages/bun-vscode/.vscode/settings.json +++ b/packages/bun-vscode/.vscode/settings.json @@ -5,5 +5,5 @@ "search.exclude": { "out": true // set this to false to include "out" folder in search results }, - "typescript.tsc.autoDetect": "off", -}
\ No newline at end of file + "typescript.tsc.autoDetect": "off" +} diff --git a/packages/bun-vscode/.vscode/tasks.json b/packages/bun-vscode/.vscode/tasks.json index e31008850..a471df3ec 100644 --- a/packages/bun-vscode/.vscode/tasks.json +++ b/packages/bun-vscode/.vscode/tasks.json @@ -4,13 +4,15 @@ { "label": "Build", "type": "shell", - "command": "bun run build" + "command": "bun run build", + "problemMatcher": "$esbuild" }, { "label": "Build (watch)", "type": "shell", "command": "bun run build:watch", - "isBackground": true + "isBackground": true, + "problemMatcher": "$esbuild-watch" } ] -}
\ No newline at end of file +} diff --git a/packages/bun-vscode/README.md b/packages/bun-vscode/README.md index e22107c19..08c81fb2f 100644 --- a/packages/bun-vscode/README.md +++ b/packages/bun-vscode/README.md @@ -1 +1,22 @@ -# Debug Adapter Protocol for Bun +# Bun for Visual Studio Code + + + + + +<img align="right" src="https://user-images.githubusercontent.com/709451/182802334-d9c42afe-f35d-4a7b-86ea-9985f73f20c3.png" height="150px" style="float: right; padding: 30px;"> + +This extension adds support for using [Bun](https://bun.sh/) with Visual Studio Code. Bun is an all-in-one toolkit for JavaScript and TypeScript apps. + +At its core is the _Bun runtime_, a fast JavaScript runtime designed as a drop-in replacement for Node.js. It's written in Zig and powered by JavaScriptCore under the hood, dramatically reducing startup times and memory usage. + +<div align="center"> + <a href="https://bun.sh/docs">Documentation</a> + <span> • </span> + <a href="https://discord.com/invite/CXdq2DP29u">Discord</a> + <span> • </span> + <a href="https://github.com/oven-sh/bun/issues/new">Issues</a> + <span> • </span> + <a href="https://github.com/oven-sh/bun/issues/159">Roadmap</a> + <br/> +</div> diff --git a/packages/bun-vscode/TODO.md b/packages/bun-vscode/TODO.md deleted file mode 100644 index bdebd273d..000000000 --- a/packages/bun-vscode/TODO.md +++ /dev/null @@ -1,5 +0,0 @@ -* Off-by-one for debug lines -* Formatting values in console (some code is wired up) -* Play button on debugger actually starting Bun -* bun debug or --inspect command added to Bun, not need Bun.serve -* Breakpoint actually setting diff --git a/packages/bun-vscode/bun.lockb b/packages/bun-vscode/bun.lockb Binary files differindex eab6a3178..c0949dd2d 100755 --- a/packages/bun-vscode/bun.lockb +++ b/packages/bun-vscode/bun.lockb diff --git a/packages/bun-vscode/example/.vscode/launch.json b/packages/bun-vscode/example/.vscode/launch.json index 11cb43173..7ab446fad 100644 --- a/packages/bun-vscode/example/.vscode/launch.json +++ b/packages/bun-vscode/example/.vscode/launch.json @@ -4,16 +4,15 @@ { "type": "bun", "request": "launch", - "name": "Debug", - "program": "${workspaceFolder}/example.js", - "stopOnEntry": true + "name": "Debug Bun", + "program": "${file}", + "watch": "hot" }, { "type": "bun", "request": "attach", - "name": "Attach", - "program": "${workspaceFolder}/example.js", - "stopOnEntry": true + "name": "Attach to Bun", + "url": "ws://localhost:6499/", } ] } diff --git a/packages/bun-vscode/example/example-sourcemap.js b/packages/bun-vscode/example/example-sourcemap.js new file mode 100644 index 000000000..82035bedb --- /dev/null +++ b/packages/bun-vscode/example/example-sourcemap.js @@ -0,0 +1,30 @@ +// @bun +// example.ts +var a = function (request) { + b(request); +}; +var b = function (request) { + c(request); +}; +var c = function (request) { + console.log(request); +}; +var example_default = { + async fetch(request, server) { + a(request); + const coolThing = new SuperCoolThing(); + coolThing.doCoolThing(); + debugger; + return new Response(request.url); + }, +}; + +class SuperCoolThing { + doCoolThing() { + console.log("super cool thing!"); + } +} +export { example_default as default }; + +//# debugId=9BB0B773A8E4771564756e2164756e21 +//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiZXhhbXBsZS50cyJdLAogICJzb3VyY2VzQ29udGVudCI6IFsKICAgICJpbXBvcnQgdHlwZSB7IFNlcnZlciB9IGZyb20gXCJidW5cIjtcblxuZXhwb3J0IGRlZmF1bHQge1xuICBhc3luYyBmZXRjaChyZXF1ZXN0OiBSZXF1ZXN0LCBzZXJ2ZXI6IFNlcnZlcik6IFByb21pc2U8UmVzcG9uc2U+IHtcbiAgICBhKHJlcXVlc3QpO1xuICAgIGNvbnN0IGNvb2xUaGluZzogQ29vbFRoaW5nID0gbmV3IFN1cGVyQ29vbFRoaW5nKCk7XG4gICAgY29vbFRoaW5nLmRvQ29vbFRoaW5nKCk7XG4gICAgZGVidWdnZXI7XG4gICAgcmV0dXJuIG5ldyBSZXNwb25zZShyZXF1ZXN0LnVybCk7XG4gIH1cbn07XG5cbi8vIGFcbmZ1bmN0aW9uIGEocmVxdWVzdDogUmVxdWVzdCk6IHZvaWQge1xuICBiKHJlcXVlc3QpO1xufVxuXG4vLyBiXG5mdW5jdGlvbiBiKHJlcXVlc3Q6IFJlcXVlc3QpOiB2b2lkIHtcbiAgYyhyZXF1ZXN0KTtcbn1cblxuLy8gY1xuZnVuY3Rpb24gYyhyZXF1ZXN0OiBSZXF1ZXN0KSB7XG4gIGNvbnNvbGUubG9nKHJlcXVlc3QpO1xufVxuXG5pbnRlcmZhY2UgQ29vbFRoaW5nIHtcbiAgZG9Db29sVGhpbmcoKTogdm9pZDtcbn1cblxuY2xhc3MgU3VwZXJDb29sVGhpbmcgaW1wbGVtZW50cyBDb29sVGhpbmcge1xuICBkb0Nvb2xUaGluZygpOiB2b2lkIHtcbiAgICBjb25zb2xlLmxvZyhcInN1cGVyIGNvb2wgdGhpbmchXCIpO1xuICB9XG59XG4iCiAgXSwKICAibWFwcGluZ3MiOiAiOztBQS8vLy8vZkFhQSxJQUFTLFlBQUMsQ0FBQyxTQUF3QjtBQUNqQyxJQUFFLE9BQU87QUFBQTtBQUlYLElBQVMsWUFBQyxDQUFDLFNBQXdCO0FBQ2pDLElBQUUsT0FBTztBQUFBO0FBSVgsSUFBUyxZQUFDLENBQUMsU0FBa0I7QUFDM0IsVUFBUSxJQUFJLE9BQU87QUFBQTtBQXRCckIsSUFBZTtBQUFBLE9BQ1AsTUFBSyxDQUFDLFNBQWtCLFFBQW1DO0FBQy9ELE1BQUUsT0FBTztBQUNULFVBQU0sWUFBdUIsSUFBSTtBQUNqQyxjQUFVLFlBQVk7QUFDdEI7QUFDQSxXQUFPLElBQUksU0FBUyxRQUFRLEdBQUc7QUFBQTtBQUVuQztBQXFCQTtBQUFBLE1BQU0sZUFBb0M7QUFBQSxFQUN4QyxXQUFXLEdBQVM7QUFDbEIsWUFBUSxJQUFJLG1CQUFtQjtBQUFBO0FBRW5DOyIsCiAgImRlYnVnSWQiOiAiOUJCMEI3NzNBOEU0NzcxNTY0NzU2ZTIxNjQ3NTZlMjEiLAogICJuYW1lcyI6IFtdCn0= diff --git a/packages/bun-vscode/example/example.js b/packages/bun-vscode/example/example.js index d7e8709d6..31831824b 100644 --- a/packages/bun-vscode/example/example.js +++ b/packages/bun-vscode/example/example.js @@ -5,7 +5,7 @@ import { readFile } from "node:fs/promises"; app .get("/", (req, res) => { - console.log("I am logging a request!"); + console.log("I am logging a request!??"); readFile(import.meta.path, "utf-8").then(data => { console.log(data.length); debugger; @@ -57,7 +57,7 @@ Bun.serve({ inspector: true, development: true, fetch(request, server) { - console.log(request); + // console.log(request); return new Response(request.url); }, }); diff --git a/packages/bun-vscode/example/example.ts b/packages/bun-vscode/example/example.ts new file mode 100644 index 000000000..386b97f7c --- /dev/null +++ b/packages/bun-vscode/example/example.ts @@ -0,0 +1,34 @@ +export default { + async fetch(request: Request): Promise<Response> { + a(request); + const coolThing: CoolThing = new SuperCoolThing(); + coolThing.doCoolThing(); + debugger; + return new Response("HELLO WORLD"); + }, +}; + +// a +function a(request: Request): void { + b(request); +} + +// b +function b(request: Request): void { + c(request); +} + +// c +function c(request: Request) { + console.log(request); +} + +interface CoolThing { + doCoolThing(): void; +} + +class SuperCoolThing implements CoolThing { + doCoolThing(): void { + console.log("BLAH BLAH"); + } +} diff --git a/packages/bun-vscode/package.json b/packages/bun-vscode/package.json index e43b2979d..c959cd8ab 100644 --- a/packages/bun-vscode/package.json +++ b/packages/bun-vscode/package.json @@ -1,65 +1,101 @@ { "name": "bun-vscode", "version": "0.0.1", - "main": "./dist/extension.js", + "author": "oven", + "repository": { + "type": "git", + "url": "https://github.com/oven-sh/bun" + }, + "main": "dist/extension.js", + "dependencies": { + "semver": "^7.5.4", + "source-map-js": "^1.0.2", + "ws": "^8.13.0" + }, "devDependencies": { "@types/vscode": "^1.81.0", "@vscode/debugadapter": "^1.56.0", "@vscode/debugadapter-testsupport": "^1.56.0", "bun-types": "^0.7.3", - "typescript": "^5.0.0" + "typescript": "^5.0.0", + "esbuild": "^0.19.2" }, "activationEvents": [ + "onLanguage:javascript", + "onLanguage:javascriptreact", + "onLanguage:typescript", + "onLanguage:typescriptreact", + "workspaceContains:**/.lockb", "onDebugResolve:bun", - "onDebugDynamicConfigurations:bun", - "onCommand:extension.bun.getProgramName" + "onDebugDynamicConfigurations:bun" ], - "browser": "./dist/web-extension.js", + "browser": "dist/web-extension.js", + "bugs": { + "url": "https://github.com/oven-sh/bun/issues" + }, + "capabilities": { + "untrustedWorkspaces": { + "supported": false, + "description": "This extension needs to be able to run your code using Bun." + } + }, "categories": [ "Programming Languages", - "Debuggers" + "Debuggers", + "Testing" ], "contributes": { + "configuration": { + "title": "Bun", + "properties": { + "bun.path": { + "type": "string", + "description": "A path to the `bun` executable. By default, the extension looks for `bun` in the `PATH`, but if set, it will use the specified path instead.", + "scope": "window", + "default": null + } + } + }, + "commands": [ + { + "command": "extension.bun.runFile", + "title": "Run File", + "category": "Bun", + "enablement": "!inDebugMode", + "icon": "$(play)" + }, + { + "command": "extension.bun.debugFile", + "title": "Debug File", + "category": "Bun", + "enablement": "!inDebugMode", + "icon": "$(debug-alt)" + } + ], "menus": { "editor/title/run": [ { - "command": "extension.bun.runEditorContents", - "when": "resourceLangId == javascript", + "command": "extension.bun.runFile", + "when": "resourceLangId == javascript || resourceLangId == javascriptreact || resourceLangId == typescript || resourceLangId == typescriptreact", "group": "navigation@1" }, { - "command": "extension.bun.debugEditorContents", - "when": "resourceLangId == javascript", + "command": "extension.bun.debugFile", + "when": "resourceLangId == javascript || resourceLangId == javascriptreact || resourceLangId == typescript || resourceLangId == typescriptreact", "group": "navigation@2" } ], "commandPalette": [ { - "command": "extension.bun.debugEditorContents", - "when": "resourceLangId == javascript" + "command": "extension.bun.runFile", + "when": "resourceLangId == javascript || resourceLangId == javascriptreact || resourceLangId == typescript || resourceLangId == typescriptreact" }, { - "command": "extension.bun.runEditorContents", - "when": "resourceLangId == javascript" + "command": "extension.bun.debugFile", + "when": "resourceLangId == javascript || resourceLangId == javascriptreact || resourceLangId == typescript || resourceLangId == typescriptreact" } ] }, - "commands": [ - { - "command": "extension.bun.debugEditorContents", - "title": "Debug File", - "category": "Bun Debug", - "enablement": "!inDebugMode", - "icon": "$(debug-alt)" - }, - { - "command": "extension.bun.runEditorContents", - "title": "Run File", - "category": "Bun Debug", - "enablement": "!inDebugMode", - "icon": "$(play)" - } - ], "breakpoints": [ { "language": "javascript" @@ -85,31 +121,64 @@ "typescriptreact" ], "runtime": "node", - "program": "./dist/adapter.js", + "program": "dist/adapter.js", "configurationAttributes": { "launch": { "required": [ "program" ], "properties": { + "runtime": { + "type": "string", + "description": "The path to Bun.", + "default": "bun" + }, "program": { "type": "string", - "description": "The file to run and debug.", - "default": "${workspaceFolder}/${command:AskForProgramName}" + "description": "The file to debug.", + "default": "${file}" + }, + "cwd": { + "type": "string", + "description": "The working directory.", + "default": "${workspaceFolder}" + }, + "args": { + "type": "array", + "description": "The arguments passed to Bun.", + "items": { + "type": "string" + }, + "default": [] + }, + "env": { + "type": "object", + "description": "The environment variables passed to Bun.", + "default": {} + }, + "inheritEnv": { + "type": "boolean", + "description": "If environment variables should be inherited from the parent process.", + "default": true + }, + "watch": { + "type": ["boolean", "string"], + "description": "If the process should be restarted when files change.", + "enum": [ + true, + false, + "hot" + ], + "default": true } } }, "attach": { "properties": { - "port": { - "type": "integer", - "description": "The port to attach and debug.", - "default": 6499 - }, - "hostname": { + "url": { "type": "string", - "description": "The hostname to attach and debug.", - "default": "localhost" + "description": "The URL of the Bun process to attach to.", + "default": "ws://localhost:6499/" } } } @@ -119,12 +188,13 @@ "type": "bun", "request": "launch", "name": "Bun: Debug", - "program": "${workspaceFolder}/${command:AskForProgramName}" + "program": "${file}" }, { "type": "bun", "request": "attach", - "name": "Bun: Attach" + "name": "Bun: Attach", + "url": "ws://localhost:6499/" } ], "configurationSnippets": [ @@ -135,7 +205,7 @@ "type": "bun", "request": "launch", "name": "Ask for file name", - "program": "^\"\\${workspaceFolder}/\\${command:AskForProgramName}\"" + "program": "^\"\\${file}\"" } }, { @@ -145,14 +215,10 @@ "type": "bun", "request": "attach", "name": "Attach to Bun", - "port": 6499, - "hostname": "localhost" + "url": "ws://localhost:6499/" } } - ], - "variables": { - "AskForProgramName": "extension.bun.getProgramName" - } + ] } ], "languages": [ @@ -165,15 +231,15 @@ ".lockb" ], "icon": { - "dark": "./src/assets/icon-small.png", - "light": "./src/assets/icon-small.png" + "dark": "src/assets/icon-small.png", + "light": "src/assets/icon-small.png" } } ], "jsonValidation": [ { "fileMatch": "package.json", - "url": "./src/resources/package.json" + "url": "src/resources/package.json" } ], "customEditors": [ @@ -189,26 +255,40 @@ } ] }, - "description": "Visual Studio Code extension for Bun.", + "description": "The Visual Studio Code extension for Bun.", + "displayName": "Bun", "engines": { - "vscode": "^1.66.0" + "vscode": "^1.81.0" }, + "extensionKind": [ + "workspace" + ], "galleryBanner": { "color": "#C80000", "theme": "dark" }, - "icon": "./src/assets/icon.png", + "homepage": "https://bun.sh/", + "icon": "src/assets/icon.png", + "keywords": [ + "bun", + "node.js", + "javascript", + "typescript", + "vscode" + ], "license": "MIT", - "private": true, "publisher": "oven", "scripts": { - "build": "bunx esbuild src/extension.ts src/web-extension.ts --bundle --external:vscode --outdir=dist --platform=node --format=cjs", - "build:watch": "bunx esbuild --watch src/extension.ts src/web-extension.ts --bundle --external:vscode --outdir=dist --platform=node --format=cjs" + "bundle": "./node_modules/.bin/esbuild src/extension.ts src/web-extension.ts --bundle --external:vscode --outdir=dist --platform=node --format=cjs", + "prebuild": "bun run bundle && rm -rf extension && mkdir -p extension/src && cp -r dist extension/dist && cp -r src/assets extension/src/assets && cp package.json extension && cp README.md extension", + "build": "cd extension && vsce package", + "build:watch": "./node_modules/.bin/esbuild --watch src/extension.ts src/web-extension.ts --bundle --external:vscode --outdir=dist --platform=node --format=cjs" }, "workspaceTrust": { "request": "never" }, - "dependencies": { - "ws": "^8.13.0" - } + "workspaces": [ + "../bun-debug-adapter-protocol", + "../bun-inspector-protocol" + ] } diff --git a/packages/bun-vscode/src/activate.ts b/packages/bun-vscode/src/activate.ts deleted file mode 100644 index cbcb8cc1a..000000000 --- a/packages/bun-vscode/src/activate.ts +++ /dev/null @@ -1,118 +0,0 @@ -import * as vscode from "vscode"; -import { CancellationToken, DebugConfiguration, ProviderResult, WorkspaceFolder } from "vscode"; -import { DAPAdapter } from "./dap"; -import lockfile from "./lockfile"; - -export function activateBunDebug(context: vscode.ExtensionContext, factory?: vscode.DebugAdapterDescriptorFactory) { - lockfile(context); - - context.subscriptions.push( - vscode.commands.registerCommand("extension.bun.runEditorContents", (resource: vscode.Uri) => { - let targetResource = resource; - if (!targetResource && vscode.window.activeTextEditor) { - targetResource = vscode.window.activeTextEditor.document.uri; - } - if (targetResource) { - vscode.debug.startDebugging( - undefined, - { - type: "bun", - name: "Run File", - request: "launch", - program: targetResource.fsPath, - }, - { noDebug: true }, - ); - } - }), - vscode.commands.registerCommand("extension.bun.debugEditorContents", (resource: vscode.Uri) => { - let targetResource = resource; - if (!targetResource && vscode.window.activeTextEditor) { - targetResource = vscode.window.activeTextEditor.document.uri; - } - if (targetResource) { - vscode.debug.startDebugging(undefined, { - type: "bun", - name: "Debug File", - request: "launch", - program: targetResource.fsPath, - stopOnEntry: true, - }); - } - }), - ); - - context.subscriptions.push( - vscode.commands.registerCommand("extension.bun.getProgramName", config => { - return vscode.window.showInputBox({ - placeHolder: "Please enter the name of a file in the workspace folder", - value: "src/index.js", - }); - }), - ); - - const provider = new BunConfigurationProvider(); - context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider("bun", provider)); - - context.subscriptions.push( - vscode.debug.registerDebugConfigurationProvider( - "bun", - { - provideDebugConfigurations(folder: WorkspaceFolder | undefined): ProviderResult<DebugConfiguration[]> { - return [ - { - name: "Launch", - request: "launch", - type: "bun", - program: "${file}", - }, - ]; - }, - }, - vscode.DebugConfigurationProviderTriggerKind.Dynamic, - ), - ); - - if (!factory) { - factory = new InlineDebugAdapterFactory(); - } - context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory("bun", factory)); - if ("dispose" in factory) { - // @ts-expect-error ??? - context.subscriptions.push(factory); - } -} - -class BunConfigurationProvider implements vscode.DebugConfigurationProvider { - resolveDebugConfiguration( - folder: WorkspaceFolder | undefined, - config: DebugConfiguration, - token?: CancellationToken, - ): ProviderResult<DebugConfiguration> { - // if launch.json is missing or empty - if (!config.type && !config.request && !config.name) { - const editor = vscode.window.activeTextEditor; - if (editor && editor.document.languageId === "javascript") { - config.type = "bun"; - config.name = "Launch"; - config.request = "launch"; - config.program = "${file}"; - config.stopOnEntry = true; - } - } - - if (!config.program) { - return vscode.window.showInformationMessage("Cannot find a program to debug").then(_ => { - return undefined; // abort launch - }); - } - - return config; - } -} - -class InlineDebugAdapterFactory implements vscode.DebugAdapterDescriptorFactory { - createDebugAdapterDescriptor(_session: vscode.DebugSession): ProviderResult<vscode.DebugAdapterDescriptor> { - return new vscode.DebugAdapterInlineImplementation(new DAPAdapter(_session)); - } -} diff --git a/packages/bun-vscode/src/dap.ts b/packages/bun-vscode/src/dap.ts deleted file mode 100644 index efa7e08b4..000000000 --- a/packages/bun-vscode/src/dap.ts +++ /dev/null @@ -1,1305 +0,0 @@ -import * as vscode from "vscode"; -import { spawn, type ChildProcess } from "node:child_process"; -import { - ContinuedEvent, - InitializedEvent, - LoadedSourceEvent, - LoggingDebugSession, - OutputEvent, - StoppedEvent, - ThreadEvent, - Thread, - ExitedEvent, - TerminatedEvent, - Source, - BreakpointEvent, - DebugSession, -} from "@vscode/debugadapter"; -import type { DebugProtocol as DAP } from "@vscode/debugprotocol"; -import { JSCClient, type JSC } from "./jsc"; -import { isAbsolute } from "node:path"; - -const capabilities: Required<DAP.Capabilities> = { - /** The debug adapter supports the `configurationDone` request. */ - supportsConfigurationDoneRequest: true, - /** The debug adapter supports function breakpoints. */ - supportsFunctionBreakpoints: true, - /** The debug adapter supports conditional breakpoints. */ - supportsConditionalBreakpoints: true, - /** The debug adapter supports breakpoints that break execution after a specified number of hits. */ - supportsHitConditionalBreakpoints: true, // TODO - /** The debug adapter supports a (side effect free) `evaluate` request for data hovers. */ - supportsEvaluateForHovers: true, - /** Available exception filter options for the `setExceptionBreakpoints` request. */ - exceptionBreakpointFilters: [], - /** The debug adapter supports stepping back via the `stepBack` and `reverseContinue` requests. */ - supportsStepBack: false, - /** The debug adapter supports setting a variable to a value. */ - supportsSetVariable: false, // TODO - /** The debug adapter supports restarting a frame. */ - supportsRestartFrame: false, // TODO - /** The debug adapter supports the `gotoTargets` request. */ - supportsGotoTargetsRequest: false, // TODO - /** The debug adapter supports the `stepInTargets` request. */ - supportsStepInTargetsRequest: false, // TODO - /** The debug adapter supports the `completions` request. */ - supportsCompletionsRequest: false, // TODO - /** The set of characters that should trigger completion in a REPL. If not specified, the UI should assume the `.` character. */ - completionTriggerCharacters: [".", "[", '"', "'"], - /** The debug adapter supports the `modules` request. */ - supportsModulesRequest: true, - /** The set of additional module information exposed by the debug adapter. */ - additionalModuleColumns: [], - /** Checksum algorithms supported by the debug adapter. */ - supportedChecksumAlgorithms: [], - /** The debug adapter supports the `restart` request. In this case a client should not implement `restart` by terminating and relaunching the adapter but by calling the `restart` request. */ - supportsRestartRequest: false, - /** The debug adapter supports `exceptionOptions` on the `setExceptionBreakpoints` request. */ - supportsExceptionOptions: true, - /** The debug adapter supports a `format` attribute on the `stackTrace`, `variables`, and `evaluate` requests. */ - supportsValueFormattingOptions: false, // TODO - /** The debug adapter supports the `exceptionInfo` request. */ - supportsExceptionInfoRequest: true, - /** The debug adapter supports the `terminateDebuggee` attribute on the `disconnect` request. */ - supportTerminateDebuggee: true, - /** The debug adapter supports the `suspendDebuggee` attribute on the `disconnect` request. */ - supportSuspendDebuggee: false, - /** The debug adapter supports the delayed loading of parts of the stack, which requires that both the `startFrame` and `levels` arguments and the `totalFrames` result of the `stackTrace` request are supported. */ - supportsDelayedStackTraceLoading: true, - /** The debug adapter supports the `loadedSources` request. */ - supportsLoadedSourcesRequest: true, - /** The debug adapter supports log points by interpreting the `logMessage` attribute of the `SourceBreakpoint`. */ - supportsLogPoints: true, - /** The debug adapter supports the `terminateThreads` request. */ - supportsTerminateThreadsRequest: false, - /** The debug adapter supports the `setExpression` request. */ - supportsSetExpression: false, // TODO - /** The debug adapter supports the `terminate` request. */ - supportsTerminateRequest: true, - /** The debug adapter supports data breakpoints. */ - supportsDataBreakpoints: true, - /** The debug adapter supports the `readMemory` request. */ - supportsReadMemoryRequest: false, - /** The debug adapter supports the `writeMemory` request. */ - supportsWriteMemoryRequest: false, - /** The debug adapter supports the `disassemble` request. */ - supportsDisassembleRequest: false, - /** The debug adapter supports the `cancel` request. */ - supportsCancelRequest: false, - /** The debug adapter supports the `breakpointLocations` request. */ - supportsBreakpointLocationsRequest: true, - /** The debug adapter supports the `clipboard` context value in the `evaluate` request. */ - supportsClipboardContext: false, // TODO - /** The debug adapter supports stepping granularities (argument `granularity`) for the stepping requests. */ - supportsSteppingGranularity: false, // TODO - /** The debug adapter supports adding breakpoints based on instruction references. */ - supportsInstructionBreakpoints: true, - /** The debug adapter supports `filterOptions` as an argument on the `setExceptionBreakpoints` request. */ - supportsExceptionFilterOptions: false, // TODO - /** The debug adapter supports the `singleThread` property on the execution requests (`continue`, `next`, `stepIn`, `stepOut`, `reverseContinue`, `stepBack`). */ - supportsSingleThreadExecutionRequests: false, -}; - -const nodejsCapabilities: DAP.Capabilities = { - supportsConfigurationDoneRequest: true, - supportsFunctionBreakpoints: false, - supportsConditionalBreakpoints: true, - supportsHitConditionalBreakpoints: true, - supportsEvaluateForHovers: true, - supportsReadMemoryRequest: true, - supportsWriteMemoryRequest: true, - exceptionBreakpointFilters: [ - { - filter: "all", - label: "Caught Exceptions", - default: false, - supportsCondition: true, - description: "Breaks on all throw errors, even if they're caught later.", - conditionDescription: `error.name == "MyError"`, - }, - { - filter: "uncaught", - label: "Uncaught Exceptions", - default: false, - supportsCondition: true, - description: "Breaks only on errors or promise rejections that are not handled.", - conditionDescription: `error.name == "MyError"`, - }, - ], - supportsStepBack: false, - supportsSetVariable: true, - supportsRestartFrame: true, - supportsGotoTargetsRequest: false, - supportsStepInTargetsRequest: true, - supportsCompletionsRequest: true, - supportsModulesRequest: false, - additionalModuleColumns: [], - supportedChecksumAlgorithms: [], - supportsRestartRequest: true, - supportsExceptionOptions: false, - supportsValueFormattingOptions: true, - supportsExceptionInfoRequest: true, - supportTerminateDebuggee: true, - supportsDelayedStackTraceLoading: true, - supportsLoadedSourcesRequest: true, - supportsLogPoints: true, - supportsTerminateThreadsRequest: false, - supportsSetExpression: true, - supportsTerminateRequest: false, - completionTriggerCharacters: [".", "[", '"', "'"], - supportsBreakpointLocationsRequest: true, - supportsClipboardContext: true, - supportsExceptionFilterOptions: true, - //supportsEvaluationOptions: extended ? true : false, - //supportsDebuggerProperties: extended ? true : false, - //supportsSetSymbolOptions: extended ? true : false, - //supportsDataBreakpoints: false, - //supportsDisassembleRequest: false, -}; - -export type LaunchRequestArguments = DAP.LaunchRequestArguments & { - program: string; -}; - -export type AttachRequestArguments = DAP.AttachRequestArguments & { - url?: string; - port?: number; -}; - -export class DAPAdapter extends LoggingDebugSession implements Context { - #session: vscode.DebugSession; - #pendingSources = new Map<string, Array<{ resolve: Function; reject: Function }>>(); - #client?: JSCClient; - #process?: ChildProcess; - #thread?: DAP.Thread; - #ready: AbortController; - #sources: Map<string, DAP.Source>; - #scriptIds: Map<number, number>; - #stackFrames: DAP.StackFrame[]; - #scopes: Map<number, DAP.Scope[]>; - #frameIds = new Array<string>(64); - #callFrames = new Array<JSC.Debugger.CallFrame>(64); - #callFramesRange = [0, 0]; - - public constructor(session: vscode.DebugSession) { - super(); - this.#resumePromise = new Promise(resolve => { - this.#resume = resolve; - }); - - this.#ready = new AbortController(); - this.#session = session; - this.#sources = new Map(); - this.#scriptIds = new Map(); - this.#stackFrames = []; - this.#scopes = new Map(); - // 1-based lines and columns - this.setDebuggerLinesStartAt1(true); - this.setDebuggerColumnsStartAt1(false); - } - - #ack<R extends DAP.Response = DAP.Response>(response: R, extra?: Partial<R>["body"]): void { - this.sendResponse({ ...response, body: extra, success: true }); - } - - #nack(response: DAP.Response, error?: unknown): void { - const message = error instanceof Error ? error.message : String(error); - this.sendResponse({ ...response, success: false, message }); - } - - #todo(response: DAP.Response, label: string): void { - this.#nack(response, `TODO: ${label}`); - } - - #noop(response: DAP.Response, label: string): void { - this.#nack(response, `Not supported: ${label}`); - } - - async #send<R extends DAP.Response, T extends keyof JSC.RequestMap>( - response: R, - method: T, - params?: JSC.Request<T>["params"], - callback?: (result: JSC.ResponseMap[T]) => Partial<R["body"]> | void, - ) { - try { - const result = await this.#client.fetch(method, params); - const ack = callback?.(result); - if (ack) { - this.#ack(response, ack); - } else { - this.#ack(response); - } - } catch (error) { - console.error(error); - this.#nack(response, error); - } - } - - getReferenceId(objectId: string): number { - try { - const { injectedScriptId, id } = JSON.parse(objectId); - const referenceId = Number(`${injectedScriptId}${id}`); - if (isNaN(referenceId)) { - throw new Error(); - } - return referenceId; - } catch { - return hashCode(objectId); - } - } - - getObjectId(referenceId: number): string { - const objectId = String(referenceId); - try { - const injectedScriptId = Number(objectId.slice(0, 1)); - const id = Number(objectId.slice(1)); - return JSON.stringify({ injectedScriptId, id }); - } catch { - return objectId; - } - } - - getStackFrameId(callFrameId: string): number { - try { - const { injectedScriptId, ordinal } = JSON.parse(callFrameId); - const frameId = Number(`${injectedScriptId}${ordinal}`); - if (isNaN(frameId)) { - throw new Error(); - } - return frameId; - } catch { - return hashCode(callFrameId); - } - } - - getCallFrameId(stackFrameId: number): string { - const objectId = String(stackFrameId); - try { - const injectedScriptId = Number(objectId.slice(0, 1)); - const ordinal = Number(objectId.slice(1)); - return JSON.stringify({ injectedScriptId, ordinal }); - } catch { - return objectId; - } - } - - getSource(scriptId: string): DAP.Source | undefined { - return this.#sources.get(scriptId); - } - - getModuleId(scriptId: string): number | undefined { - return undefined; // TODO - } - - async getProperties(objectId: string): Promise<JSC.Runtime.PropertyDescriptor[]> { - const { properties } = await this.#client.fetch("Runtime.getDisplayableProperties", { - objectId, - }); - let hasEntries = false; - for (const { name } of properties) { - if (name === "entries") { - hasEntries = true; - } - // HACK: Do not call on arrays, as it appears to error the debugger. - // Internal error [code: -32000] - if (name === "at") { - hasEntries = false; - break; - } - } - if (!hasEntries) { - return properties; - } - const { entries } = await this.#client.fetch("Runtime.getCollectionEntries", { - objectId, - }); - const results: JSC.Runtime.PropertyDescriptor[] = [...properties.reverse()]; - for (let i = entries.length - 1; i >= 0; i--) { - const { key, value } = entries[i]; - results.push({ - name: key?.description ?? `${i}`, - value, - }); - } - return results.reverse(); - } - - protected onEvent(event: JSC.Event): void { - console.log(Date.now(), "JSC Event:", event); - const { method, params } = event; - this[method]?.(params); - } - - protected ["Debugger.scriptParsed"](event: JSC.Debugger.ScriptParsedEvent): void { - let { sourceURL, url, scriptId } = event; - - if (!url) { - url = sourceURL; - } - - if (!url) { - return; // If the script has no URL, it is an `eval` command. - } - - const name = vscode.workspace.asRelativePath(url); - const scriptIdNumber = scriptIdFromEvent(scriptId); - const source = new Source(name, url, scriptIdNumber); - source.sourceReference = scriptIdNumber; - this.#sources.set(scriptId, source); - this.#scriptIds.set(hashCode(url), scriptIdNumber); - this.sendEvent(new LoadedSourceEvent("new", source)); - const pendingMap = this.#pendingSources; - const promises = pendingMap.get(url); - if (promises) { - pendingMap.delete(url); - for (const { resolve } of promises) { - resolve(); - } - } - - if (!this.#thread) { - this.#thread = new Thread(0, url); - this.sendEvent(new ThreadEvent("started", 0)); - } - } - - protected ["Debugger.paused"](event: JSC.Debugger.PausedEvent): void { - const { reason, callFrames, asyncStackTrace } = event; - - this.sendEvent(new StoppedEvent(pauseReason(reason), this.#thread?.id ?? 0)); - const stackFrames: DAP.StackFrame[] = []; - const scopes: Map<number, DAP.Scope[]> = new Map(); - const frameIds = this.#frameIds; - frameIds.length = - callFrames.length + - (asyncStackTrace?.callFrames?.length || 0) + - (asyncStackTrace?.parentStackTrace?.callFrames?.length || 0); - const frames = this.#callFrames; - frames.length = callFrames.length; - let frameId = 0; - for (const callFrame of callFrames) { - const stackFrame = formatStackFrame(this, callFrame); - frames[frameId] = callFrame; - frameIds[frameId++] = callFrame.callFrameId; - stackFrames.push(stackFrame); - const frameScopes: DAP.Scope[] = []; - for (const scope of callFrame.scopeChain) { - frameScopes.push(...formatScope(this, scope)); - } - scopes.set(stackFrame.id, frameScopes); - } - - if (asyncStackTrace?.callFrames?.length) { - for (const callFrame of asyncStackTrace.callFrames) { - frameIds[frameId++] = ""; - stackFrames.push(formatAsyncStackFrame(this, callFrame)); - } - } - - if (asyncStackTrace?.parentStackTrace?.callFrames?.length) { - for (const callFrame of asyncStackTrace.parentStackTrace.callFrames) { - frameIds[frameId++] = ""; - stackFrames.push(formatAsyncStackFrame(this, callFrame)); - } - } - this.#scopes = scopes; - this.#stackFrames = stackFrames; - } - - protected ["Debugger.resumed"](event: JSC.Debugger.ResumedEvent): void { - this.#frameIds.length = 0; - this.#callFrames.length = 0; - this.sendEvent(new ContinuedEvent(this.#thread?.id)); - } - - handleMessage(message: DAP.ProtocolMessage): void { - console.log(Date.now(), "DAP Request:", message); - super.handleMessage(message); - } - - sendResponse(response: DAP.Response): void { - console.log(Date.now(), "DAP Response:", response); - super.sendResponse(response); - } - - sendEvent(event: DAP.Event): void { - console.log(Date.now(), "DAP Event:", event); - super.sendEvent(event); - } - - runInTerminalRequest( - args: DAP.RunInTerminalRequestArguments, - timeout: number, - cb: (response: DAP.RunInTerminalResponse) => void, - ): void { - // TODO - } - - protected initializeRequest(response: DAP.InitializeResponse, args: DAP.InitializeRequestArguments): void { - this.#ack(response, nodejsCapabilities); - this.sendEvent(new InitializedEvent()); - } - - protected async disconnectRequest( - response: DAP.DisconnectResponse, - args: DAP.DisconnectArguments, - request?: DAP.Request, - ): Promise<void> { - await this.#client?.fetch("Debugger.disable"); - const { terminateDebuggee } = args; - if (terminateDebuggee) { - this.#process?.kill(); - } - await this.#ack(response); - } - - async #launch(path: string): Promise<void> { - this.#process?.kill(); - const url = "localhost:9232"; - // // TODO: Change to "bun" before merging, or make it configurable - // const process = spawn("bun-debug", ["--inspect=" + url, "run", path], { - // cwd: this.#session.workspaceFolder?.uri?.fsPath, - // stdio: ["ignore", "pipe", "pipe"], - // env: { - // ...globalThis.process.env, - // NODE_ENV: "development", - // BUN_DEBUG_QUIET_LOGS: "1", - // FORCE_COLOR: "1", - // }, - // }); - // let resolve, - // reject, - // promise = new Promise<void>((res, rej) => { - // resolve = res; - // reject = rej; - // }); - // process.on("error", error => { - // console.error(error); - - // vscode.window.showErrorMessage(`Failed to start Bun: ${error.message}`); - // this.sendEvent(new ExitedEvent(-1)); - // this.#process = undefined; - // reject(error); - // }); - // process.on("exit", exitCode => { - // this.sendEvent(new ExitedEvent(exitCode)); - // this.#process = undefined; - // }); - // process.stdout.on("data", (data: Buffer) => { - // console.log(data); - // this.sendEvent(new OutputEvent(data.toString(), "stdout")); - // }); - // process.stderr.on("data", (data: Buffer) => { - // console.error(data); - // this.sendEvent(new OutputEvent(data.toString(), "stderr")); - // }); - // this.#process = process; - - // process.once("spawn", () => { - // this.#attach(url).then(resolve, reject); - // }); - return this.#attach(url); - } - - async #attach(url: string): Promise<void> { - this.#client?.close(); - const client = new JSCClient({ - url, - onEvent: this.onEvent.bind(this), - onResponse(response) { - console.log(Date.now(), "JSC Response:", response); - }, - onRequest(request) { - console.log(Date.now(), "JSC Request:", request); - }, - onError(error) { - console.error("JSC Error:", error); - }, - onClose(code, reason) { - console.log(Date.now(), "JSC Close:", code, reason); - this.#process?.kill(); - }, - }); - this.#client = client; - globalThis.jsc = client; - await client.ready; - await Promise.all([ - client.fetch("Runtime.enable"), - client.fetch("Console.enable"), - client.fetch("Debugger.enable"), - client.fetch("Debugger.setAsyncStackTraceDepth", { depth: 100 }), - client.fetch("Debugger.setPauseOnDebuggerStatements", { enabled: true }), - client.fetch("Debugger.setBreakpointsActive", { active: true }), - ]); - } - - protected async launchRequest( - response: DAP.LaunchResponse, - args: LaunchRequestArguments, - request?: DAP.Request, - ): Promise<void> { - await new Promise<void>(resolve => { - if (this.#ready.signal.aborted) { - resolve(); - return; - } - this.#ready.signal.addEventListener("abort", () => { - resolve(); - }); - }); - const { program } = args; - try { - await this.#launch(program); - this.#ack(response); - } catch (error) { - this.#nack(response, error); - } - } - - #resume = undefined; - #resumePromise = undefined; - - protected async attachRequest( - response: DAP.AttachResponse, - args: AttachRequestArguments, - request?: DAP.Request, - ): Promise<void> { - console.log("Attach!"); - const { url, port } = args; - try { - if (url) { - await this.#attach(url); - } else if (port) { - await this.#attach(`localhost:${port}`); - } else { - await this.#attach("localhost:9229"); - } - this.#resume(); - this.#ack(response); - } catch (error) { - this.#nack(response, error); - } - } - - protected terminateRequest( - response: DAP.TerminateResponse, - args: DAP.TerminateArguments, - request?: DAP.Request, - ): void { - this.#client?.close(); - this.sendEvent(new TerminatedEvent()); - this.#ack(response); - } - - protected restartRequest(response: DAP.RestartResponse, args: DAP.RestartArguments, request?: DAP.Request): void { - this.#noop(response, "restartRequest"); - } - - getScriptIdFromSource(source: DAP.Source): string { - if (source.sourceReference) { - return String(source.sourceReference); - } - - // @ts-expect-error - if (source.sourceReferenceInternal) { - // @ts-expect-error - return String(source.sourceReferenceInternal); - } - - const { path } = source; - const id = this.#scriptIds.get(hashCode(path)); - if (!id) { - return undefined; - } - - return String(id); - } - - async waitForSourceToBeLoaded(source: DAP.Source): Promise<void> { - const pendingMap = this.#pendingSources; - let promises = pendingMap.get(source.path); - if (!promises) { - promises = []; - pendingMap.set(source.path, promises); - } - - await new Promise<void>((resolve, reject) => { - promises.push({ resolve, reject }); - }); - } - - protected async setBreakPointsRequest( - response: DAP.SetBreakpointsResponse, - args: DAP.SetBreakpointsArguments, - request?: DAP.Request, - ): Promise<void> { - if (!args.breakpoints?.length) { - this.#nack(response, "No breakpoints"); - return; - } - if (!this.#client) { - await this.#resumePromise; - } - - const { source, breakpoints } = args; - let scriptId = this.getScriptIdFromSource(source); - - if (!scriptId) { - await this.waitForSourceToBeLoaded(source); - scriptId = this.getScriptIdFromSource(source); - } - - const results: DAP.Breakpoint[] = await Promise.all( - breakpoints.map(({ line, column }) => - this.#client - .fetch("Debugger.setBreakpoint", { - location: { - scriptId, - lineNumber: line, - columnNumber: column, - }, - }) - .then( - ({ breakpointId, actualLocation }) => { - return { - id: Number(breakpointId), - line: actualLocation.lineNumber, - // column: actualLocation.columnNumber, - verified: true, - }; - }, - err => { - if (err?.code === -32000) { - return undefined; - } - - throw err; - }, - ), - ), - ); - this.#ack(response, { breakpoints: results.filter(Boolean) }); - } - - protected setFunctionBreakPointsRequest( - response: DAP.SetFunctionBreakpointsResponse, - args: DAP.SetFunctionBreakpointsArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "setFunctionBreakPointsRequest"); - } - - protected setExceptionBreakPointsRequest( - response: DAP.SetExceptionBreakpointsResponse, - args: DAP.SetExceptionBreakpointsArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "setExceptionBreakPointsRequest"); - } - - protected configurationDoneRequest( - response: DAP.ConfigurationDoneResponse, - args: DAP.ConfigurationDoneArguments, - request?: DAP.Request, - ): void { - super.configurationDoneRequest(response, args, request); - this.#ready.abort(); - // this.#ack(response); - } - - protected async continueRequest( - response: DAP.ContinueResponse, - args: DAP.ContinueArguments, - request?: DAP.Request, - ): Promise<void> { - await this.#send(response, "Debugger.resume"); - } - - protected async nextRequest( - response: DAP.NextResponse, - args: DAP.NextArguments, - request?: DAP.Request, - ): Promise<void> { - await this.#send(response, "Debugger.stepNext"); - } - - protected async stepInRequest( - response: DAP.StepInResponse, - args: DAP.StepInArguments, - request?: DAP.Request, - ): Promise<void> { - await this.#send(response, "Debugger.stepInto"); - } - - protected async stepOutRequest( - response: DAP.StepOutResponse, - args: DAP.StepOutArguments, - request?: DAP.Request, - ): Promise<void> { - await this.#send(response, "Debugger.stepOut"); - } - - protected stepBackRequest(response: DAP.StepBackResponse, args: DAP.StepBackArguments, request?: DAP.Request): void { - this.#todo(response, "stepBackRequest"); - } - - protected reverseContinueRequest( - response: DAP.ReverseContinueResponse, - args: DAP.ReverseContinueArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "reverseContinueRequest"); - } - - protected restartFrameRequest( - response: DAP.RestartFrameResponse, - args: DAP.RestartFrameArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "restartFrameRequest"); - } - - protected gotoRequest(response: DAP.GotoResponse, args: DAP.GotoArguments, request?: DAP.Request): void { - this.#todo(response, "gotoRequest"); - } - - protected pauseRequest(response: DAP.PauseResponse, args: DAP.PauseArguments, request?: DAP.Request): void { - this.#send(response, "Debugger.pause"); - } - - protected async sourceRequest( - response: DAP.SourceResponse, - args: DAP.SourceArguments, - request?: DAP.Request, - ): Promise<void> { - const { sourceReference, source } = args; - const scriptId = sourceReference ? String(sourceReference) : this.getScriptIdFromSource(source); - - await this.#send(response, "Debugger.getScriptSource", { scriptId }, ({ scriptSource }) => ({ - content: scriptSource, - })); - } - - protected threadsRequest(response: DAP.ThreadsResponse, request?: DAP.Request): void { - if (this.#thread) { - this.#ack(response, { threads: [this.#thread] }); - } else { - this.#ack(response, { threads: [] }); - } - } - - protected terminateThreadsRequest( - response: DAP.TerminateThreadsResponse, - args: DAP.TerminateThreadsArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "terminateThreadsRequest"); - } - - protected stackTraceRequest( - response: DAP.StackTraceResponse, - args: DAP.StackTraceArguments, - request?: DAP.Request, - ): void { - const totalFrames = this.#stackFrames.length; - const { startFrame = 0, levels = totalFrames } = args; - const stackFrames = this.#stackFrames.slice( - (this.#callFramesRange[0] = startFrame), - (this.#callFramesRange[1] = Math.min(totalFrames, startFrame + levels)), - ); - - this.#ack(response, { - stackFrames, - totalFrames, - }); - } - - protected scopesRequest(response: DAP.ScopesResponse, args: DAP.ScopesArguments, request?: DAP.Request): void { - const { frameId } = args; - const scopes = this.#scopes.get(frameId) ?? []; - this.#ack(response, { scopes }); - } - - protected async variablesRequest( - response: DAP.VariablesResponse, - args: DAP.VariablesArguments, - request?: DAP.Request, - ): Promise<void> { - const { variablesReference } = args; - const objectId = this.getObjectId(variablesReference); - try { - const variables = await formatObject(this, objectId); - this.#ack(response, { variables }); - } catch (error) { - this.#nack(response, error); - } - } - - protected setVariableRequest( - response: DAP.SetVariableResponse, - args: DAP.SetVariableArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "setVariableRequest"); - } - - protected setExpressionRequest( - response: DAP.SetExpressionResponse, - args: DAP.SetExpressionArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "setExpressionRequest"); - } - - protected async evaluateRequest( - response: DAP.EvaluateResponse, - args: DAP.EvaluateArguments, - request?: DAP.Request, - ): Promise<void> { - const { context, expression, frameId } = args; - let callFrame: JSC.Debugger.CallFrame = - typeof frameId === "number" - ? this.#callFrames[this.#stackFrames.findIndex(frame => frame.id === frameId)] - : undefined; - - if (callFrame && context === "hover") { - if (expression.includes(".")) { - // TODO: use getDisplayableProperties to make this side-effect free. - // for each ".", call Runtime.getProperties on the previous result and find the specific property - await this.#send( - response, - "Debugger.evaluateOnCallFrame", - { - expression, - callFrameId: callFrame.callFrameId, - "includeCommandLineAPI": false, - }, - ({ result: { objectId, value, description }, wasThrown }) => { - return { - result: value ?? description, - variablesReference: objectId ? this.getReferenceId(objectId) : 0, - }; - }, - ); - } else { - for (let scope of callFrame.scopeChain) { - if (scope.empty || scope.type === "with" || scope.type === "global") { - continue; - } - - // For the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. - const { properties } = await this.#client.fetch("Runtime.getDisplayableProperties", { - "objectId": scope.object.objectId, - "fetchStart": 0, - "fetchCount": 100, - }); - - for (let i = 0; i < properties.length; i++) { - const prop = properties[i]; - const { name, value } = prop; - if (name === expression) { - if (value) { - const { objectId } = value; - response.body = { - result: value?.value || value?.description || "", - variablesReference: objectId ? this.getReferenceId(objectId) : 0, - type: value?.type || "undefined", - presentationHint: presentationHintForProperty(prop, !!value.classPrototype), - }; - } else { - response.body = { - result: "undefined", - variablesReference: 0, - type: "undefined", - }; - } - response.success = true; - this.sendResponse(response); - return; - } - } - } - } - } else { - await this.#send( - response, - "Runtime.evaluate", - { - expression, - includeCommandLineAPI: true, - }, - ({ result: { objectId, value, description }, wasThrown }) => { - return { - result: value ?? description, - variablesReference: objectId ? this.getReferenceId(objectId) : 0, - }; - }, - ); - } - } - - protected stepInTargetsRequest( - response: DAP.StepInTargetsResponse, - args: DAP.StepInTargetsArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "stepInTargetsRequest"); - } - - protected gotoTargetsRequest( - response: DAP.GotoTargetsResponse, - args: DAP.GotoTargetsArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "gotoTargetsRequest"); - } - - protected completionsRequest( - response: DAP.CompletionsResponse, - args: DAP.CompletionsArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "completionsRequest"); - } - - protected exceptionInfoRequest( - response: DAP.ExceptionInfoResponse, - args: DAP.ExceptionInfoArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "exceptionInfoRequest"); - } - - protected loadedSourcesRequest( - response: DAP.LoadedSourcesResponse, - args: DAP.LoadedSourcesArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "loadedSourcesRequest"); - } - - protected dataBreakpointInfoRequest( - response: DAP.DataBreakpointInfoResponse, - args: DAP.DataBreakpointInfoArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "dataBreakpointInfoRequest"); - } - - protected setDataBreakpointsRequest( - response: DAP.SetDataBreakpointsResponse, - args: DAP.SetDataBreakpointsArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "setDataBreakpointsRequest"); - } - - protected readMemoryRequest( - response: DAP.ReadMemoryResponse, - args: DAP.ReadMemoryArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "readMemoryRequest"); - } - - protected writeMemoryRequest( - response: DAP.WriteMemoryResponse, - args: DAP.WriteMemoryArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "writeMemoryRequest"); - } - - protected disassembleRequest( - response: DAP.DisassembleResponse, - args: DAP.DisassembleArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "disassembleRequest"); - } - - protected cancelRequest(response: DAP.CancelResponse, args: DAP.CancelArguments, request?: DAP.Request): void { - this.#todo(response, "cancelRequest"); - } - - protected async breakpointLocationsRequest( - response: DAP.BreakpointLocationsResponse, - args: DAP.BreakpointLocationsArguments, - request?: DAP.Request, - ): Promise<void> { - const { line, endLine, column, endColumn, source } = args; - console.log(source); - let scriptId: string = this.getScriptIdFromSource(source); - if (!scriptId) { - await this.waitForSourceToBeLoaded(source); - scriptId = this.getScriptIdFromSource(source); - } - - if (!scriptId) { - this.#nack(response, new Error("Either source.path or source.sourceReference must be specified")); - return; - } - - await this.#send( - response, - "Debugger.getBreakpointLocations", - { - start: { - scriptId, - lineNumber: line, - columnNumber: column, - }, - end: { - scriptId, - lineNumber: endLine ?? line + 1, - columnNumber: endColumn, - }, - }, - ({ locations }) => { - return { - breakpoints: locations.map(({ lineNumber, columnNumber }) => ({ - line: lineNumber, - column: columnNumber, - })), - }; - }, - ); - } - - protected setInstructionBreakpointsRequest( - response: DAP.SetInstructionBreakpointsResponse, - args: DAP.SetInstructionBreakpointsArguments, - request?: DAP.Request, - ): void { - this.#todo(response, "setInstructionBreakpointsRequest"); - } - - protected customRequest(command: string, response: DAP.Response, args: any, request?: DAP.Request): void { - super.customRequest(command, response, args, request); - } - - protected convertClientLineToDebugger(line: number): number { - return line; - } - - protected convertDebuggerLineToClient(line: number): number { - return line; - } - - protected convertClientColumnToDebugger(column: number): number { - return column; - } - - protected convertDebuggerColumnToClient(column: number): number { - return column; - } - - protected convertClientPathToDebugger(clientPath: string): string { - return clientPath; - } - - protected convertDebuggerPathToClient(debuggerPath: string): string { - return debuggerPath; - } -} - -function hashCode(string: string): number { - let hash = 0, - i, - chr; - if (string.length === 0) return hash; - for (i = 0; i < string.length; i++) { - chr = string.charCodeAt(i); - hash = (hash << 5) - hash + chr; - hash |= 0; - } - return hash; -} - -interface Context { - getReferenceId(objectId: string): number; - getObjectId(referenceId: number): string; - getStackFrameId(callFrameId: string): number; - getCallFrameId(stackFrameId: number): string; - getSource(scriptId: string): DAP.Source | undefined; - getModuleId(scriptId: string): number | undefined; - getProperties(objectId: string): Promise<JSC.Runtime.PropertyDescriptor[]>; -} - -function formatStackFrame(ctx: Context, callFrame: JSC.Debugger.CallFrame): DAP.StackFrame { - const { callFrameId, functionName, location } = callFrame; - const { scriptId, lineNumber, columnNumber = 0 } = location; - const source = ctx.getSource(scriptId); - return { - id: ctx.getStackFrameId(callFrameId), - name: functionName || "<anonymous>", - line: lineNumber, - column: columnNumber, - source, - moduleId: ctx.getModuleId(scriptId), - presentationHint: source?.presentationHint || !source?.path ? "subtle" : "normal", - }; -} - -function formatAsyncStackFrame(ctx: Context, callFrame: JSC.Console.CallFrame): DAP.StackFrame { - const { functionName, scriptId, lineNumber, columnNumber } = callFrame; - return { - id: hashCode(functionName + "-" + scriptId + "-" + lineNumber + "-" + columnNumber), - name: functionName || "<anonymous>", - line: lineNumber, - column: columnNumber, - source: ctx.getSource(scriptId), - moduleId: scriptId, - }; -} - -function formatScope(ctx: Context, scope: JSC.Debugger.Scope): DAP.Scope[] { - const { name, type, location, object, empty } = scope; - if (empty) { - return []; - } - const presentationHint = formatScopeHint(type); - const title = presentationHint.charAt(0).toUpperCase() + presentationHint.slice(1); - const displayName = name ? `${title}: ${name}` : title; - return [ - { - name: displayName, - presentationHint, - expensive: presentationHint === "globals", - variablesReference: object ? ctx.getReferenceId(object.objectId) : 0, - line: location?.lineNumber, - column: location?.columnNumber, - source: location && ctx.getSource(location.scriptId), - }, - ]; -} - -function formatScopeHint(type: JSC.Debugger.Scope["type"]): "arguments" | "locals" | "globals" | "" { - switch (type) { - case "closure": - return "locals"; // ? - case "functionName": - case "with": - case "catch": - case "nestedLexical": - return "locals"; - case "global": - case "globalLexicalEnvironment": - return "globals"; - default: - return ""; - } -} - -async function formatObject(ctx: Context, objectId: JSC.Runtime.RemoteObjectId): Promise<DAP.Variable[]> { - const properties = await ctx.getProperties(objectId); - return properties.flatMap(property => formatProperty(ctx, property)); -} - -function formatProperty(ctx: Context, propertyDescriptor: JSC.Runtime.PropertyDescriptor): DAP.Variable[] { - const { name, value, get, set, symbol, isOwn } = propertyDescriptor; - const variables: DAP.Variable[] = []; - if (value) { - variables.push(formatPropertyValue(ctx, name, value, propertyDescriptor)); - } - return variables; -} - -function formatPropertyValue( - ctx: Context, - name: string, - remoteObject: JSC.Runtime.RemoteObject, - descriptor: JSC.Runtime.PropertyDescriptor, -): DAP.Variable { - const { type, subtype, value, description, objectId } = remoteObject; - return { - name, - value: description ?? "", - type: subtype ?? type, - variablesReference: objectId ? ctx.getReferenceId(objectId) : 0, - presentationHint: - value && typeof value !== "object" && typeof value !== "undefined" - ? formatPropertyHint(descriptor, typeof value) - : formatPropertyHint(value || descriptor, ""), - }; -} - -function formatPropertyHint( - propertyDescriptor: JSC.Runtime.PropertyDescriptor, - valueType: string, -): DAP.VariablePresentationHint { - const { value, get, set, configurable, enumerable, writable, isOwn } = propertyDescriptor; - const hasGetter = get?.type !== "undefined"; - const hasSetter = set?.type !== "undefined"; - const hint: DAP.VariablePresentationHint = { - kind: (value && formatPropertyKind(value)) ?? "property", - attributes: [], - visibility: "public", - }; - if (!writable && !hasSetter && hasGetter) { - hint.attributes.push("readOnly"); - } - if (!enumerable && !hasGetter) { - hint.visibility = "internal"; - } - - if (valueType) { - hint.kind = "data"; - } - - return hint; -} - -function formatPropertyKind(remoteObject: JSC.Runtime.RemoteObject): DAP.VariablePresentationHint["kind"] { - const { type, subtype, className, value } = remoteObject; - if (type === "function") { - return "method"; - } - if (subtype === "class") { - return "class"; - } - if (className?.endsWith("Event")) { - return "event"; - } - if (value) { - return "data"; - } - - return "property"; -} - -function scriptIdFromLocation(location: JSC.Debugger.Location): number { - const id = Number(location.scriptId); - console.log({ id }); - return id; -} - -function pauseReason(reason: JSC.EventMap["Debugger.paused"]["reason"]): DAP.StoppedEvent["body"]["reason"] { - return reason; -} - -function scriptIdFromEvent(scriptId: JSC.Debugger.ScriptParsedEvent["scriptId"]): number { - return Number(scriptId); -} - -function presentationHintForProperty(property: JSC.Runtime.PropertyDescriptor, isClass): DAP.VariablePresentationHint { - const attributes = []; - if (!property.writable) { - attributes.push("readOnly"); - } - - let kind = ""; - if (isClass) { - kind = "class"; - } else if (property.get || property.set) { - kind = "property"; - } else if (property.value) { - kind = "data"; - } - - return { - attributes, - visibility: property.isPrivate || property.symbol || !property.enumerable ? "private" : "public", - kind, - }; -} diff --git a/packages/bun-vscode/src/extension.ts b/packages/bun-vscode/src/extension.ts index f840dd7a9..e333aedd7 100644 --- a/packages/bun-vscode/src/extension.ts +++ b/packages/bun-vscode/src/extension.ts @@ -1,16 +1,10 @@ import * as vscode from "vscode"; -import { activateBunDebug } from "./activate"; - -const runMode: "external" | "server" | "namedPipeServer" | "inline" = "inline"; +import activateLockfile from "./features/lockfile"; +import activateDebug from "./features/debug"; export function activate(context: vscode.ExtensionContext) { - if (runMode === "inline") { - activateBunDebug(context); - return; - } - throw new Error(`This extension does not support '${runMode}' mode.`); + activateLockfile(context); + activateDebug(context); } -export function deactivate() { - // No-op -} +export function deactivate() {} diff --git a/packages/bun-vscode/src/features/debug.ts b/packages/bun-vscode/src/features/debug.ts new file mode 100644 index 000000000..3b841ea66 --- /dev/null +++ b/packages/bun-vscode/src/features/debug.ts @@ -0,0 +1,153 @@ +import * as vscode from "vscode"; +import type { CancellationToken, DebugConfiguration, ProviderResult, WorkspaceFolder } from "vscode"; +import type { DAP } from "../../../bun-debug-adapter-protocol"; +import { DebugAdapter } from "../../../bun-debug-adapter-protocol"; +import { DebugSession } from "@vscode/debugadapter"; + +const debugConfiguration: vscode.DebugConfiguration = { + type: "bun", + request: "launch", + name: "Debug Bun", + program: "${file}", + watch: true, +}; + +const runConfiguration: vscode.DebugConfiguration = { + type: "bun", + request: "launch", + name: "Run Bun", + program: "${file}", + watch: true, +}; + +const attachConfiguration: vscode.DebugConfiguration = { + type: "bun", + request: "attach", + name: "Attach to Bun", + url: "ws://localhost:6499/", +}; + +const debugConfigurations: vscode.DebugConfiguration[] = [debugConfiguration, attachConfiguration]; + +export default function (context: vscode.ExtensionContext, factory?: vscode.DebugAdapterDescriptorFactory) { + context.subscriptions.push( + vscode.commands.registerCommand("extension.bun.runFile", (resource: vscode.Uri) => { + let targetResource = resource; + if (!targetResource && vscode.window.activeTextEditor) { + targetResource = vscode.window.activeTextEditor.document.uri; + } + if (targetResource) { + vscode.debug.startDebugging(undefined, runConfiguration, { + noDebug: true, + }); + } + }), + vscode.commands.registerCommand("extension.bun.debugFile", (resource: vscode.Uri) => { + let targetResource = resource; + if (!targetResource && vscode.window.activeTextEditor) { + targetResource = vscode.window.activeTextEditor.document.uri; + } + if (targetResource) { + vscode.debug.startDebugging(undefined, { + ...debugConfiguration, + program: targetResource.fsPath, + }); + } + }), + ); + + const provider = new BunConfigurationProvider(); + context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider("bun", provider)); + + context.subscriptions.push( + vscode.debug.registerDebugConfigurationProvider( + "bun", + { + provideDebugConfigurations(folder: WorkspaceFolder | undefined): ProviderResult<DebugConfiguration[]> { + return debugConfigurations; + }, + }, + vscode.DebugConfigurationProviderTriggerKind.Dynamic, + ), + ); + + if (!factory) { + factory = new InlineDebugAdapterFactory(); + } + context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory("bun", factory)); + if ("dispose" in factory && typeof factory.dispose === "function") { + // @ts-ignore + context.subscriptions.push(factory); + } +} + +class BunConfigurationProvider implements vscode.DebugConfigurationProvider { + resolveDebugConfiguration( + folder: WorkspaceFolder | undefined, + config: DebugConfiguration, + token?: CancellationToken, + ): ProviderResult<DebugConfiguration> { + if (!config.type && !config.request && !config.name) { + const editor = vscode.window.activeTextEditor; + if (editor && isJavaScript(editor.document.languageId)) { + Object.assign(config, debugConfiguration); + } + } + return config; + } +} + +class InlineDebugAdapterFactory implements vscode.DebugAdapterDescriptorFactory { + createDebugAdapterDescriptor(_session: vscode.DebugSession): ProviderResult<vscode.DebugAdapterDescriptor> { + const adapter = new VSCodeAdapter(_session); + return new vscode.DebugAdapterInlineImplementation(adapter); + } +} + +function isJavaScript(languageId: string): boolean { + return ( + languageId === "javascript" || + languageId === "javascriptreact" || + languageId === "typescript" || + languageId === "typescriptreact" + ); +} + +export class VSCodeAdapter extends DebugSession { + #adapter: DebugAdapter; + #dap: vscode.OutputChannel; + + constructor(session: vscode.DebugSession) { + super(); + this.#dap = vscode.window.createOutputChannel("Debug Adapter Protocol"); + this.#adapter = new DebugAdapter({ + sendToAdapter: this.sendMessage.bind(this), + }); + } + + sendMessage(message: DAP.Request | DAP.Response | DAP.Event): void { + console.log("[dap] -->", message); + this.#dap.appendLine("--> " + JSON.stringify(message)); + + const { type } = message; + if (type === "response") { + this.sendResponse(message); + } else if (type === "event") { + this.sendEvent(message); + } else { + throw new Error(`Not supported: ${type}`); + } + } + + handleMessage(message: DAP.Event | DAP.Request | DAP.Response): void { + console.log("[dap] <--", message); + this.#dap.appendLine("<-- " + JSON.stringify(message)); + + this.#adapter.accept(message); + } + + dispose() { + this.#adapter.close(); + this.#dap.dispose(); + } +} diff --git a/packages/bun-vscode/src/lockfile.ts b/packages/bun-vscode/src/features/lockfile.ts index 22b48faba..81adf5b9e 100644 --- a/packages/bun-vscode/src/lockfile.ts +++ b/packages/bun-vscode/src/features/lockfile.ts @@ -52,10 +52,10 @@ function previewLockfile(uri: vscode.Uri, token?: vscode.CancellationToken): Pro process.stderr.on("data", (data: Buffer) => { stderr += data.toString(); }); - process.on("error", (error) => { + process.on("error", error => { reject(error); }); - process.on("exit", (code) => { + process.on("exit", code => { if (code === 0) { resolve(stdout); } else { @@ -65,19 +65,15 @@ function previewLockfile(uri: vscode.Uri, token?: vscode.CancellationToken): Pro }); } -export default function(context: vscode.ExtensionContext): void { +export default function (context: vscode.ExtensionContext): void { const viewType = "bun.lockb"; const provider = new BunLockfileEditorProvider(context); - - vscode.window.registerCustomEditorProvider( - viewType, - provider, - { - supportsMultipleEditorsPerDocument: true, - webviewOptions: { - enableFindWidget: true, - retainContextWhenHidden: true, - }, + + vscode.window.registerCustomEditorProvider(viewType, provider, { + supportsMultipleEditorsPerDocument: true, + webviewOptions: { + enableFindWidget: true, + retainContextWhenHidden: true, }, - ); + }); } diff --git a/packages/bun-vscode/src/jsc.ts b/packages/bun-vscode/src/jsc.ts deleted file mode 100644 index 5b8d4ed84..000000000 --- a/packages/bun-vscode/src/jsc.ts +++ /dev/null @@ -1,308 +0,0 @@ -import { Socket, createConnection } from "node:net"; -import { inspect } from "node:util"; -import type { JSC } from "../types/jsc"; -export type { JSC }; - -export type JSCClientOptions = { - url: string | URL; - retry?: boolean; - onEvent?: (event: JSC.Event) => void; - onRequest?: (request: JSC.Request) => void; - onResponse?: (response: JSC.Response) => void; - onError?: (error: Error) => void; - onClose?: (code: number, reason: string) => void; -}; -const headerInvalidNumber = 2147483646; - -// We use non-printable characters to separate messages in the stream. -// These should never appear in textual messages. - -// These are non-sequential so that code which just counts up from 0 doesn't accidentally parse them as messages. -// 0x12 0x11 0x13 0x14 as a little-endian 32-bit unsigned integer -const headerPrefix = "\x14\x13\x11\x12"; - -// 0x14 0x12 0x13 0x11 as a little-endian 32-bit unsigned integer -const headerSuffixString = "\x11\x13\x12\x14"; - -const headerSuffixInt = Buffer.from(headerSuffixString).readInt32LE(0); -const headerPrefixInt = Buffer.from(headerPrefix).readInt32LE(0); - -const messageLengthBuffer = new ArrayBuffer(12); -const messageLengthDataView = new DataView(messageLengthBuffer); -messageLengthDataView.setInt32(0, headerPrefixInt, true); -messageLengthDataView.setInt32(8, headerSuffixInt, true); - -function writeJSONMessageToBuffer(message: any) { - const asString = JSON.stringify(message); - const byteLength = Buffer.byteLength(asString, "utf8"); - const buffer = Buffer.allocUnsafe(12 + byteLength); - buffer.writeInt32LE(headerPrefixInt, 0); - buffer.writeInt32LE(byteLength, 4); - buffer.writeInt32LE(headerSuffixInt, 8); - if (buffer.write(asString, 12, byteLength, "utf8") !== byteLength) { - throw new Error("Failed to write message to buffer"); - } - - return buffer; -} - -let currentMessageLength = 0; -const DEBUGGING = true; -function extractMessageLengthAndOffsetFromBytes(buffer: Buffer, offset: number) { - const bufferLength = buffer.length; - while (offset < bufferLength) { - const headerStart = buffer.indexOf(headerPrefix, offset, "binary"); - if (headerStart === -1) { - if (DEBUGGING) { - console.error("No header found in buffer of length " + bufferLength + " starting at offset " + offset); - } - return headerInvalidNumber; - } - - // [headerPrefix (4), byteLength (4), headerSuffix (4)] - if (bufferLength <= headerStart + 12) { - if (DEBUGGING) { - console.error( - "Not enough bytes for header in buffer of length " + bufferLength + " starting at offset " + offset, - ); - } - return headerInvalidNumber; - } - - const prefix = buffer.readInt32LE(headerStart); - const byteLengthInt = buffer.readInt32LE(headerStart + 4); - const suffix = buffer.readInt32LE(headerStart + 8); - - if (prefix !== headerPrefixInt || suffix !== headerSuffixInt) { - offset = headerStart + 1; - currentMessageLength = 0; - - if (DEBUGGING) { - console.error( - "Invalid header in buffer of length " + bufferLength + " starting at offset " + offset + ": " + prefix, - byteLengthInt, - suffix, - ); - } - continue; - } - - if (byteLengthInt < 0) { - if (DEBUGGING) { - console.error( - "Invalid byteLength in buffer of length " + bufferLength + " starting at offset " + offset + ": " + prefix, - byteLengthInt, - suffix, - ); - } - - return headerInvalidNumber; - } - - if (byteLengthInt === 0) { - // Ignore 0-length messages - // Shouldn't happen in practice - offset = headerStart + 12; - currentMessageLength = 0; - - if (DEBUGGING) { - console.error( - "Ignoring 0-length message in buffer of length " + bufferLength + " starting at offset " + offset, - ); - console.error({ - buffer: buffer, - string: buffer.toString(), - }); - } - - continue; - } - - currentMessageLength = byteLengthInt; - - return headerStart + 12; - } - - if (DEBUGGING) { - if (bufferLength > 0) - console.error("Header not found in buffer of length " + bufferLength + " starting at offset " + offset); - } - - return headerInvalidNumber; -} - -class StreamingReader { - pendingBuffer: Buffer; - - constructor() { - this.pendingBuffer = Buffer.alloc(0); - } - - *onMessage(chunk: Buffer) { - let buffer: Buffer; - if (this.pendingBuffer.length > 0) { - this.pendingBuffer = buffer = Buffer.concat([this.pendingBuffer, chunk]); - } else { - this.pendingBuffer = buffer = chunk; - } - - currentMessageLength = 0; - - for ( - let offset = extractMessageLengthAndOffsetFromBytes(buffer, 0); - buffer.length > 0 && offset !== headerInvalidNumber; - currentMessageLength = 0, offset = extractMessageLengthAndOffsetFromBytes(buffer, 0) - ) { - const messageLength = currentMessageLength; - const start = offset; - const end = start + messageLength; - offset = end; - const messageChunk = buffer.slice(start, end); - this.pendingBuffer = buffer = buffer.slice(offset); - yield messageChunk.toString(); - } - } -} - -export class JSCClient { - #options: JSCClientOptions; - #requestId: number; - #pendingMessages: Buffer[]; - #pendingRequests: Map<number, (result: unknown) => void>; - #socket: Socket; - #ready?: Promise<void>; - #reader = new StreamingReader(); - signal?: AbortSignal; - - constructor(options: JSCClientOptions) { - this.#options = options; - this.#socket = undefined; - this.#requestId = 1; - - this.#pendingMessages = []; - this.#pendingRequests = new Map(); - } - - get ready(): Promise<void> { - if (!this.#ready) { - this.#ready = this.#connect(); - } - return this.#ready; - } - - #connect(): Promise<void> { - const { url, retry, onError, onResponse, onEvent, onClose } = this.#options; - let [host, port] = typeof url === "string" ? url.split(":") : [url.hostname, url.port]; - if (port == null) { - if (host == null) { - host = "localhost"; - port = "9229"; - } else { - port = "9229"; - } - } - - if (host == null) { - host = "localhost"; - } - var resolve, - reject, - promise = new Promise<void>((r1, r2) => { - resolve = r1; - reject = r2; - }), - socket: Socket; - let didConnect = false; - - this.#socket = socket = createConnection( - { - host, - port: Number(port), - }, - () => { - for (const message of this.#pendingMessages) { - this.#send(message); - } - this.#pendingMessages.length = 0; - didConnect = true; - resolve(); - }, - ) - .once("error", e => { - const error = new Error(`Socket error: ${e?.message || e}`); - reject(error); - }) - .on("data", buffer => { - for (const message of this.#reader.onMessage(buffer)) { - let received: JSC.Event | JSC.Response; - try { - received = JSON.parse(message); - } catch { - const error = new Error(`Invalid WebSocket data: ${inspect(message)}`); - onError?.(error); - return; - } - console.log({ received }); - if ("id" in received) { - onResponse?.(received); - if ("error" in received) { - const { message, code = "?" } = received.error; - const error = new Error(`${message} [code: ${code}]`); - error.code = code; - onError?.(error); - this.#pendingRequests.get(received.id)?.(error); - } else { - this.#pendingRequests.get(received.id)?.(received.result); - } - } else { - onEvent?.(received); - } - } - }) - .on("close", hadError => { - if (didConnect) { - onClose?.(hadError ? 1 : 0, "Socket closed"); - } - }); - - return promise; - } - - #send(message: any): void { - const socket = this.#socket; - const framed = writeJSONMessageToBuffer(message); - if (socket && !socket.connecting) { - socket.write(framed); - } else { - this.#pendingMessages.push(framed); - } - } - - async fetch<T extends keyof JSC.RequestMap>( - method: T, - params?: JSC.Request<T>["params"], - ): Promise<JSC.ResponseMap[T]> { - const request: JSC.Request<T> = { - id: this.#requestId++, - method, - params, - }; - this.#options.onRequest?.(request); - return new Promise((resolve, reject) => { - const done = (result: Error | JSC.ResponseMap[T]) => { - this.#pendingRequests.delete(request.id); - if (result instanceof Error) { - reject(result); - } else { - resolve(result); - } - }; - this.#pendingRequests.set(request.id, done); - this.#send(request); - }); - } - - close(): void { - if (this.#socket) this.#socket.end(); - } -} diff --git a/packages/bun-vscode/src/web-extension.ts b/packages/bun-vscode/src/web-extension.ts index 2a66793b5..cd2e2623e 100644 --- a/packages/bun-vscode/src/web-extension.ts +++ b/packages/bun-vscode/src/web-extension.ts @@ -1,10 +1,5 @@ import * as vscode from "vscode"; -import { activateBunDebug } from "./activate"; -export function activate(context: vscode.ExtensionContext) { - activateBunDebug(context); -} +export function activate(context: vscode.ExtensionContext) {} -export function deactivate() { - // No-op -} +export function deactivate() {} diff --git a/packages/bun-vscode/test/fixtures/echo.ts b/packages/bun-vscode/test/fixtures/echo.ts deleted file mode 100644 index 2779de0a5..000000000 --- a/packages/bun-vscode/test/fixtures/echo.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { serve } from "bun"; - -serve({ - port: 9229, - development: true, - fetch(request, server) { - return new Response(`Hello, ${request.url}!`); - }, - inspector: true, -}); diff --git a/packages/bun-vscode/test/jsc.test.ts b/packages/bun-vscode/test/jsc.test.ts deleted file mode 100644 index fa9158aa2..000000000 --- a/packages/bun-vscode/test/jsc.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { beforeAll, afterAll, describe, test, expect, mock } from "bun:test"; -import { Worker } from "node:worker_threads"; -import { JSCClient, type JSC } from "../src/jsc"; - -let worker: Worker; - -beforeAll(async () => { - const { pathname } = new URL("./fixtures/echo.ts", import.meta.url); - worker = new Worker(pathname, { smol: true }); - while (true) { - try { - await fetch("http://localhost:9229/"); - break; - } catch {} - } -}); - -afterAll(() => { - worker?.terminate(); -}); - -describe("JSCClient", () => { - const onRequest = mock((request: JSC.Request) => { - expect(request).toBeInstanceOf(Object); - expect(request.id).toBeNumber(); - expect(request.method).toBeString(); - if (request.params) { - expect(request.params).toBeInstanceOf(Object); - } else { - expect(request).toBeUndefined(); - } - }); - const onResponse = mock((response: JSC.Response) => { - expect(response).toBeInstanceOf(Object); - expect(response.id).toBeNumber(); - if ("result" in response) { - expect(response.result).toBeInstanceOf(Object); - } else { - expect(response.error).toBeInstanceOf(Object); - expect(response.error.message).toBeString(); - } - }); - const onEvent = mock((event: JSC.Event) => { - expect(event).toBeInstanceOf(Object); - expect(event.method).toBeString(); - if (event.params) { - expect(event.params).toBeInstanceOf(Object); - } else { - expect(event).toBeUndefined(); - } - }); - const onError = mock((error: Error) => { - expect(error).toBeInstanceOf(Error); - }); - const client = new JSCClient({ - url: "ws://localhost:9229/bun:inspect", - onRequest, - onResponse, - onEvent, - onError, - }); - test("can connect", () => { - expect(client.ready).resolves.toBeUndefined(); - }); - test("can send a request", () => { - expect(client.fetch("Runtime.evaluate", { expression: "1 + 1" })).resolves.toStrictEqual({ - result: { - type: "number", - value: 2, - description: "2", - }, - wasThrown: false, - }); - expect(onRequest).toHaveBeenCalled(); - expect(onRequest.mock.lastCall[0]).toStrictEqual({ - id: 1, - method: "Runtime.evaluate", - params: { expression: "1 + 1" }, - }); - expect(onResponse).toHaveBeenCalled(); - expect(onResponse.mock.lastCall[0]).toMatchObject({ - id: 1, - result: { - result: { - type: "number", - value: 2, - description: "2", - }, - wasThrown: false, - }, - }); - }); - test("can send an invalid request", () => { - expect( - client.fetch("Runtime.awaitPromise", { - promiseObjectId: "this-does-not-exist", - }), - ).rejects.toMatchObject({ - name: "Error", - message: expect.stringMatching(/promiseObjectId/), - }); - expect(onRequest).toHaveBeenCalled(); - expect(onRequest.mock.lastCall[0]).toStrictEqual({ - id: 2, - method: "Runtime.awaitPromise", - params: { - promiseObjectId: "this-does-not-exist", - }, - }); - expect(onResponse).toHaveBeenCalled(); - expect(onResponse.mock.lastCall[0]).toMatchObject({ - id: 2, - error: { - code: expect.any(Number), - message: expect.stringMatching(/promiseObjectId/), - }, - }); - expect(onError).toHaveBeenCalled(); - }); - test("can disconnect", () => { - expect(() => client.close()).not.toThrow(); - }); -}); diff --git a/packages/bun-vscode/tsconfig.json b/packages/bun-vscode/tsconfig.json index 930bbff03..2383c5833 100644 --- a/packages/bun-vscode/tsconfig.json +++ b/packages/bun-vscode/tsconfig.json @@ -7,16 +7,8 @@ "esModuleInterop": true, "isolatedModules": false, "skipLibCheck": true, - "types": [ - "bun-types" - ] + "types": ["bun-types"] }, - "include": [ - "src", - "test", - "types" - ], - "exclude": [ - "node_modules" - ] + "include": ["src", "test", "types", "../../bun-devtools", "../../bun-debug-adapter-protocol"], + "exclude": ["node_modules"] } diff --git a/packages/bun-vscode/types/dap.d.ts b/packages/bun-vscode/types/dap.d.ts deleted file mode 100644 index 1ead3e8c3..000000000 --- a/packages/bun-vscode/types/dap.d.ts +++ /dev/null @@ -1,5216 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -// GENERATED - DO NOT EDIT -// https://github.com/microsoft/vscode-js-debug/blob/53cfeec1e92ad4d3323b308aaad650f6d1c1b6e6/src/dap/api.d.ts -// https://github.com/microsoft/vscode-js-debug/blob/53cfeec1e92ad4d3323b308aaad650f6d1c1b6e6/src/dap/error.d.ts - -export namespace DAP { - export type Message = { - /** - * Unique identifier for the message. - */ - id: number; - - /** - * A format string for the message. Embedded variables have the form '{name}'. - * If variable name starts with an underscore character, the variable does not contain user data (PII) and can be safely used for telemetry purposes. - */ - format: string; - - /** - * An object used as a dictionary for looking up the variables in the format string. - */ - variables?: { [key: string]: string }; - - /** - * If true send to telemetry. - */ - sendTelemetry?: boolean; - - /** - * If true show user. - */ - showUser?: boolean; - - /** - * An optional url where additional information about this message can be found. - */ - url?: string; - - /** - * An optional label that is presented to the user as the UI for opening the url. - */ - urlLabel?: string; - }; - - export type Error = { - __errorMarker: boolean; - error: Message; - }; - - export type integer = number; - - export interface Api { - /** - * The `cancel` request is used by the client in two situations: - * - to indicate that it is no longer interested in the result produced by a specific request issued earlier - * - to cancel a progress sequence. Clients should only call this request if the corresponding capability `supportsCancelRequest` is true. - * This request has a hint characteristic: a debug adapter can only be expected to make a 'best effort' in honoring this request but there are no guarantees. - * The `cancel` request may return an error if it could not cancel an operation but a client should refrain from presenting this error to end users. - * The request that got cancelled still needs to send a response back. This can either be a normal result (`success` attribute true) or an error response (`success` attribute false and the `message` set to `cancelled`). - * Returning partial results from a cancelled request is possible but please note that a client has no generic way for detecting that a response is partial or not. - * The progress that got cancelled still needs to send a `progressEnd` event back. - * A client should not assume that progress just got cancelled after sending the `cancel` request. - */ - on( - request: 'cancel', - handler: (params: CancelParams) => Promise<CancelResult | Error>, - ): () => void; - /** - * The `cancel` request is used by the client in two situations: - * - to indicate that it is no longer interested in the result produced by a specific request issued earlier - * - to cancel a progress sequence. Clients should only call this request if the corresponding capability `supportsCancelRequest` is true. - * This request has a hint characteristic: a debug adapter can only be expected to make a 'best effort' in honoring this request but there are no guarantees. - * The `cancel` request may return an error if it could not cancel an operation but a client should refrain from presenting this error to end users. - * The request that got cancelled still needs to send a response back. This can either be a normal result (`success` attribute true) or an error response (`success` attribute false and the `message` set to `cancelled`). - * Returning partial results from a cancelled request is possible but please note that a client has no generic way for detecting that a response is partial or not. - * The progress that got cancelled still needs to send a `progressEnd` event back. - * A client should not assume that progress just got cancelled after sending the `cancel` request. - */ - cancelRequest(params: CancelParams): Promise<CancelResult>; - - /** - * This event indicates that the debug adapter is ready to accept configuration requests (e.g. `setBreakpoints`, `setExceptionBreakpoints`). - * A debug adapter is expected to send this event when it is ready to accept configuration requests (but not before the `initialize` request has finished). - * The sequence of events/requests is as follows: - * - adapters sends `initialized` event (after the `initialize` request has returned) - * - client sends zero or more `setBreakpoints` requests - * - client sends one `setFunctionBreakpoints` request (if corresponding capability `supportsFunctionBreakpoints` is true) - * - client sends a `setExceptionBreakpoints` request if one or more `exceptionBreakpointFilters` have been defined (or if `supportsConfigurationDoneRequest` is not true) - * - client sends other future configuration requests - * - client sends one `configurationDone` request to indicate the end of the configuration. - */ - initialized(params: InitializedEventParams): void; - - /** - * The event indicates that the execution of the debuggee has stopped due to some condition. - * This can be caused by a breakpoint previously set, a stepping request has completed, by executing a debugger statement etc. - */ - stopped(params: StoppedEventParams): void; - - /** - * The event indicates that the execution of the debuggee has continued. - * Please note: a debug adapter is not expected to send this event in response to a request that implies that execution continues, e.g. `launch` or `continue`. - * It is only necessary to send a `continued` event if there was no previous request that implied this. - */ - continued(params: ContinuedEventParams): void; - - /** - * The event indicates that the debuggee has exited and returns its exit code. - */ - exited(params: ExitedEventParams): void; - - /** - * The event indicates that debugging of the debuggee has terminated. This does **not** mean that the debuggee itself has exited. - */ - terminated(params: TerminatedEventParams): void; - - /** - * The event indicates that a thread has started or exited. - */ - thread(params: ThreadEventParams): void; - - /** - * The event indicates that the target has produced some output. - */ - output(params: OutputEventParams): void; - - /** - * The event indicates that some information about a breakpoint has changed. - */ - breakpoint(params: BreakpointEventParams): void; - - /** - * The event indicates that some information about a module has changed. - */ - module(params: ModuleEventParams): void; - - /** - * The event indicates that some source has been added, changed, or removed from the set of all loaded sources. - */ - loadedSource(params: LoadedSourceEventParams): void; - - /** - * The event indicates that the debugger has begun debugging a new process. Either one that it has launched, or one that it has attached to. - */ - process(params: ProcessEventParams): void; - - /** - * The event indicates that one or more capabilities have changed. - * Since the capabilities are dependent on the client and its UI, it might not be possible to change that at random times (or too late). - * Consequently this event has a hint characteristic: a client can only be expected to make a 'best effort' in honoring individual capabilities but there are no guarantees. - * Only changed capabilities need to be included, all other capabilities keep their values. - */ - capabilities(params: CapabilitiesEventParams): void; - - /** - * The event signals that a long running operation is about to start and provides additional information for the client to set up a corresponding progress and cancellation UI. - * The client is free to delay the showing of the UI in order to reduce flicker. - * This event should only be sent if the corresponding capability `supportsProgressReporting` is true. - */ - progressStart(params: ProgressStartEventParams): void; - - /** - * The event signals that the progress reporting needs to be updated with a new message and/or percentage. - * The client does not have to update the UI immediately, but the clients needs to keep track of the message and/or percentage values. - * This event should only be sent if the corresponding capability `supportsProgressReporting` is true. - */ - progressUpdate(params: ProgressUpdateEventParams): void; - - /** - * The event signals the end of the progress reporting with a final message. - * This event should only be sent if the corresponding capability `supportsProgressReporting` is true. - */ - progressEnd(params: ProgressEndEventParams): void; - - /** - * This event signals that some state in the debug adapter has changed and requires that the client needs to re-render the data snapshot previously requested. - * Debug adapters do not have to emit this event for runtime changes like stopped or thread events because in that case the client refetches the new state anyway. But the event can be used for example to refresh the UI after rendering formatting has changed in the debug adapter. - * This event should only be sent if the corresponding capability `supportsInvalidatedEvent` is true. - */ - invalidated(params: InvalidatedEventParams): void; - - /** - * This event indicates that some memory range has been updated. It should only be sent if the corresponding capability `supportsMemoryEvent` is true. - * Clients typically react to the event by re-issuing a `readMemory` request if they show the memory identified by the `memoryReference` and if the updated memory range overlaps the displayed range. Clients should not make assumptions how individual memory references relate to each other, so they should not assume that they are part of a single continuous address range and might overlap. - * Debug adapters can use this event to indicate that the contents of a memory range has changed due to some other request like `setVariable` or `setExpression`. Debug adapters are not expected to emit this event for each and every memory change of a running program, because that information is typically not available from debuggers and it would flood clients with too many events. - */ - memory(params: MemoryEventParams): void; - - /** - * This request is sent from the debug adapter to the client to run a command in a terminal. - * This is typically used to launch the debuggee in a terminal provided by the client. - * This request should only be called if the corresponding client capability `supportsRunInTerminalRequest` is true. - * Client implementations of `runInTerminal` are free to run the command however they choose including issuing the command to a command line interpreter (aka 'shell'). Argument strings passed to the `runInTerminal` request must arrive verbatim in the command to be run. As a consequence, clients which use a shell are responsible for escaping any special shell characters in the argument strings to prevent them from being interpreted (and modified) by the shell. - * Some users may wish to take advantage of shell processing in the argument strings. For clients which implement `runInTerminal` using an intermediary shell, the `argsCanBeInterpretedByShell` property can be set to true. In this case the client is requested not to escape any special shell characters in the argument strings. - */ - on( - request: 'runInTerminal', - handler: (params: RunInTerminalParams) => Promise<RunInTerminalResult | Error>, - ): () => void; - /** - * This request is sent from the debug adapter to the client to run a command in a terminal. - * This is typically used to launch the debuggee in a terminal provided by the client. - * This request should only be called if the corresponding client capability `supportsRunInTerminalRequest` is true. - * Client implementations of `runInTerminal` are free to run the command however they choose including issuing the command to a command line interpreter (aka 'shell'). Argument strings passed to the `runInTerminal` request must arrive verbatim in the command to be run. As a consequence, clients which use a shell are responsible for escaping any special shell characters in the argument strings to prevent them from being interpreted (and modified) by the shell. - * Some users may wish to take advantage of shell processing in the argument strings. For clients which implement `runInTerminal` using an intermediary shell, the `argsCanBeInterpretedByShell` property can be set to true. In this case the client is requested not to escape any special shell characters in the argument strings. - */ - runInTerminalRequest(params: RunInTerminalParams): Promise<RunInTerminalResult>; - - /** - * This request is sent from the debug adapter to the client to start a new debug session of the same type as the caller. - * This request should only be sent if the corresponding client capability `supportsStartDebuggingRequest` is true. - * A client implementation of `startDebugging` should start a new debug session (of the same type as the caller) in the same way that the caller's session was started. If the client supports hierarchical debug sessions, the newly created session can be treated as a child of the caller session. - */ - on( - request: 'startDebugging', - handler: (params: StartDebuggingParams) => Promise<StartDebuggingResult | Error>, - ): () => void; - /** - * This request is sent from the debug adapter to the client to start a new debug session of the same type as the caller. - * This request should only be sent if the corresponding client capability `supportsStartDebuggingRequest` is true. - * A client implementation of `startDebugging` should start a new debug session (of the same type as the caller) in the same way that the caller's session was started. If the client supports hierarchical debug sessions, the newly created session can be treated as a child of the caller session. - */ - startDebuggingRequest(params: StartDebuggingParams): Promise<StartDebuggingResult>; - - /** - * The `initialize` request is sent as the first request from the client to the debug adapter in order to configure it with client capabilities and to retrieve capabilities from the debug adapter. - * Until the debug adapter has responded with an `initialize` response, the client must not send any additional requests or events to the debug adapter. - * In addition the debug adapter is not allowed to send any requests or events to the client until it has responded with an `initialize` response. - * The `initialize` request may only be sent once. - */ - on( - request: 'initialize', - handler: (params: InitializeParams) => Promise<InitializeResult | Error>, - ): () => void; - /** - * The `initialize` request is sent as the first request from the client to the debug adapter in order to configure it with client capabilities and to retrieve capabilities from the debug adapter. - * Until the debug adapter has responded with an `initialize` response, the client must not send any additional requests or events to the debug adapter. - * In addition the debug adapter is not allowed to send any requests or events to the client until it has responded with an `initialize` response. - * The `initialize` request may only be sent once. - */ - initializeRequest(params: InitializeParams): Promise<InitializeResult>; - - /** - * This request indicates that the client has finished initialization of the debug adapter. - * So it is the last request in the sequence of configuration requests (which was started by the `initialized` event). - * Clients should only call this request if the corresponding capability `supportsConfigurationDoneRequest` is true. - */ - on( - request: 'configurationDone', - handler: (params: ConfigurationDoneParams) => Promise<ConfigurationDoneResult | Error>, - ): () => void; - /** - * This request indicates that the client has finished initialization of the debug adapter. - * So it is the last request in the sequence of configuration requests (which was started by the `initialized` event). - * Clients should only call this request if the corresponding capability `supportsConfigurationDoneRequest` is true. - */ - configurationDoneRequest(params: ConfigurationDoneParams): Promise<ConfigurationDoneResult>; - - /** - * This launch request is sent from the client to the debug adapter to start the debuggee with or without debugging (if `noDebug` is true). - * Since launching is debugger/runtime specific, the arguments for this request are not part of this specification. - */ - on( - request: 'launch', - handler: (params: LaunchParams) => Promise<LaunchResult | Error>, - ): () => void; - /** - * This launch request is sent from the client to the debug adapter to start the debuggee with or without debugging (if `noDebug` is true). - * Since launching is debugger/runtime specific, the arguments for this request are not part of this specification. - */ - launchRequest(params: LaunchParams): Promise<LaunchResult>; - - /** - * The `attach` request is sent from the client to the debug adapter to attach to a debuggee that is already running. - * Since attaching is debugger/runtime specific, the arguments for this request are not part of this specification. - */ - on( - request: 'attach', - handler: (params: AttachParams) => Promise<AttachResult | Error>, - ): () => void; - /** - * The `attach` request is sent from the client to the debug adapter to attach to a debuggee that is already running. - * Since attaching is debugger/runtime specific, the arguments for this request are not part of this specification. - */ - attachRequest(params: AttachParams): Promise<AttachResult>; - - /** - * Restarts a debug session. Clients should only call this request if the corresponding capability `supportsRestartRequest` is true. - * If the capability is missing or has the value false, a typical client emulates `restart` by terminating the debug adapter first and then launching it anew. - */ - on( - request: 'restart', - handler: (params: RestartParams) => Promise<RestartResult | Error>, - ): () => void; - /** - * Restarts a debug session. Clients should only call this request if the corresponding capability `supportsRestartRequest` is true. - * If the capability is missing or has the value false, a typical client emulates `restart` by terminating the debug adapter first and then launching it anew. - */ - restartRequest(params: RestartParams): Promise<RestartResult>; - - /** - * The `disconnect` request asks the debug adapter to disconnect from the debuggee (thus ending the debug session) and then to shut down itself (the debug adapter). - * In addition, the debug adapter must terminate the debuggee if it was started with the `launch` request. If an `attach` request was used to connect to the debuggee, then the debug adapter must not terminate the debuggee. - * This implicit behavior of when to terminate the debuggee can be overridden with the `terminateDebuggee` argument (which is only supported by a debug adapter if the corresponding capability `supportTerminateDebuggee` is true). - */ - on( - request: 'disconnect', - handler: (params: DisconnectParams) => Promise<DisconnectResult | Error>, - ): () => void; - /** - * The `disconnect` request asks the debug adapter to disconnect from the debuggee (thus ending the debug session) and then to shut down itself (the debug adapter). - * In addition, the debug adapter must terminate the debuggee if it was started with the `launch` request. If an `attach` request was used to connect to the debuggee, then the debug adapter must not terminate the debuggee. - * This implicit behavior of when to terminate the debuggee can be overridden with the `terminateDebuggee` argument (which is only supported by a debug adapter if the corresponding capability `supportTerminateDebuggee` is true). - */ - disconnectRequest(params: DisconnectParams): Promise<DisconnectResult>; - - /** - * The `terminate` request is sent from the client to the debug adapter in order to shut down the debuggee gracefully. Clients should only call this request if the capability `supportsTerminateRequest` is true. - * Typically a debug adapter implements `terminate` by sending a software signal which the debuggee intercepts in order to clean things up properly before terminating itself. - * Please note that this request does not directly affect the state of the debug session: if the debuggee decides to veto the graceful shutdown for any reason by not terminating itself, then the debug session just continues. - * Clients can surface the `terminate` request as an explicit command or they can integrate it into a two stage Stop command that first sends `terminate` to request a graceful shutdown, and if that fails uses `disconnect` for a forceful shutdown. - */ - on( - request: 'terminate', - handler: (params: TerminateParams) => Promise<TerminateResult | Error>, - ): () => void; - /** - * The `terminate` request is sent from the client to the debug adapter in order to shut down the debuggee gracefully. Clients should only call this request if the capability `supportsTerminateRequest` is true. - * Typically a debug adapter implements `terminate` by sending a software signal which the debuggee intercepts in order to clean things up properly before terminating itself. - * Please note that this request does not directly affect the state of the debug session: if the debuggee decides to veto the graceful shutdown for any reason by not terminating itself, then the debug session just continues. - * Clients can surface the `terminate` request as an explicit command or they can integrate it into a two stage Stop command that first sends `terminate` to request a graceful shutdown, and if that fails uses `disconnect` for a forceful shutdown. - */ - terminateRequest(params: TerminateParams): Promise<TerminateResult>; - - /** - * The `breakpointLocations` request returns all possible locations for source breakpoints in a given range. - * Clients should only call this request if the corresponding capability `supportsBreakpointLocationsRequest` is true. - */ - on( - request: 'breakpointLocations', - handler: (params: BreakpointLocationsParams) => Promise<BreakpointLocationsResult | Error>, - ): () => void; - /** - * The `breakpointLocations` request returns all possible locations for source breakpoints in a given range. - * Clients should only call this request if the corresponding capability `supportsBreakpointLocationsRequest` is true. - */ - breakpointLocationsRequest( - params: BreakpointLocationsParams, - ): Promise<BreakpointLocationsResult>; - - /** - * Sets multiple breakpoints for a single source and clears all previous breakpoints in that source. - * To clear all breakpoint for a source, specify an empty array. - * When a breakpoint is hit, a `stopped` event (with reason `breakpoint`) is generated. - */ - on( - request: 'setBreakpoints', - handler: (params: SetBreakpointsParams) => Promise<SetBreakpointsResult | Error>, - ): () => void; - /** - * Sets multiple breakpoints for a single source and clears all previous breakpoints in that source. - * To clear all breakpoint for a source, specify an empty array. - * When a breakpoint is hit, a `stopped` event (with reason `breakpoint`) is generated. - */ - setBreakpointsRequest(params: SetBreakpointsParams): Promise<SetBreakpointsResult>; - - /** - * Replaces all existing function breakpoints with new function breakpoints. - * To clear all function breakpoints, specify an empty array. - * When a function breakpoint is hit, a `stopped` event (with reason `function breakpoint`) is generated. - * Clients should only call this request if the corresponding capability `supportsFunctionBreakpoints` is true. - */ - on( - request: 'setFunctionBreakpoints', - handler: ( - params: SetFunctionBreakpointsParams, - ) => Promise<SetFunctionBreakpointsResult | Error>, - ): () => void; - /** - * Replaces all existing function breakpoints with new function breakpoints. - * To clear all function breakpoints, specify an empty array. - * When a function breakpoint is hit, a `stopped` event (with reason `function breakpoint`) is generated. - * Clients should only call this request if the corresponding capability `supportsFunctionBreakpoints` is true. - */ - setFunctionBreakpointsRequest( - params: SetFunctionBreakpointsParams, - ): Promise<SetFunctionBreakpointsResult>; - - /** - * The request configures the debugger's response to thrown exceptions. - * If an exception is configured to break, a `stopped` event is fired (with reason `exception`). - * Clients should only call this request if the corresponding capability `exceptionBreakpointFilters` returns one or more filters. - */ - on( - request: 'setExceptionBreakpoints', - handler: ( - params: SetExceptionBreakpointsParams, - ) => Promise<SetExceptionBreakpointsResult | Error>, - ): () => void; - /** - * The request configures the debugger's response to thrown exceptions. - * If an exception is configured to break, a `stopped` event is fired (with reason `exception`). - * Clients should only call this request if the corresponding capability `exceptionBreakpointFilters` returns one or more filters. - */ - setExceptionBreakpointsRequest( - params: SetExceptionBreakpointsParams, - ): Promise<SetExceptionBreakpointsResult>; - - /** - * Obtains information on a possible data breakpoint that could be set on an expression or variable. - * Clients should only call this request if the corresponding capability `supportsDataBreakpoints` is true. - */ - on( - request: 'dataBreakpointInfo', - handler: (params: DataBreakpointInfoParams) => Promise<DataBreakpointInfoResult | Error>, - ): () => void; - /** - * Obtains information on a possible data breakpoint that could be set on an expression or variable. - * Clients should only call this request if the corresponding capability `supportsDataBreakpoints` is true. - */ - dataBreakpointInfoRequest(params: DataBreakpointInfoParams): Promise<DataBreakpointInfoResult>; - - /** - * Replaces all existing data breakpoints with new data breakpoints. - * To clear all data breakpoints, specify an empty array. - * When a data breakpoint is hit, a `stopped` event (with reason `data breakpoint`) is generated. - * Clients should only call this request if the corresponding capability `supportsDataBreakpoints` is true. - */ - on( - request: 'setDataBreakpoints', - handler: (params: SetDataBreakpointsParams) => Promise<SetDataBreakpointsResult | Error>, - ): () => void; - /** - * Replaces all existing data breakpoints with new data breakpoints. - * To clear all data breakpoints, specify an empty array. - * When a data breakpoint is hit, a `stopped` event (with reason `data breakpoint`) is generated. - * Clients should only call this request if the corresponding capability `supportsDataBreakpoints` is true. - */ - setDataBreakpointsRequest(params: SetDataBreakpointsParams): Promise<SetDataBreakpointsResult>; - - /** - * Replaces all existing instruction breakpoints. Typically, instruction breakpoints would be set from a disassembly window. - * To clear all instruction breakpoints, specify an empty array. - * When an instruction breakpoint is hit, a `stopped` event (with reason `instruction breakpoint`) is generated. - * Clients should only call this request if the corresponding capability `supportsInstructionBreakpoints` is true. - */ - on( - request: 'setInstructionBreakpoints', - handler: ( - params: SetInstructionBreakpointsParams, - ) => Promise<SetInstructionBreakpointsResult | Error>, - ): () => void; - /** - * Replaces all existing instruction breakpoints. Typically, instruction breakpoints would be set from a disassembly window. - * To clear all instruction breakpoints, specify an empty array. - * When an instruction breakpoint is hit, a `stopped` event (with reason `instruction breakpoint`) is generated. - * Clients should only call this request if the corresponding capability `supportsInstructionBreakpoints` is true. - */ - setInstructionBreakpointsRequest( - params: SetInstructionBreakpointsParams, - ): Promise<SetInstructionBreakpointsResult>; - - /** - * The request resumes execution of all threads. If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true resumes only the specified thread. If not all threads were resumed, the `allThreadsContinued` attribute of the response should be set to false. - */ - on( - request: 'continue', - handler: (params: ContinueParams) => Promise<ContinueResult | Error>, - ): () => void; - /** - * The request resumes execution of all threads. If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true resumes only the specified thread. If not all threads were resumed, the `allThreadsContinued` attribute of the response should be set to false. - */ - continueRequest(params: ContinueParams): Promise<ContinueResult>; - - /** - * The request executes one step (in the given granularity) for the specified thread and allows all other threads to run freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - */ - on(request: 'next', handler: (params: NextParams) => Promise<NextResult | Error>): () => void; - /** - * The request executes one step (in the given granularity) for the specified thread and allows all other threads to run freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - */ - nextRequest(params: NextParams): Promise<NextResult>; - - /** - * The request resumes the given thread to step into a function/method and allows all other threads to run freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * If the request cannot step into a target, `stepIn` behaves like the `next` request. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - * If there are multiple function/method calls (or other targets) on the source line, - * the argument `targetId` can be used to control into which target the `stepIn` should occur. - * The list of possible targets for a given source line can be retrieved via the `stepInTargets` request. - */ - on( - request: 'stepIn', - handler: (params: StepInParams) => Promise<StepInResult | Error>, - ): () => void; - /** - * The request resumes the given thread to step into a function/method and allows all other threads to run freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * If the request cannot step into a target, `stepIn` behaves like the `next` request. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - * If there are multiple function/method calls (or other targets) on the source line, - * the argument `targetId` can be used to control into which target the `stepIn` should occur. - * The list of possible targets for a given source line can be retrieved via the `stepInTargets` request. - */ - stepInRequest(params: StepInParams): Promise<StepInResult>; - - /** - * The request resumes the given thread to step out (return) from a function/method and allows all other threads to run freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - */ - on( - request: 'stepOut', - handler: (params: StepOutParams) => Promise<StepOutResult | Error>, - ): () => void; - /** - * The request resumes the given thread to step out (return) from a function/method and allows all other threads to run freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - */ - stepOutRequest(params: StepOutParams): Promise<StepOutResult>; - - /** - * The request executes one backward step (in the given granularity) for the specified thread and allows all other threads to run backward freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - * Clients should only call this request if the corresponding capability `supportsStepBack` is true. - */ - on( - request: 'stepBack', - handler: (params: StepBackParams) => Promise<StepBackResult | Error>, - ): () => void; - /** - * The request executes one backward step (in the given granularity) for the specified thread and allows all other threads to run backward freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - * Clients should only call this request if the corresponding capability `supportsStepBack` is true. - */ - stepBackRequest(params: StepBackParams): Promise<StepBackResult>; - - /** - * The request resumes backward execution of all threads. If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true resumes only the specified thread. If not all threads were resumed, the `allThreadsContinued` attribute of the response should be set to false. - * Clients should only call this request if the corresponding capability `supportsStepBack` is true. - */ - on( - request: 'reverseContinue', - handler: (params: ReverseContinueParams) => Promise<ReverseContinueResult | Error>, - ): () => void; - /** - * The request resumes backward execution of all threads. If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true resumes only the specified thread. If not all threads were resumed, the `allThreadsContinued` attribute of the response should be set to false. - * Clients should only call this request if the corresponding capability `supportsStepBack` is true. - */ - reverseContinueRequest(params: ReverseContinueParams): Promise<ReverseContinueResult>; - - /** - * The request restarts execution of the specified stack frame. - * The debug adapter first sends the response and then a `stopped` event (with reason `restart`) after the restart has completed. - * Clients should only call this request if the corresponding capability `supportsRestartFrame` is true. - */ - on( - request: 'restartFrame', - handler: (params: RestartFrameParams) => Promise<RestartFrameResult | Error>, - ): () => void; - /** - * The request restarts execution of the specified stack frame. - * The debug adapter first sends the response and then a `stopped` event (with reason `restart`) after the restart has completed. - * Clients should only call this request if the corresponding capability `supportsRestartFrame` is true. - */ - restartFrameRequest(params: RestartFrameParams): Promise<RestartFrameResult>; - - /** - * The request sets the location where the debuggee will continue to run. - * This makes it possible to skip the execution of code or to execute code again. - * The code between the current location and the goto target is not executed but skipped. - * The debug adapter first sends the response and then a `stopped` event with reason `goto`. - * Clients should only call this request if the corresponding capability `supportsGotoTargetsRequest` is true (because only then goto targets exist that can be passed as arguments). - */ - on(request: 'goto', handler: (params: GotoParams) => Promise<GotoResult | Error>): () => void; - /** - * The request sets the location where the debuggee will continue to run. - * This makes it possible to skip the execution of code or to execute code again. - * The code between the current location and the goto target is not executed but skipped. - * The debug adapter first sends the response and then a `stopped` event with reason `goto`. - * Clients should only call this request if the corresponding capability `supportsGotoTargetsRequest` is true (because only then goto targets exist that can be passed as arguments). - */ - gotoRequest(params: GotoParams): Promise<GotoResult>; - - /** - * The request suspends the debuggee. - * The debug adapter first sends the response and then a `stopped` event (with reason `pause`) after the thread has been paused successfully. - */ - on( - request: 'pause', - handler: (params: PauseParams) => Promise<PauseResult | Error>, - ): () => void; - /** - * The request suspends the debuggee. - * The debug adapter first sends the response and then a `stopped` event (with reason `pause`) after the thread has been paused successfully. - */ - pauseRequest(params: PauseParams): Promise<PauseResult>; - - /** - * The request returns a stacktrace from the current execution state of a given thread. - * A client can request all stack frames by omitting the startFrame and levels arguments. For performance-conscious clients and if the corresponding capability `supportsDelayedStackTraceLoading` is true, stack frames can be retrieved in a piecemeal way with the `startFrame` and `levels` arguments. The response of the `stackTrace` request may contain a `totalFrames` property that hints at the total number of frames in the stack. If a client needs this total number upfront, it can issue a request for a single (first) frame and depending on the value of `totalFrames` decide how to proceed. In any case a client should be prepared to receive fewer frames than requested, which is an indication that the end of the stack has been reached. - */ - on( - request: 'stackTrace', - handler: (params: StackTraceParams) => Promise<StackTraceResult | Error>, - ): () => void; - /** - * The request returns a stacktrace from the current execution state of a given thread. - * A client can request all stack frames by omitting the startFrame and levels arguments. For performance-conscious clients and if the corresponding capability `supportsDelayedStackTraceLoading` is true, stack frames can be retrieved in a piecemeal way with the `startFrame` and `levels` arguments. The response of the `stackTrace` request may contain a `totalFrames` property that hints at the total number of frames in the stack. If a client needs this total number upfront, it can issue a request for a single (first) frame and depending on the value of `totalFrames` decide how to proceed. In any case a client should be prepared to receive fewer frames than requested, which is an indication that the end of the stack has been reached. - */ - stackTraceRequest(params: StackTraceParams): Promise<StackTraceResult>; - - /** - * The request returns the variable scopes for a given stack frame ID. - */ - on( - request: 'scopes', - handler: (params: ScopesParams) => Promise<ScopesResult | Error>, - ): () => void; - /** - * The request returns the variable scopes for a given stack frame ID. - */ - scopesRequest(params: ScopesParams): Promise<ScopesResult>; - - /** - * Retrieves all child variables for the given variable reference. - * A filter can be used to limit the fetched children to either named or indexed children. - */ - on( - request: 'variables', - handler: (params: VariablesParams) => Promise<VariablesResult | Error>, - ): () => void; - /** - * Retrieves all child variables for the given variable reference. - * A filter can be used to limit the fetched children to either named or indexed children. - */ - variablesRequest(params: VariablesParams): Promise<VariablesResult>; - - /** - * Set the variable with the given name in the variable container to a new value. Clients should only call this request if the corresponding capability `supportsSetVariable` is true. - * If a debug adapter implements both `setVariable` and `setExpression`, a client will only use `setExpression` if the variable has an `evaluateName` property. - */ - on( - request: 'setVariable', - handler: (params: SetVariableParams) => Promise<SetVariableResult | Error>, - ): () => void; - /** - * Set the variable with the given name in the variable container to a new value. Clients should only call this request if the corresponding capability `supportsSetVariable` is true. - * If a debug adapter implements both `setVariable` and `setExpression`, a client will only use `setExpression` if the variable has an `evaluateName` property. - */ - setVariableRequest(params: SetVariableParams): Promise<SetVariableResult>; - - /** - * The request retrieves the source code for a given source reference. - */ - on( - request: 'source', - handler: (params: SourceParams) => Promise<SourceResult | Error>, - ): () => void; - /** - * The request retrieves the source code for a given source reference. - */ - sourceRequest(params: SourceParams): Promise<SourceResult>; - - /** - * The request retrieves a list of all threads. - */ - on( - request: 'threads', - handler: (params: ThreadsParams) => Promise<ThreadsResult | Error>, - ): () => void; - /** - * The request retrieves a list of all threads. - */ - threadsRequest(params: ThreadsParams): Promise<ThreadsResult>; - - /** - * The request terminates the threads with the given ids. - * Clients should only call this request if the corresponding capability `supportsTerminateThreadsRequest` is true. - */ - on( - request: 'terminateThreads', - handler: (params: TerminateThreadsParams) => Promise<TerminateThreadsResult | Error>, - ): () => void; - /** - * The request terminates the threads with the given ids. - * Clients should only call this request if the corresponding capability `supportsTerminateThreadsRequest` is true. - */ - terminateThreadsRequest(params: TerminateThreadsParams): Promise<TerminateThreadsResult>; - - /** - * Modules can be retrieved from the debug adapter with this request which can either return all modules or a range of modules to support paging. - * Clients should only call this request if the corresponding capability `supportsModulesRequest` is true. - */ - on( - request: 'modules', - handler: (params: ModulesParams) => Promise<ModulesResult | Error>, - ): () => void; - /** - * Modules can be retrieved from the debug adapter with this request which can either return all modules or a range of modules to support paging. - * Clients should only call this request if the corresponding capability `supportsModulesRequest` is true. - */ - modulesRequest(params: ModulesParams): Promise<ModulesResult>; - - /** - * Retrieves the set of all sources currently loaded by the debugged process. - * Clients should only call this request if the corresponding capability `supportsLoadedSourcesRequest` is true. - */ - on( - request: 'loadedSources', - handler: (params: LoadedSourcesParams) => Promise<LoadedSourcesResult | Error>, - ): () => void; - /** - * Retrieves the set of all sources currently loaded by the debugged process. - * Clients should only call this request if the corresponding capability `supportsLoadedSourcesRequest` is true. - */ - loadedSourcesRequest(params: LoadedSourcesParams): Promise<LoadedSourcesResult>; - - /** - * Evaluates the given expression in the context of the topmost stack frame. - * The expression has access to any variables and arguments that are in scope. - */ - on( - request: 'evaluate', - handler: (params: EvaluateParams) => Promise<EvaluateResult | Error>, - ): () => void; - /** - * Evaluates the given expression in the context of the topmost stack frame. - * The expression has access to any variables and arguments that are in scope. - */ - evaluateRequest(params: EvaluateParams): Promise<EvaluateResult>; - - /** - * Evaluates the given `value` expression and assigns it to the `expression` which must be a modifiable l-value. - * The expressions have access to any variables and arguments that are in scope of the specified frame. - * Clients should only call this request if the corresponding capability `supportsSetExpression` is true. - * If a debug adapter implements both `setExpression` and `setVariable`, a client uses `setExpression` if the variable has an `evaluateName` property. - */ - on( - request: 'setExpression', - handler: (params: SetExpressionParams) => Promise<SetExpressionResult | Error>, - ): () => void; - /** - * Evaluates the given `value` expression and assigns it to the `expression` which must be a modifiable l-value. - * The expressions have access to any variables and arguments that are in scope of the specified frame. - * Clients should only call this request if the corresponding capability `supportsSetExpression` is true. - * If a debug adapter implements both `setExpression` and `setVariable`, a client uses `setExpression` if the variable has an `evaluateName` property. - */ - setExpressionRequest(params: SetExpressionParams): Promise<SetExpressionResult>; - - /** - * This request retrieves the possible step-in targets for the specified stack frame. - * These targets can be used in the `stepIn` request. - * Clients should only call this request if the corresponding capability `supportsStepInTargetsRequest` is true. - */ - on( - request: 'stepInTargets', - handler: (params: StepInTargetsParams) => Promise<StepInTargetsResult | Error>, - ): () => void; - /** - * This request retrieves the possible step-in targets for the specified stack frame. - * These targets can be used in the `stepIn` request. - * Clients should only call this request if the corresponding capability `supportsStepInTargetsRequest` is true. - */ - stepInTargetsRequest(params: StepInTargetsParams): Promise<StepInTargetsResult>; - - /** - * This request retrieves the possible goto targets for the specified source location. - * These targets can be used in the `goto` request. - * Clients should only call this request if the corresponding capability `supportsGotoTargetsRequest` is true. - */ - on( - request: 'gotoTargets', - handler: (params: GotoTargetsParams) => Promise<GotoTargetsResult | Error>, - ): () => void; - /** - * This request retrieves the possible goto targets for the specified source location. - * These targets can be used in the `goto` request. - * Clients should only call this request if the corresponding capability `supportsGotoTargetsRequest` is true. - */ - gotoTargetsRequest(params: GotoTargetsParams): Promise<GotoTargetsResult>; - - /** - * Returns a list of possible completions for a given caret position and text. - * Clients should only call this request if the corresponding capability `supportsCompletionsRequest` is true. - */ - on( - request: 'completions', - handler: (params: CompletionsParams) => Promise<CompletionsResult | Error>, - ): () => void; - /** - * Returns a list of possible completions for a given caret position and text. - * Clients should only call this request if the corresponding capability `supportsCompletionsRequest` is true. - */ - completionsRequest(params: CompletionsParams): Promise<CompletionsResult>; - - /** - * Retrieves the details of the exception that caused this event to be raised. - * Clients should only call this request if the corresponding capability `supportsExceptionInfoRequest` is true. - */ - on( - request: 'exceptionInfo', - handler: (params: ExceptionInfoParams) => Promise<ExceptionInfoResult | Error>, - ): () => void; - /** - * Retrieves the details of the exception that caused this event to be raised. - * Clients should only call this request if the corresponding capability `supportsExceptionInfoRequest` is true. - */ - exceptionInfoRequest(params: ExceptionInfoParams): Promise<ExceptionInfoResult>; - - /** - * Reads bytes from memory at the provided location. - * Clients should only call this request if the corresponding capability `supportsReadMemoryRequest` is true. - */ - on( - request: 'readMemory', - handler: (params: ReadMemoryParams) => Promise<ReadMemoryResult | Error>, - ): () => void; - /** - * Reads bytes from memory at the provided location. - * Clients should only call this request if the corresponding capability `supportsReadMemoryRequest` is true. - */ - readMemoryRequest(params: ReadMemoryParams): Promise<ReadMemoryResult>; - - /** - * Writes bytes to memory at the provided location. - * Clients should only call this request if the corresponding capability `supportsWriteMemoryRequest` is true. - */ - on( - request: 'writeMemory', - handler: (params: WriteMemoryParams) => Promise<WriteMemoryResult | Error>, - ): () => void; - /** - * Writes bytes to memory at the provided location. - * Clients should only call this request if the corresponding capability `supportsWriteMemoryRequest` is true. - */ - writeMemoryRequest(params: WriteMemoryParams): Promise<WriteMemoryResult>; - - /** - * Disassembles code stored at the provided location. - * Clients should only call this request if the corresponding capability `supportsDisassembleRequest` is true. - */ - on( - request: 'disassemble', - handler: (params: DisassembleParams) => Promise<DisassembleResult | Error>, - ): () => void; - /** - * Disassembles code stored at the provided location. - * Clients should only call this request if the corresponding capability `supportsDisassembleRequest` is true. - */ - disassembleRequest(params: DisassembleParams): Promise<DisassembleResult>; - - /** - * Enable custom breakpoints. - */ - on( - request: 'enableCustomBreakpoints', - handler: ( - params: EnableCustomBreakpointsParams, - ) => Promise<EnableCustomBreakpointsResult | Error>, - ): () => void; - /** - * Enable custom breakpoints. - */ - enableCustomBreakpointsRequest( - params: EnableCustomBreakpointsParams, - ): Promise<EnableCustomBreakpointsResult>; - - /** - * Disable custom breakpoints. - */ - on( - request: 'disableCustomBreakpoints', - handler: ( - params: DisableCustomBreakpointsParams, - ) => Promise<DisableCustomBreakpointsResult | Error>, - ): () => void; - /** - * Disable custom breakpoints. - */ - disableCustomBreakpointsRequest( - params: DisableCustomBreakpointsParams, - ): Promise<DisableCustomBreakpointsResult>; - - /** - * Pretty prints source for debugging. - */ - on( - request: 'prettyPrintSource', - handler: (params: PrettyPrintSourceParams) => Promise<PrettyPrintSourceResult | Error>, - ): () => void; - /** - * Pretty prints source for debugging. - */ - prettyPrintSourceRequest(params: PrettyPrintSourceParams): Promise<PrettyPrintSourceResult>; - - /** - * Toggle skip status of file. - */ - on( - request: 'toggleSkipFileStatus', - handler: (params: ToggleSkipFileStatusParams) => Promise<ToggleSkipFileStatusResult | Error>, - ): () => void; - /** - * Toggle skip status of file. - */ - toggleSkipFileStatusRequest( - params: ToggleSkipFileStatusParams, - ): Promise<ToggleSkipFileStatusResult>; - - /** - * A request to reveal a certain location in the UI. - */ - revealLocationRequested(params: RevealLocationRequestedEventParams): void; - - /** - * A request to copy a certain string to clipboard. - */ - copyRequested(params: CopyRequestedEventParams): void; - - /** - * An event sent when breakpoint prediction takes a significant amount of time. - */ - longPrediction(params: LongPredictionEventParams): void; - - /** - * Request to launch a browser in the companion extension within the UI. - */ - launchBrowserInCompanion(params: LaunchBrowserInCompanionEventParams): void; - - /** - * Kills a launched browser companion. - */ - killCompanionBrowser(params: KillCompanionBrowserEventParams): void; - - /** - * Starts taking a profile of the target. - */ - on( - request: 'startProfile', - handler: (params: StartProfileParams) => Promise<StartProfileResult | Error>, - ): () => void; - /** - * Starts taking a profile of the target. - */ - startProfileRequest(params: StartProfileParams): Promise<StartProfileResult>; - - /** - * Stops a running profile. - */ - on( - request: 'stopProfile', - handler: (params: StopProfileParams) => Promise<StopProfileResult | Error>, - ): () => void; - /** - * Stops a running profile. - */ - stopProfileRequest(params: StopProfileParams): Promise<StopProfileResult>; - - /** - * Fired when a profiling state changes. - */ - profileStarted(params: ProfileStartedEventParams): void; - - /** - * Fired when a profiling state changes. - */ - profilerStateUpdate(params: ProfilerStateUpdateEventParams): void; - - /** - * Launches a VS Code extension host in debug mode. - */ - on( - request: 'launchVSCode', - handler: (params: LaunchVSCodeParams) => Promise<LaunchVSCodeResult | Error>, - ): () => void; - /** - * Launches a VS Code extension host in debug mode. - */ - launchVSCodeRequest(params: LaunchVSCodeParams): Promise<LaunchVSCodeResult>; - - /** - * Launches a VS Code extension host in debug mode. - */ - on( - request: 'launchUnelevated', - handler: (params: LaunchUnelevatedParams) => Promise<LaunchUnelevatedResult | Error>, - ): () => void; - /** - * Launches a VS Code extension host in debug mode. - */ - launchUnelevatedRequest(params: LaunchUnelevatedParams): Promise<LaunchUnelevatedResult>; - - /** - * Check if file exists on remote file system, used in VS. - */ - on( - request: 'remoteFileExists', - handler: (params: RemoteFileExistsParams) => Promise<RemoteFileExistsResult | Error>, - ): () => void; - /** - * Check if file exists on remote file system, used in VS. - */ - remoteFileExistsRequest(params: RemoteFileExistsParams): Promise<RemoteFileExistsResult>; - - /** - * Focuses the browser page or tab associated with the session. - */ - on( - request: 'revealPage', - handler: (params: RevealPageParams) => Promise<RevealPageResult | Error>, - ): () => void; - /** - * Focuses the browser page or tab associated with the session. - */ - revealPageRequest(params: RevealPageParams): Promise<RevealPageResult>; - - /** - * Starts profiling the extension itself. Used by VS. - */ - on( - request: 'startSelfProfile', - handler: (params: StartSelfProfileParams) => Promise<StartSelfProfileResult | Error>, - ): () => void; - /** - * Starts profiling the extension itself. Used by VS. - */ - startSelfProfileRequest(params: StartSelfProfileParams): Promise<StartSelfProfileResult>; - - /** - * Stops profiling the extension itself. Used by VS. - */ - on( - request: 'stopSelfProfile', - handler: (params: StopSelfProfileParams) => Promise<StopSelfProfileResult | Error>, - ): () => void; - /** - * Stops profiling the extension itself. Used by VS. - */ - stopSelfProfileRequest(params: StopSelfProfileParams): Promise<StopSelfProfileResult>; - - /** - * Requests that we get performance information from the runtime. - */ - on( - request: 'getPerformance', - handler: (params: GetPerformanceParams) => Promise<GetPerformanceResult | Error>, - ): () => void; - /** - * Requests that we get performance information from the runtime. - */ - getPerformanceRequest(params: GetPerformanceParams): Promise<GetPerformanceResult>; - - /** - * Fired when requesting a missing source from a sourcemap. UI will offer to disable the sourcemap. - */ - suggestDisableSourcemap(params: SuggestDisableSourcemapEventParams): void; - - /** - * Disables the sourcemapped source and refreshes the stacktrace if paused. - */ - on( - request: 'disableSourcemap', - handler: (params: DisableSourcemapParams) => Promise<DisableSourcemapResult | Error>, - ): () => void; - /** - * Disables the sourcemapped source and refreshes the stacktrace if paused. - */ - disableSourcemapRequest(params: DisableSourcemapParams): Promise<DisableSourcemapResult>; - - /** - * Generates diagnostic information for the debug session. - */ - on( - request: 'createDiagnostics', - handler: (params: CreateDiagnosticsParams) => Promise<CreateDiagnosticsResult | Error>, - ): () => void; - /** - * Generates diagnostic information for the debug session. - */ - createDiagnosticsRequest(params: CreateDiagnosticsParams): Promise<CreateDiagnosticsResult>; - - /** - * Saves recent diagnostic logs for the debug session. - */ - on( - request: 'saveDiagnosticLogs', - handler: (params: SaveDiagnosticLogsParams) => Promise<SaveDiagnosticLogsResult | Error>, - ): () => void; - /** - * Saves recent diagnostic logs for the debug session. - */ - saveDiagnosticLogsRequest(params: SaveDiagnosticLogsParams): Promise<SaveDiagnosticLogsResult>; - - /** - * Shows a prompt to the user suggesting they use the diagnostic tool if breakpoints don't bind. - */ - suggestDiagnosticTool(params: SuggestDiagnosticToolEventParams): void; - - /** - * Opens the diagnostic tool if breakpoints don't bind. - */ - openDiagnosticTool(params: OpenDiagnosticToolEventParams): void; - - /** - * Request WebSocket connection information on a proxy for this debug sessions CDP connection. - */ - on( - request: 'requestCDPProxy', - handler: (params: RequestCDPProxyParams) => Promise<RequestCDPProxyResult | Error>, - ): () => void; - /** - * Request WebSocket connection information on a proxy for this debug sessions CDP connection. - */ - requestCDPProxyRequest(params: RequestCDPProxyParams): Promise<RequestCDPProxyResult>; - - /** - * Adds an excluded caller/target pair. - */ - on( - request: 'setExcludedCallers', - handler: (params: SetExcludedCallersParams) => Promise<SetExcludedCallersResult | Error>, - ): () => void; - /** - * Adds an excluded caller/target pair. - */ - setExcludedCallersRequest(params: SetExcludedCallersParams): Promise<SetExcludedCallersResult>; - - /** - * Configures whether source map stepping is enabled. - */ - on( - request: 'setSourceMapStepping', - handler: (params: SetSourceMapSteppingParams) => Promise<SetSourceMapSteppingResult | Error>, - ): () => void; - /** - * Configures whether source map stepping is enabled. - */ - setSourceMapSteppingRequest( - params: SetSourceMapSteppingParams, - ): Promise<SetSourceMapSteppingResult>; - - /** - * Sets debugger properties. - */ - on( - request: 'setDebuggerProperty', - handler: (params: SetDebuggerPropertyParams) => Promise<SetDebuggerPropertyResult | Error>, - ): () => void; - /** - * Sets debugger properties. - */ - setDebuggerPropertyRequest( - params: SetDebuggerPropertyParams, - ): Promise<SetDebuggerPropertyResult>; - - /** - * The event indicates that one or more capabilities have changed. - */ - on( - request: 'capabilitiesExtended', - handler: (params: CapabilitiesExtendedParams) => Promise<CapabilitiesExtendedResult | Error>, - ): () => void; - /** - * The event indicates that one or more capabilities have changed. - */ - capabilitiesExtendedRequest( - params: CapabilitiesExtendedParams, - ): Promise<CapabilitiesExtendedResult>; - - /** - * Used by evaluate and variables. - */ - on( - request: 'evaluationOptions', - handler: (params: EvaluationOptionsParams) => Promise<EvaluationOptionsResult | Error>, - ): () => void; - /** - * Used by evaluate and variables. - */ - evaluationOptionsRequest(params: EvaluationOptionsParams): Promise<EvaluationOptionsResult>; - - /** - * Sets options for locating symbols. - */ - on( - request: 'setSymbolOptions', - handler: (params: SetSymbolOptionsParams) => Promise<SetSymbolOptionsResult | Error>, - ): () => void; - /** - * Sets options for locating symbols. - */ - setSymbolOptionsRequest(params: SetSymbolOptionsParams): Promise<SetSymbolOptionsResult>; - } - - export interface TestApi { - /** - * The `cancel` request is used by the client in two situations: - * - to indicate that it is no longer interested in the result produced by a specific request issued earlier - * - to cancel a progress sequence. Clients should only call this request if the corresponding capability `supportsCancelRequest` is true. - * This request has a hint characteristic: a debug adapter can only be expected to make a 'best effort' in honoring this request but there are no guarantees. - * The `cancel` request may return an error if it could not cancel an operation but a client should refrain from presenting this error to end users. - * The request that got cancelled still needs to send a response back. This can either be a normal result (`success` attribute true) or an error response (`success` attribute false and the `message` set to `cancelled`). - * Returning partial results from a cancelled request is possible but please note that a client has no generic way for detecting that a response is partial or not. - * The progress that got cancelled still needs to send a `progressEnd` event back. - * A client should not assume that progress just got cancelled after sending the `cancel` request. - */ - cancel(params: CancelParams): Promise<CancelResult>; - - /** - * This event indicates that the debug adapter is ready to accept configuration requests (e.g. `setBreakpoints`, `setExceptionBreakpoints`). - * A debug adapter is expected to send this event when it is ready to accept configuration requests (but not before the `initialize` request has finished). - * The sequence of events/requests is as follows: - * - adapters sends `initialized` event (after the `initialize` request has returned) - * - client sends zero or more `setBreakpoints` requests - * - client sends one `setFunctionBreakpoints` request (if corresponding capability `supportsFunctionBreakpoints` is true) - * - client sends a `setExceptionBreakpoints` request if one or more `exceptionBreakpointFilters` have been defined (or if `supportsConfigurationDoneRequest` is not true) - * - client sends other future configuration requests - * - client sends one `configurationDone` request to indicate the end of the configuration. - */ - on(request: 'initialized', handler: (params: InitializedEventParams) => void): void; - off(request: 'initialized', handler: (params: InitializedEventParams) => void): void; - once( - request: 'initialized', - filter?: (event: InitializedEventParams) => boolean, - ): Promise<InitializedEventParams>; - - /** - * The event indicates that the execution of the debuggee has stopped due to some condition. - * This can be caused by a breakpoint previously set, a stepping request has completed, by executing a debugger statement etc. - */ - on(request: 'stopped', handler: (params: StoppedEventParams) => void): void; - off(request: 'stopped', handler: (params: StoppedEventParams) => void): void; - once( - request: 'stopped', - filter?: (event: StoppedEventParams) => boolean, - ): Promise<StoppedEventParams>; - - /** - * The event indicates that the execution of the debuggee has continued. - * Please note: a debug adapter is not expected to send this event in response to a request that implies that execution continues, e.g. `launch` or `continue`. - * It is only necessary to send a `continued` event if there was no previous request that implied this. - */ - on(request: 'continued', handler: (params: ContinuedEventParams) => void): void; - off(request: 'continued', handler: (params: ContinuedEventParams) => void): void; - once( - request: 'continued', - filter?: (event: ContinuedEventParams) => boolean, - ): Promise<ContinuedEventParams>; - - /** - * The event indicates that the debuggee has exited and returns its exit code. - */ - on(request: 'exited', handler: (params: ExitedEventParams) => void): void; - off(request: 'exited', handler: (params: ExitedEventParams) => void): void; - once( - request: 'exited', - filter?: (event: ExitedEventParams) => boolean, - ): Promise<ExitedEventParams>; - - /** - * The event indicates that debugging of the debuggee has terminated. This does **not** mean that the debuggee itself has exited. - */ - on(request: 'terminated', handler: (params: TerminatedEventParams) => void): void; - off(request: 'terminated', handler: (params: TerminatedEventParams) => void): void; - once( - request: 'terminated', - filter?: (event: TerminatedEventParams) => boolean, - ): Promise<TerminatedEventParams>; - - /** - * The event indicates that a thread has started or exited. - */ - on(request: 'thread', handler: (params: ThreadEventParams) => void): void; - off(request: 'thread', handler: (params: ThreadEventParams) => void): void; - once( - request: 'thread', - filter?: (event: ThreadEventParams) => boolean, - ): Promise<ThreadEventParams>; - - /** - * The event indicates that the target has produced some output. - */ - on(request: 'output', handler: (params: OutputEventParams) => void): void; - off(request: 'output', handler: (params: OutputEventParams) => void): void; - once( - request: 'output', - filter?: (event: OutputEventParams) => boolean, - ): Promise<OutputEventParams>; - - /** - * The event indicates that some information about a breakpoint has changed. - */ - on(request: 'breakpoint', handler: (params: BreakpointEventParams) => void): void; - off(request: 'breakpoint', handler: (params: BreakpointEventParams) => void): void; - once( - request: 'breakpoint', - filter?: (event: BreakpointEventParams) => boolean, - ): Promise<BreakpointEventParams>; - - /** - * The event indicates that some information about a module has changed. - */ - on(request: 'module', handler: (params: ModuleEventParams) => void): void; - off(request: 'module', handler: (params: ModuleEventParams) => void): void; - once( - request: 'module', - filter?: (event: ModuleEventParams) => boolean, - ): Promise<ModuleEventParams>; - - /** - * The event indicates that some source has been added, changed, or removed from the set of all loaded sources. - */ - on(request: 'loadedSource', handler: (params: LoadedSourceEventParams) => void): void; - off(request: 'loadedSource', handler: (params: LoadedSourceEventParams) => void): void; - once( - request: 'loadedSource', - filter?: (event: LoadedSourceEventParams) => boolean, - ): Promise<LoadedSourceEventParams>; - - /** - * The event indicates that the debugger has begun debugging a new process. Either one that it has launched, or one that it has attached to. - */ - on(request: 'process', handler: (params: ProcessEventParams) => void): void; - off(request: 'process', handler: (params: ProcessEventParams) => void): void; - once( - request: 'process', - filter?: (event: ProcessEventParams) => boolean, - ): Promise<ProcessEventParams>; - - /** - * The event indicates that one or more capabilities have changed. - * Since the capabilities are dependent on the client and its UI, it might not be possible to change that at random times (or too late). - * Consequently this event has a hint characteristic: a client can only be expected to make a 'best effort' in honoring individual capabilities but there are no guarantees. - * Only changed capabilities need to be included, all other capabilities keep their values. - */ - on(request: 'capabilities', handler: (params: CapabilitiesEventParams) => void): void; - off(request: 'capabilities', handler: (params: CapabilitiesEventParams) => void): void; - once( - request: 'capabilities', - filter?: (event: CapabilitiesEventParams) => boolean, - ): Promise<CapabilitiesEventParams>; - - /** - * The event signals that a long running operation is about to start and provides additional information for the client to set up a corresponding progress and cancellation UI. - * The client is free to delay the showing of the UI in order to reduce flicker. - * This event should only be sent if the corresponding capability `supportsProgressReporting` is true. - */ - on(request: 'progressStart', handler: (params: ProgressStartEventParams) => void): void; - off(request: 'progressStart', handler: (params: ProgressStartEventParams) => void): void; - once( - request: 'progressStart', - filter?: (event: ProgressStartEventParams) => boolean, - ): Promise<ProgressStartEventParams>; - - /** - * The event signals that the progress reporting needs to be updated with a new message and/or percentage. - * The client does not have to update the UI immediately, but the clients needs to keep track of the message and/or percentage values. - * This event should only be sent if the corresponding capability `supportsProgressReporting` is true. - */ - on(request: 'progressUpdate', handler: (params: ProgressUpdateEventParams) => void): void; - off(request: 'progressUpdate', handler: (params: ProgressUpdateEventParams) => void): void; - once( - request: 'progressUpdate', - filter?: (event: ProgressUpdateEventParams) => boolean, - ): Promise<ProgressUpdateEventParams>; - - /** - * The event signals the end of the progress reporting with a final message. - * This event should only be sent if the corresponding capability `supportsProgressReporting` is true. - */ - on(request: 'progressEnd', handler: (params: ProgressEndEventParams) => void): void; - off(request: 'progressEnd', handler: (params: ProgressEndEventParams) => void): void; - once( - request: 'progressEnd', - filter?: (event: ProgressEndEventParams) => boolean, - ): Promise<ProgressEndEventParams>; - - /** - * This event signals that some state in the debug adapter has changed and requires that the client needs to re-render the data snapshot previously requested. - * Debug adapters do not have to emit this event for runtime changes like stopped or thread events because in that case the client refetches the new state anyway. But the event can be used for example to refresh the UI after rendering formatting has changed in the debug adapter. - * This event should only be sent if the corresponding capability `supportsInvalidatedEvent` is true. - */ - on(request: 'invalidated', handler: (params: InvalidatedEventParams) => void): void; - off(request: 'invalidated', handler: (params: InvalidatedEventParams) => void): void; - once( - request: 'invalidated', - filter?: (event: InvalidatedEventParams) => boolean, - ): Promise<InvalidatedEventParams>; - - /** - * This event indicates that some memory range has been updated. It should only be sent if the corresponding capability `supportsMemoryEvent` is true. - * Clients typically react to the event by re-issuing a `readMemory` request if they show the memory identified by the `memoryReference` and if the updated memory range overlaps the displayed range. Clients should not make assumptions how individual memory references relate to each other, so they should not assume that they are part of a single continuous address range and might overlap. - * Debug adapters can use this event to indicate that the contents of a memory range has changed due to some other request like `setVariable` or `setExpression`. Debug adapters are not expected to emit this event for each and every memory change of a running program, because that information is typically not available from debuggers and it would flood clients with too many events. - */ - on(request: 'memory', handler: (params: MemoryEventParams) => void): void; - off(request: 'memory', handler: (params: MemoryEventParams) => void): void; - once( - request: 'memory', - filter?: (event: MemoryEventParams) => boolean, - ): Promise<MemoryEventParams>; - - /** - * This request is sent from the debug adapter to the client to run a command in a terminal. - * This is typically used to launch the debuggee in a terminal provided by the client. - * This request should only be called if the corresponding client capability `supportsRunInTerminalRequest` is true. - * Client implementations of `runInTerminal` are free to run the command however they choose including issuing the command to a command line interpreter (aka 'shell'). Argument strings passed to the `runInTerminal` request must arrive verbatim in the command to be run. As a consequence, clients which use a shell are responsible for escaping any special shell characters in the argument strings to prevent them from being interpreted (and modified) by the shell. - * Some users may wish to take advantage of shell processing in the argument strings. For clients which implement `runInTerminal` using an intermediary shell, the `argsCanBeInterpretedByShell` property can be set to true. In this case the client is requested not to escape any special shell characters in the argument strings. - */ - runInTerminal(params: RunInTerminalParams): Promise<RunInTerminalResult>; - - /** - * This request is sent from the debug adapter to the client to start a new debug session of the same type as the caller. - * This request should only be sent if the corresponding client capability `supportsStartDebuggingRequest` is true. - * A client implementation of `startDebugging` should start a new debug session (of the same type as the caller) in the same way that the caller's session was started. If the client supports hierarchical debug sessions, the newly created session can be treated as a child of the caller session. - */ - startDebugging(params: StartDebuggingParams): Promise<StartDebuggingResult>; - - /** - * The `initialize` request is sent as the first request from the client to the debug adapter in order to configure it with client capabilities and to retrieve capabilities from the debug adapter. - * Until the debug adapter has responded with an `initialize` response, the client must not send any additional requests or events to the debug adapter. - * In addition the debug adapter is not allowed to send any requests or events to the client until it has responded with an `initialize` response. - * The `initialize` request may only be sent once. - */ - initialize(params: InitializeParams): Promise<InitializeResult>; - - /** - * This request indicates that the client has finished initialization of the debug adapter. - * So it is the last request in the sequence of configuration requests (which was started by the `initialized` event). - * Clients should only call this request if the corresponding capability `supportsConfigurationDoneRequest` is true. - */ - configurationDone(params: ConfigurationDoneParams): Promise<ConfigurationDoneResult>; - - /** - * This launch request is sent from the client to the debug adapter to start the debuggee with or without debugging (if `noDebug` is true). - * Since launching is debugger/runtime specific, the arguments for this request are not part of this specification. - */ - launch(params: LaunchParams): Promise<LaunchResult>; - - /** - * The `attach` request is sent from the client to the debug adapter to attach to a debuggee that is already running. - * Since attaching is debugger/runtime specific, the arguments for this request are not part of this specification. - */ - attach(params: AttachParams): Promise<AttachResult>; - - /** - * Restarts a debug session. Clients should only call this request if the corresponding capability `supportsRestartRequest` is true. - * If the capability is missing or has the value false, a typical client emulates `restart` by terminating the debug adapter first and then launching it anew. - */ - restart(params: RestartParams): Promise<RestartResult>; - - /** - * The `disconnect` request asks the debug adapter to disconnect from the debuggee (thus ending the debug session) and then to shut down itself (the debug adapter). - * In addition, the debug adapter must terminate the debuggee if it was started with the `launch` request. If an `attach` request was used to connect to the debuggee, then the debug adapter must not terminate the debuggee. - * This implicit behavior of when to terminate the debuggee can be overridden with the `terminateDebuggee` argument (which is only supported by a debug adapter if the corresponding capability `supportTerminateDebuggee` is true). - */ - disconnect(params: DisconnectParams): Promise<DisconnectResult>; - - /** - * The `terminate` request is sent from the client to the debug adapter in order to shut down the debuggee gracefully. Clients should only call this request if the capability `supportsTerminateRequest` is true. - * Typically a debug adapter implements `terminate` by sending a software signal which the debuggee intercepts in order to clean things up properly before terminating itself. - * Please note that this request does not directly affect the state of the debug session: if the debuggee decides to veto the graceful shutdown for any reason by not terminating itself, then the debug session just continues. - * Clients can surface the `terminate` request as an explicit command or they can integrate it into a two stage Stop command that first sends `terminate` to request a graceful shutdown, and if that fails uses `disconnect` for a forceful shutdown. - */ - terminate(params: TerminateParams): Promise<TerminateResult>; - - /** - * The `breakpointLocations` request returns all possible locations for source breakpoints in a given range. - * Clients should only call this request if the corresponding capability `supportsBreakpointLocationsRequest` is true. - */ - breakpointLocations(params: BreakpointLocationsParams): Promise<BreakpointLocationsResult>; - - /** - * Sets multiple breakpoints for a single source and clears all previous breakpoints in that source. - * To clear all breakpoint for a source, specify an empty array. - * When a breakpoint is hit, a `stopped` event (with reason `breakpoint`) is generated. - */ - setBreakpoints(params: SetBreakpointsParams): Promise<SetBreakpointsResult>; - - /** - * Replaces all existing function breakpoints with new function breakpoints. - * To clear all function breakpoints, specify an empty array. - * When a function breakpoint is hit, a `stopped` event (with reason `function breakpoint`) is generated. - * Clients should only call this request if the corresponding capability `supportsFunctionBreakpoints` is true. - */ - setFunctionBreakpoints( - params: SetFunctionBreakpointsParams, - ): Promise<SetFunctionBreakpointsResult>; - - /** - * The request configures the debugger's response to thrown exceptions. - * If an exception is configured to break, a `stopped` event is fired (with reason `exception`). - * Clients should only call this request if the corresponding capability `exceptionBreakpointFilters` returns one or more filters. - */ - setExceptionBreakpoints( - params: SetExceptionBreakpointsParams, - ): Promise<SetExceptionBreakpointsResult>; - - /** - * Obtains information on a possible data breakpoint that could be set on an expression or variable. - * Clients should only call this request if the corresponding capability `supportsDataBreakpoints` is true. - */ - dataBreakpointInfo(params: DataBreakpointInfoParams): Promise<DataBreakpointInfoResult>; - - /** - * Replaces all existing data breakpoints with new data breakpoints. - * To clear all data breakpoints, specify an empty array. - * When a data breakpoint is hit, a `stopped` event (with reason `data breakpoint`) is generated. - * Clients should only call this request if the corresponding capability `supportsDataBreakpoints` is true. - */ - setDataBreakpoints(params: SetDataBreakpointsParams): Promise<SetDataBreakpointsResult>; - - /** - * Replaces all existing instruction breakpoints. Typically, instruction breakpoints would be set from a disassembly window. - * To clear all instruction breakpoints, specify an empty array. - * When an instruction breakpoint is hit, a `stopped` event (with reason `instruction breakpoint`) is generated. - * Clients should only call this request if the corresponding capability `supportsInstructionBreakpoints` is true. - */ - setInstructionBreakpoints( - params: SetInstructionBreakpointsParams, - ): Promise<SetInstructionBreakpointsResult>; - - /** - * The request resumes execution of all threads. If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true resumes only the specified thread. If not all threads were resumed, the `allThreadsContinued` attribute of the response should be set to false. - */ - continue(params: ContinueParams): Promise<ContinueResult>; - - /** - * The request executes one step (in the given granularity) for the specified thread and allows all other threads to run freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - */ - next(params: NextParams): Promise<NextResult>; - - /** - * The request resumes the given thread to step into a function/method and allows all other threads to run freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * If the request cannot step into a target, `stepIn` behaves like the `next` request. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - * If there are multiple function/method calls (or other targets) on the source line, - * the argument `targetId` can be used to control into which target the `stepIn` should occur. - * The list of possible targets for a given source line can be retrieved via the `stepInTargets` request. - */ - stepIn(params: StepInParams): Promise<StepInResult>; - - /** - * The request resumes the given thread to step out (return) from a function/method and allows all other threads to run freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - */ - stepOut(params: StepOutParams): Promise<StepOutResult>; - - /** - * The request executes one backward step (in the given granularity) for the specified thread and allows all other threads to run backward freely by resuming them. - * If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. - * The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. - * Clients should only call this request if the corresponding capability `supportsStepBack` is true. - */ - stepBack(params: StepBackParams): Promise<StepBackResult>; - - /** - * The request resumes backward execution of all threads. If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true resumes only the specified thread. If not all threads were resumed, the `allThreadsContinued` attribute of the response should be set to false. - * Clients should only call this request if the corresponding capability `supportsStepBack` is true. - */ - reverseContinue(params: ReverseContinueParams): Promise<ReverseContinueResult>; - - /** - * The request restarts execution of the specified stack frame. - * The debug adapter first sends the response and then a `stopped` event (with reason `restart`) after the restart has completed. - * Clients should only call this request if the corresponding capability `supportsRestartFrame` is true. - */ - restartFrame(params: RestartFrameParams): Promise<RestartFrameResult>; - - /** - * The request sets the location where the debuggee will continue to run. - * This makes it possible to skip the execution of code or to execute code again. - * The code between the current location and the goto target is not executed but skipped. - * The debug adapter first sends the response and then a `stopped` event with reason `goto`. - * Clients should only call this request if the corresponding capability `supportsGotoTargetsRequest` is true (because only then goto targets exist that can be passed as arguments). - */ - goto(params: GotoParams): Promise<GotoResult>; - - /** - * The request suspends the debuggee. - * The debug adapter first sends the response and then a `stopped` event (with reason `pause`) after the thread has been paused successfully. - */ - pause(params: PauseParams): Promise<PauseResult>; - - /** - * The request returns a stacktrace from the current execution state of a given thread. - * A client can request all stack frames by omitting the startFrame and levels arguments. For performance-conscious clients and if the corresponding capability `supportsDelayedStackTraceLoading` is true, stack frames can be retrieved in a piecemeal way with the `startFrame` and `levels` arguments. The response of the `stackTrace` request may contain a `totalFrames` property that hints at the total number of frames in the stack. If a client needs this total number upfront, it can issue a request for a single (first) frame and depending on the value of `totalFrames` decide how to proceed. In any case a client should be prepared to receive fewer frames than requested, which is an indication that the end of the stack has been reached. - */ - stackTrace(params: StackTraceParams): Promise<StackTraceResult>; - - /** - * The request returns the variable scopes for a given stack frame ID. - */ - scopes(params: ScopesParams): Promise<ScopesResult>; - - /** - * Retrieves all child variables for the given variable reference. - * A filter can be used to limit the fetched children to either named or indexed children. - */ - variables(params: VariablesParams): Promise<VariablesResult>; - - /** - * Set the variable with the given name in the variable container to a new value. Clients should only call this request if the corresponding capability `supportsSetVariable` is true. - * If a debug adapter implements both `setVariable` and `setExpression`, a client will only use `setExpression` if the variable has an `evaluateName` property. - */ - setVariable(params: SetVariableParams): Promise<SetVariableResult>; - - /** - * The request retrieves the source code for a given source reference. - */ - source(params: SourceParams): Promise<SourceResult>; - - /** - * The request retrieves a list of all threads. - */ - threads(params: ThreadsParams): Promise<ThreadsResult>; - - /** - * The request terminates the threads with the given ids. - * Clients should only call this request if the corresponding capability `supportsTerminateThreadsRequest` is true. - */ - terminateThreads(params: TerminateThreadsParams): Promise<TerminateThreadsResult>; - - /** - * Modules can be retrieved from the debug adapter with this request which can either return all modules or a range of modules to support paging. - * Clients should only call this request if the corresponding capability `supportsModulesRequest` is true. - */ - modules(params: ModulesParams): Promise<ModulesResult>; - - /** - * Retrieves the set of all sources currently loaded by the debugged process. - * Clients should only call this request if the corresponding capability `supportsLoadedSourcesRequest` is true. - */ - loadedSources(params: LoadedSourcesParams): Promise<LoadedSourcesResult>; - - /** - * Evaluates the given expression in the context of the topmost stack frame. - * The expression has access to any variables and arguments that are in scope. - */ - evaluate(params: EvaluateParams): Promise<EvaluateResult>; - - /** - * Evaluates the given `value` expression and assigns it to the `expression` which must be a modifiable l-value. - * The expressions have access to any variables and arguments that are in scope of the specified frame. - * Clients should only call this request if the corresponding capability `supportsSetExpression` is true. - * If a debug adapter implements both `setExpression` and `setVariable`, a client uses `setExpression` if the variable has an `evaluateName` property. - */ - setExpression(params: SetExpressionParams): Promise<SetExpressionResult>; - - /** - * This request retrieves the possible step-in targets for the specified stack frame. - * These targets can be used in the `stepIn` request. - * Clients should only call this request if the corresponding capability `supportsStepInTargetsRequest` is true. - */ - stepInTargets(params: StepInTargetsParams): Promise<StepInTargetsResult>; - - /** - * This request retrieves the possible goto targets for the specified source location. - * These targets can be used in the `goto` request. - * Clients should only call this request if the corresponding capability `supportsGotoTargetsRequest` is true. - */ - gotoTargets(params: GotoTargetsParams): Promise<GotoTargetsResult>; - - /** - * Returns a list of possible completions for a given caret position and text. - * Clients should only call this request if the corresponding capability `supportsCompletionsRequest` is true. - */ - completions(params: CompletionsParams): Promise<CompletionsResult>; - - /** - * Retrieves the details of the exception that caused this event to be raised. - * Clients should only call this request if the corresponding capability `supportsExceptionInfoRequest` is true. - */ - exceptionInfo(params: ExceptionInfoParams): Promise<ExceptionInfoResult>; - - /** - * Reads bytes from memory at the provided location. - * Clients should only call this request if the corresponding capability `supportsReadMemoryRequest` is true. - */ - readMemory(params: ReadMemoryParams): Promise<ReadMemoryResult>; - - /** - * Writes bytes to memory at the provided location. - * Clients should only call this request if the corresponding capability `supportsWriteMemoryRequest` is true. - */ - writeMemory(params: WriteMemoryParams): Promise<WriteMemoryResult>; - - /** - * Disassembles code stored at the provided location. - * Clients should only call this request if the corresponding capability `supportsDisassembleRequest` is true. - */ - disassemble(params: DisassembleParams): Promise<DisassembleResult>; - - /** - * Enable custom breakpoints. - */ - enableCustomBreakpoints( - params: EnableCustomBreakpointsParams, - ): Promise<EnableCustomBreakpointsResult>; - - /** - * Disable custom breakpoints. - */ - disableCustomBreakpoints( - params: DisableCustomBreakpointsParams, - ): Promise<DisableCustomBreakpointsResult>; - - /** - * Pretty prints source for debugging. - */ - prettyPrintSource(params: PrettyPrintSourceParams): Promise<PrettyPrintSourceResult>; - - /** - * Toggle skip status of file. - */ - toggleSkipFileStatus(params: ToggleSkipFileStatusParams): Promise<ToggleSkipFileStatusResult>; - - /** - * A request to reveal a certain location in the UI. - */ - on( - request: 'revealLocationRequested', - handler: (params: RevealLocationRequestedEventParams) => void, - ): void; - off( - request: 'revealLocationRequested', - handler: (params: RevealLocationRequestedEventParams) => void, - ): void; - once( - request: 'revealLocationRequested', - filter?: (event: RevealLocationRequestedEventParams) => boolean, - ): Promise<RevealLocationRequestedEventParams>; - - /** - * A request to copy a certain string to clipboard. - */ - on(request: 'copyRequested', handler: (params: CopyRequestedEventParams) => void): void; - off(request: 'copyRequested', handler: (params: CopyRequestedEventParams) => void): void; - once( - request: 'copyRequested', - filter?: (event: CopyRequestedEventParams) => boolean, - ): Promise<CopyRequestedEventParams>; - - /** - * An event sent when breakpoint prediction takes a significant amount of time. - */ - on(request: 'longPrediction', handler: (params: LongPredictionEventParams) => void): void; - off(request: 'longPrediction', handler: (params: LongPredictionEventParams) => void): void; - once( - request: 'longPrediction', - filter?: (event: LongPredictionEventParams) => boolean, - ): Promise<LongPredictionEventParams>; - - /** - * Request to launch a browser in the companion extension within the UI. - */ - on( - request: 'launchBrowserInCompanion', - handler: (params: LaunchBrowserInCompanionEventParams) => void, - ): void; - off( - request: 'launchBrowserInCompanion', - handler: (params: LaunchBrowserInCompanionEventParams) => void, - ): void; - once( - request: 'launchBrowserInCompanion', - filter?: (event: LaunchBrowserInCompanionEventParams) => boolean, - ): Promise<LaunchBrowserInCompanionEventParams>; - - /** - * Kills a launched browser companion. - */ - on( - request: 'killCompanionBrowser', - handler: (params: KillCompanionBrowserEventParams) => void, - ): void; - off( - request: 'killCompanionBrowser', - handler: (params: KillCompanionBrowserEventParams) => void, - ): void; - once( - request: 'killCompanionBrowser', - filter?: (event: KillCompanionBrowserEventParams) => boolean, - ): Promise<KillCompanionBrowserEventParams>; - - /** - * Starts taking a profile of the target. - */ - startProfile(params: StartProfileParams): Promise<StartProfileResult>; - - /** - * Stops a running profile. - */ - stopProfile(params: StopProfileParams): Promise<StopProfileResult>; - - /** - * Fired when a profiling state changes. - */ - on(request: 'profileStarted', handler: (params: ProfileStartedEventParams) => void): void; - off(request: 'profileStarted', handler: (params: ProfileStartedEventParams) => void): void; - once( - request: 'profileStarted', - filter?: (event: ProfileStartedEventParams) => boolean, - ): Promise<ProfileStartedEventParams>; - - /** - * Fired when a profiling state changes. - */ - on( - request: 'profilerStateUpdate', - handler: (params: ProfilerStateUpdateEventParams) => void, - ): void; - off( - request: 'profilerStateUpdate', - handler: (params: ProfilerStateUpdateEventParams) => void, - ): void; - once( - request: 'profilerStateUpdate', - filter?: (event: ProfilerStateUpdateEventParams) => boolean, - ): Promise<ProfilerStateUpdateEventParams>; - - /** - * Launches a VS Code extension host in debug mode. - */ - launchVSCode(params: LaunchVSCodeParams): Promise<LaunchVSCodeResult>; - - /** - * Launches a VS Code extension host in debug mode. - */ - launchUnelevated(params: LaunchUnelevatedParams): Promise<LaunchUnelevatedResult>; - - /** - * Check if file exists on remote file system, used in VS. - */ - remoteFileExists(params: RemoteFileExistsParams): Promise<RemoteFileExistsResult>; - - /** - * Focuses the browser page or tab associated with the session. - */ - revealPage(params: RevealPageParams): Promise<RevealPageResult>; - - /** - * Starts profiling the extension itself. Used by VS. - */ - startSelfProfile(params: StartSelfProfileParams): Promise<StartSelfProfileResult>; - - /** - * Stops profiling the extension itself. Used by VS. - */ - stopSelfProfile(params: StopSelfProfileParams): Promise<StopSelfProfileResult>; - - /** - * Requests that we get performance information from the runtime. - */ - getPerformance(params: GetPerformanceParams): Promise<GetPerformanceResult>; - - /** - * Fired when requesting a missing source from a sourcemap. UI will offer to disable the sourcemap. - */ - on( - request: 'suggestDisableSourcemap', - handler: (params: SuggestDisableSourcemapEventParams) => void, - ): void; - off( - request: 'suggestDisableSourcemap', - handler: (params: SuggestDisableSourcemapEventParams) => void, - ): void; - once( - request: 'suggestDisableSourcemap', - filter?: (event: SuggestDisableSourcemapEventParams) => boolean, - ): Promise<SuggestDisableSourcemapEventParams>; - - /** - * Disables the sourcemapped source and refreshes the stacktrace if paused. - */ - disableSourcemap(params: DisableSourcemapParams): Promise<DisableSourcemapResult>; - - /** - * Generates diagnostic information for the debug session. - */ - createDiagnostics(params: CreateDiagnosticsParams): Promise<CreateDiagnosticsResult>; - - /** - * Saves recent diagnostic logs for the debug session. - */ - saveDiagnosticLogs(params: SaveDiagnosticLogsParams): Promise<SaveDiagnosticLogsResult>; - - /** - * Shows a prompt to the user suggesting they use the diagnostic tool if breakpoints don't bind. - */ - on( - request: 'suggestDiagnosticTool', - handler: (params: SuggestDiagnosticToolEventParams) => void, - ): void; - off( - request: 'suggestDiagnosticTool', - handler: (params: SuggestDiagnosticToolEventParams) => void, - ): void; - once( - request: 'suggestDiagnosticTool', - filter?: (event: SuggestDiagnosticToolEventParams) => boolean, - ): Promise<SuggestDiagnosticToolEventParams>; - - /** - * Opens the diagnostic tool if breakpoints don't bind. - */ - on( - request: 'openDiagnosticTool', - handler: (params: OpenDiagnosticToolEventParams) => void, - ): void; - off( - request: 'openDiagnosticTool', - handler: (params: OpenDiagnosticToolEventParams) => void, - ): void; - once( - request: 'openDiagnosticTool', - filter?: (event: OpenDiagnosticToolEventParams) => boolean, - ): Promise<OpenDiagnosticToolEventParams>; - - /** - * Request WebSocket connection information on a proxy for this debug sessions CDP connection. - */ - requestCDPProxy(params: RequestCDPProxyParams): Promise<RequestCDPProxyResult>; - - /** - * Adds an excluded caller/target pair. - */ - setExcludedCallers(params: SetExcludedCallersParams): Promise<SetExcludedCallersResult>; - - /** - * Configures whether source map stepping is enabled. - */ - setSourceMapStepping(params: SetSourceMapSteppingParams): Promise<SetSourceMapSteppingResult>; - - /** - * Sets debugger properties. - */ - setDebuggerProperty(params: SetDebuggerPropertyParams): Promise<SetDebuggerPropertyResult>; - - /** - * The event indicates that one or more capabilities have changed. - */ - capabilitiesExtended(params: CapabilitiesExtendedParams): Promise<CapabilitiesExtendedResult>; - - /** - * Used by evaluate and variables. - */ - evaluationOptions(params: EvaluationOptionsParams): Promise<EvaluationOptionsResult>; - - /** - * Sets options for locating symbols. - */ - setSymbolOptions(params: SetSymbolOptionsParams): Promise<SetSymbolOptionsResult>; - } - - export interface AttachParams { - /** - * Arbitrary data from the previous, restarted session. - * The data is sent as the `restart` attribute of the `terminated` event. - * The client should leave the data intact. - */ - __restart?: any[] | boolean | integer | null | number | object | string; - } - - export interface AttachResult {} - - export interface BreakpointEventParams { - /** - * The reason for the event. - */ - reason: 'changed' | 'new' | 'removed'; - - /** - * The `id` attribute is used to find the target breakpoint, the other attributes are used as the new values. - */ - breakpoint: Breakpoint; - } - - export interface BreakpointLocationsParams { - /** - * The source location of the breakpoints; either `source.path` or `source.reference` must be specified. - */ - source: Source; - - /** - * Start line of range to search possible breakpoint locations in. If only the line is specified, the request returns all possible locations in that line. - */ - line: integer; - - /** - * Start position within `line` to search possible breakpoint locations in. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. If no column is given, the first position in the start line is assumed. - */ - column?: integer; - - /** - * End line of range to search possible breakpoint locations in. If no end line is given, then the end line is assumed to be the start line. - */ - endLine?: integer; - - /** - * End position within `endLine` to search possible breakpoint locations in. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. If no end column is given, the last position in the end line is assumed. - */ - endColumn?: integer; - } - - export interface BreakpointLocationsResult { - /** - * Sorted set of possible breakpoint locations. - */ - breakpoints: BreakpointLocation[]; - } - - export interface CancelParams { - /** - * The ID (attribute `seq`) of the request to cancel. If missing no request is cancelled. - * Both a `requestId` and a `progressId` can be specified in one request. - */ - requestId?: integer; - - /** - * The ID (attribute `progressId`) of the progress to cancel. If missing no progress is cancelled. - * Both a `requestId` and a `progressId` can be specified in one request. - */ - progressId?: string; - } - - export interface CancelResult {} - - export interface CapabilitiesEventParams { - /** - * The set of updated capabilities. - */ - capabilities: Capabilities; - } - - export interface CapabilitiesExtendedParams { - params: CapabilitiesExtended; - } - - export interface CapabilitiesExtendedResult {} - - export interface CompletionsParams { - /** - * Returns completions in the scope of this stack frame. If not specified, the completions are returned for the global scope. - */ - frameId?: integer; - - /** - * One or more source lines. Typically this is the text users have typed into the debug console before they asked for completion. - */ - text: string; - - /** - * The position within `text` for which to determine the completion proposals. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - column: integer; - - /** - * A line for which to determine the completion proposals. If missing the first line of the text is assumed. - */ - line?: integer; - } - - export interface CompletionsResult { - /** - * The possible completions for . - */ - targets: CompletionItem[]; - } - - export interface ConfigurationDoneParams {} - - export interface ConfigurationDoneResult {} - - export interface ContinueParams { - /** - * Specifies the active thread. If the debug adapter supports single thread execution (see `supportsSingleThreadExecutionRequests`) and the argument `singleThread` is true, only the thread with this ID is resumed. - */ - threadId: integer; - - /** - * If this flag is true, execution is resumed only for the thread with given `threadId`. - */ - singleThread?: boolean; - } - - export interface ContinueResult { - /** - * The value true (or a missing property) signals to the client that all threads have been resumed. The value false indicates that not all threads were resumed. - */ - allThreadsContinued?: boolean; - } - - export interface ContinuedEventParams { - /** - * The thread which was continued. - */ - threadId: integer; - - /** - * If `allThreadsContinued` is true, a debug adapter can announce that all threads have continued. - */ - allThreadsContinued?: boolean; - } - - export interface CopyRequestedEventParams { - /** - * Text to copy. - */ - text: string; - } - - export interface CreateDiagnosticsParams { - /** - * Whether the tool is opening from a prompt - */ - fromSuggestion?: boolean; - } - - export interface CreateDiagnosticsResult { - /** - * Location of the generated report on disk - */ - file: string; - } - - export interface DataBreakpointInfoParams { - /** - * Reference to the variable container if the data breakpoint is requested for a child of the container. The `variablesReference` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. - */ - variablesReference?: integer; - - /** - * The name of the variable's child to obtain data breakpoint information for. - * If `variablesReference` isn't specified, this can be an expression. - */ - name: string; - - /** - * When `name` is an expression, evaluate it in the scope of this stack frame. If not specified, the expression is evaluated in the global scope. When `variablesReference` is specified, this property has no effect. - */ - frameId?: integer; - } - - export interface DataBreakpointInfoResult { - /** - * An identifier for the data on which a data breakpoint can be registered with the `setDataBreakpoints` request or null if no data breakpoint is available. - */ - dataId: string | null; - - /** - * UI string that describes on what data the breakpoint is set on or why a data breakpoint is not available. - */ - description: string; - - /** - * Attribute lists the available access types for a potential data breakpoint. A UI client could surface this information. - */ - accessTypes?: DataBreakpointAccessType[]; - - /** - * Attribute indicates that a potential data breakpoint could be persisted across sessions. - */ - canPersist?: boolean; - } - - export interface DisableCustomBreakpointsParams { - /** - * Id of breakpoints to enable. - */ - ids: string[]; - } - - export interface DisableCustomBreakpointsResult {} - - export interface DisableSourcemapParams { - /** - * Source to be pretty printed. - */ - source: Source; - } - - export interface DisableSourcemapResult {} - - export interface DisassembleParams { - /** - * Memory reference to the base location containing the instructions to disassemble. - */ - memoryReference: string; - - /** - * Offset (in bytes) to be applied to the reference location before disassembling. Can be negative. - */ - offset?: integer; - - /** - * Offset (in instructions) to be applied after the byte offset (if any) before disassembling. Can be negative. - */ - instructionOffset?: integer; - - /** - * Number of instructions to disassemble starting at the specified location and offset. - * An adapter must return exactly this number of instructions - any unavailable instructions should be replaced with an implementation-defined 'invalid instruction' value. - */ - instructionCount: integer; - - /** - * If true, the adapter should attempt to resolve memory addresses and other values to symbolic names. - */ - resolveSymbols?: boolean; - } - - export interface DisassembleResult { - /** - * The list of disassembled instructions. - */ - instructions: DisassembledInstruction[]; - } - - export interface DisconnectParams { - /** - * A value of true indicates that this `disconnect` request is part of a restart sequence. - */ - restart?: boolean; - - /** - * Indicates whether the debuggee should be terminated when the debugger is disconnected. - * If unspecified, the debug adapter is free to do whatever it thinks is best. - * The attribute is only honored by a debug adapter if the corresponding capability `supportTerminateDebuggee` is true. - */ - terminateDebuggee?: boolean; - - /** - * Indicates whether the debuggee should stay suspended when the debugger is disconnected. - * If unspecified, the debuggee should resume execution. - * The attribute is only honored by a debug adapter if the corresponding capability `supportSuspendDebuggee` is true. - */ - suspendDebuggee?: boolean; - } - - export interface DisconnectResult {} - - export interface EnableCustomBreakpointsParams { - /** - * Id of breakpoints to enable. - */ - ids: string[]; - } - - export interface EnableCustomBreakpointsResult {} - - export interface EvaluateParams { - /** - * The expression to evaluate. - */ - expression: string; - - /** - * Evaluate the expression in the scope of this stack frame. If not specified, the expression is evaluated in the global scope. - */ - frameId?: integer; - - /** - * The context in which the evaluate request is used. - */ - context?: 'watch' | 'repl' | 'hover' | 'clipboard' | 'variables'; - - /** - * Specifies details on how to format the result. - * The attribute is only honored by a debug adapter if the corresponding capability `supportsValueFormattingOptions` is true. - */ - format?: ValueFormat; - } - - export interface EvaluateResult { - /** - * The result of the evaluate request. - */ - result: string; - - /** - * The type of the evaluate result. - * This attribute should only be returned by a debug adapter if the corresponding capability `supportsVariableType` is true. - */ - type?: string; - - /** - * Properties of an evaluate result that can be used to determine how to render the result in the UI. - */ - presentationHint?: VariablePresentationHint; - - /** - * If `variablesReference` is > 0, the evaluate result is structured and its children can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. - */ - variablesReference: integer; - - /** - * The number of named child variables. - * The client can use this information to present the variables in a paged UI and fetch them in chunks. - * The value should be less than or equal to 2147483647 (2^31-1). - */ - namedVariables?: integer; - - /** - * The number of indexed child variables. - * The client can use this information to present the variables in a paged UI and fetch them in chunks. - * The value should be less than or equal to 2147483647 (2^31-1). - */ - indexedVariables?: integer; - - /** - * A memory reference to a location appropriate for this result. - * For pointer type eval results, this is generally a reference to the memory address contained in the pointer. - * This attribute should be returned by a debug adapter if corresponding capability `supportsMemoryReferences` is true. - */ - memoryReference?: string; - } - - export interface EvaluationOptionsParams { - evaluateParams?: EvaluateParamsExtended; - - variablesParams?: VariablesParamsExtended; - - stackTraceParams?: StackTraceParamsExtended; - } - - export interface EvaluationOptionsResult {} - - export interface ExceptionInfoParams { - /** - * Thread for which exception information should be retrieved. - */ - threadId: integer; - } - - export interface ExceptionInfoResult { - /** - * ID of the exception that was thrown. - */ - exceptionId: string; - - /** - * Descriptive text for the exception. - */ - description?: string; - - /** - * Mode that caused the exception notification to be raised. - */ - breakMode: ExceptionBreakMode; - - /** - * Detailed information about the exception. - */ - details?: ExceptionDetails; - } - - export interface ExitedEventParams { - /** - * The exit code returned from the debuggee. - */ - exitCode: integer; - } - - export interface GetPerformanceParams {} - - export interface GetPerformanceResult { - /** - * Response to 'GetPerformance' request. A key-value list of runtime-dependent details. - */ - metrics?: object; - - /** - * Optional error from the adapter - */ - error?: string; - } - - export interface GotoParams { - /** - * Set the goto target for this thread. - */ - threadId: integer; - - /** - * The location where the debuggee will continue to run. - */ - targetId: integer; - } - - export interface GotoResult {} - - export interface GotoTargetsParams { - /** - * The source location for which the goto targets are determined. - */ - source: Source; - - /** - * The line location for which the goto targets are determined. - */ - line: integer; - - /** - * The position within `line` for which the goto targets are determined. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - column?: integer; - } - - export interface GotoTargetsResult { - /** - * The possible goto targets of the specified location. - */ - targets: GotoTarget[]; - } - - export interface InitializeParams { - /** - * The ID of the client using this adapter. - */ - clientID?: string; - - /** - * The human-readable name of the client using this adapter. - */ - clientName?: string; - - /** - * The ID of the debug adapter. - */ - adapterID: string; - - /** - * The ISO-639 locale of the client using this adapter, e.g. en-US or de-CH. - */ - locale?: string; - - /** - * If true all line numbers are 1-based (default). - */ - linesStartAt1?: boolean; - - /** - * If true all column numbers are 1-based (default). - */ - columnsStartAt1?: boolean; - - /** - * Determines in what format paths are specified. The default is `path`, which is the native format. - */ - pathFormat?: 'path' | 'uri'; - - /** - * Client supports the `type` attribute for variables. - */ - supportsVariableType?: boolean; - - /** - * Client supports the paging of variables. - */ - supportsVariablePaging?: boolean; - - /** - * Client supports the `runInTerminal` request. - */ - supportsRunInTerminalRequest?: boolean; - - /** - * Client supports memory references. - */ - supportsMemoryReferences?: boolean; - - /** - * Client supports progress reporting. - */ - supportsProgressReporting?: boolean; - - /** - * Client supports the `invalidated` event. - */ - supportsInvalidatedEvent?: boolean; - - /** - * Client supports the `memory` event. - */ - supportsMemoryEvent?: boolean; - - /** - * Client supports the `argsCanBeInterpretedByShell` attribute on the `runInTerminal` request. - */ - supportsArgsCanBeInterpretedByShell?: boolean; - - /** - * Client supports the `startDebugging` request. - */ - supportsStartDebuggingRequest?: boolean; - } - - export interface InitializeResult { - /** - * The debug adapter supports the `configurationDone` request. - */ - supportsConfigurationDoneRequest?: boolean; - - /** - * The debug adapter supports function breakpoints. - */ - supportsFunctionBreakpoints?: boolean; - - /** - * The debug adapter supports conditional breakpoints. - */ - supportsConditionalBreakpoints?: boolean; - - /** - * The debug adapter supports breakpoints that break execution after a specified number of hits. - */ - supportsHitConditionalBreakpoints?: boolean; - - /** - * The debug adapter supports a (side effect free) `evaluate` request for data hovers. - */ - supportsEvaluateForHovers?: boolean; - - /** - * Available exception filter options for the `setExceptionBreakpoints` request. - */ - exceptionBreakpointFilters?: ExceptionBreakpointsFilter[]; - - /** - * The debug adapter supports stepping back via the `stepBack` and `reverseContinue` requests. - */ - supportsStepBack?: boolean; - - /** - * The debug adapter supports setting a variable to a value. - */ - supportsSetVariable?: boolean; - - /** - * The debug adapter supports restarting a frame. - */ - supportsRestartFrame?: boolean; - - /** - * The debug adapter supports the `gotoTargets` request. - */ - supportsGotoTargetsRequest?: boolean; - - /** - * The debug adapter supports the `stepInTargets` request. - */ - supportsStepInTargetsRequest?: boolean; - - /** - * The debug adapter supports the `completions` request. - */ - supportsCompletionsRequest?: boolean; - - /** - * The set of characters that should trigger completion in a REPL. If not specified, the UI should assume the `.` character. - */ - completionTriggerCharacters?: string[]; - - /** - * The debug adapter supports the `modules` request. - */ - supportsModulesRequest?: boolean; - - /** - * The set of additional module information exposed by the debug adapter. - */ - additionalModuleColumns?: ColumnDescriptor[]; - - /** - * Checksum algorithms supported by the debug adapter. - */ - supportedChecksumAlgorithms?: ChecksumAlgorithm[]; - - /** - * The debug adapter supports the `restart` request. In this case a client should not implement `restart` by terminating and relaunching the adapter but by calling the `restart` request. - */ - supportsRestartRequest?: boolean; - - /** - * The debug adapter supports `exceptionOptions` on the `setExceptionBreakpoints` request. - */ - supportsExceptionOptions?: boolean; - - /** - * The debug adapter supports a `format` attribute on the `stackTrace`, `variables`, and `evaluate` requests. - */ - supportsValueFormattingOptions?: boolean; - - /** - * The debug adapter supports the `exceptionInfo` request. - */ - supportsExceptionInfoRequest?: boolean; - - /** - * The debug adapter supports the `terminateDebuggee` attribute on the `disconnect` request. - */ - supportTerminateDebuggee?: boolean; - - /** - * The debug adapter supports the `suspendDebuggee` attribute on the `disconnect` request. - */ - supportSuspendDebuggee?: boolean; - - /** - * The debug adapter supports the delayed loading of parts of the stack, which requires that both the `startFrame` and `levels` arguments and the `totalFrames` result of the `stackTrace` request are supported. - */ - supportsDelayedStackTraceLoading?: boolean; - - /** - * The debug adapter supports the `loadedSources` request. - */ - supportsLoadedSourcesRequest?: boolean; - - /** - * The debug adapter supports log points by interpreting the `logMessage` attribute of the `SourceBreakpoint`. - */ - supportsLogPoints?: boolean; - - /** - * The debug adapter supports the `terminateThreads` request. - */ - supportsTerminateThreadsRequest?: boolean; - - /** - * The debug adapter supports the `setExpression` request. - */ - supportsSetExpression?: boolean; - - /** - * The debug adapter supports the `terminate` request. - */ - supportsTerminateRequest?: boolean; - - /** - * The debug adapter supports data breakpoints. - */ - supportsDataBreakpoints?: boolean; - - /** - * The debug adapter supports the `readMemory` request. - */ - supportsReadMemoryRequest?: boolean; - - /** - * The debug adapter supports the `writeMemory` request. - */ - supportsWriteMemoryRequest?: boolean; - - /** - * The debug adapter supports the `disassemble` request. - */ - supportsDisassembleRequest?: boolean; - - /** - * The debug adapter supports the `cancel` request. - */ - supportsCancelRequest?: boolean; - - /** - * The debug adapter supports the `breakpointLocations` request. - */ - supportsBreakpointLocationsRequest?: boolean; - - /** - * The debug adapter supports the `clipboard` context value in the `evaluate` request. - */ - supportsClipboardContext?: boolean; - - /** - * The debug adapter supports stepping granularities (argument `granularity`) for the stepping requests. - */ - supportsSteppingGranularity?: boolean; - - /** - * The debug adapter supports adding breakpoints based on instruction references. - */ - supportsInstructionBreakpoints?: boolean; - - /** - * The debug adapter supports `filterOptions` as an argument on the `setExceptionBreakpoints` request. - */ - supportsExceptionFilterOptions?: boolean; - - /** - * The debug adapter supports the `singleThread` property on the execution requests (`continue`, `next`, `stepIn`, `stepOut`, `reverseContinue`, `stepBack`). - */ - supportsSingleThreadExecutionRequests?: boolean; - } - - export interface InitializedEventParams {} - - export interface InvalidatedEventParams { - /** - * Set of logical areas that got invalidated. This property has a hint characteristic: a client can only be expected to make a 'best effort' in honoring the areas but there are no guarantees. If this property is missing, empty, or if values are not understood, the client should assume a single value `all`. - */ - areas?: InvalidatedAreas[]; - - /** - * If specified, the client only needs to refetch data related to this thread. - */ - threadId?: integer; - - /** - * If specified, the client only needs to refetch data related to this stack frame (and the `threadId` is ignored). - */ - stackFrameId?: integer; - } - - export interface KillCompanionBrowserEventParams { - /** - * Incrementing ID to refer to this browser launch request - */ - launchId: number; - } - - export interface LaunchBrowserInCompanionEventParams { - /** - * Type of browser to launch - */ - type: string; - - /** - * Incrementing ID to refer to this browser launch request - */ - launchId: number; - - /** - * Local port the debug server is listening on - */ - serverPort: number; - - /** - * Server path to connect to - */ - path?: string; - - browserArgs?: string[]; - - attach?: object; - - /** - * Original launch parameters for the debug session - */ - params: object; - } - - export interface LaunchParams { - /** - * If true, the launch request should launch the program without enabling debugging. - */ - noDebug?: boolean; - - /** - * Arbitrary data from the previous, restarted session. - * The data is sent as the `restart` attribute of the `terminated` event. - * The client should leave the data intact. - */ - __restart?: any[] | boolean | integer | null | number | object | string; - } - - export interface LaunchResult {} - - export interface LaunchUnelevatedParams { - process?: string; - - args?: string[]; - } - - export interface LaunchUnelevatedResult {} - - export interface LaunchVSCodeParams { - args: LaunchVSCodeArgument[]; - - env: object; - - debugRenderer?: boolean; - } - - export interface LaunchVSCodeResult { - rendererDebugPort?: number; - } - - export interface LoadedSourceEventParams { - /** - * The reason for the event. - */ - reason: string; - - /** - * The new, changed, or removed source. - */ - source: Source; - } - - export interface LoadedSourcesParams {} - - export interface LoadedSourcesResult { - /** - * Set of loaded sources. - */ - sources: Source[]; - } - - export interface LongPredictionEventParams {} - - export interface MemoryEventParams { - /** - * Memory reference of a memory range that has been updated. - */ - memoryReference: string; - - /** - * Starting offset in bytes where memory has been updated. Can be negative. - */ - offset: integer; - - /** - * Number of bytes updated. - */ - count: integer; - } - - export interface ModuleEventParams { - /** - * The reason for the event. - */ - reason: string; - - /** - * The new, changed, or removed module. In case of `removed` only the module id is used. - */ - module: Module; - } - - export interface ModulesParams { - /** - * The index of the first module to return; if omitted modules start at 0. - */ - startModule?: integer; - - /** - * The number of modules to return. If `moduleCount` is not specified or 0, all modules are returned. - */ - moduleCount?: integer; - } - - export interface ModulesResult { - /** - * All modules or range of modules. - */ - modules: Module[]; - - /** - * The total number of modules available. - */ - totalModules?: integer; - } - - export interface NextParams { - /** - * Specifies the thread for which to resume execution for one step (of the given granularity). - */ - threadId: integer; - - /** - * If this flag is true, all other suspended threads are not resumed. - */ - singleThread?: boolean; - - /** - * Stepping granularity. If no granularity is specified, a granularity of `statement` is assumed. - */ - granularity?: SteppingGranularity; - } - - export interface NextResult {} - - export interface OpenDiagnosticToolEventParams { - /** - * Location of the generated report on disk - */ - file: string; - } - - export interface OutputEventParams { - /** - * The output category. If not specified or if the category is not understood by the client, `console` is assumed. - */ - category?: 'console' | 'important' | 'stdout' | 'stderr' | 'telemetry'; - - /** - * The output to report. - */ - output: string; - - /** - * Support for keeping an output log organized by grouping related messages. - */ - group?: string; - - /** - * If an attribute `variablesReference` exists and its value is > 0, the output contains objects which can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. - */ - variablesReference?: integer; - - /** - * The source location where the output was produced. - */ - source?: Source; - - /** - * The source location's line where the output was produced. - */ - line?: integer; - - /** - * The position in `line` where the output was produced. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - column?: integer; - - /** - * Additional data to report. For the `telemetry` category the data is sent to telemetry, for the other categories the data is shown in JSON format. - */ - data?: any[] | boolean | integer | null | number | object | string; - } - - export interface PauseParams { - /** - * Pause execution for this thread. - */ - threadId: integer; - } - - export interface PauseResult {} - - export interface PrettyPrintSourceParams { - /** - * Source to be pretty printed. - */ - source: Source; - - /** - * Line number of currently selected location to reveal after pretty printing. If not present, nothing is revealed. - */ - line?: integer; - - /** - * Column number of currently selected location to reveal after pretty printing. - */ - column?: integer; - } - - export interface PrettyPrintSourceResult {} - - export interface ProcessEventParams { - /** - * The logical name of the process. This is usually the full path to process's executable file. Example: /home/example/myproj/program.js. - */ - name: string; - - /** - * The system process id of the debugged process. This property is missing for non-system processes. - */ - systemProcessId?: integer; - - /** - * If true, the process is running on the same computer as the debug adapter. - */ - isLocalProcess?: boolean; - - /** - * Describes how the debug engine started debugging this process. - */ - startMethod?: string; - - /** - * The size of a pointer or address for this process, in bits. This value may be used by clients when formatting addresses for display. - */ - pointerSize?: integer; - } - - export interface ProfileStartedEventParams { - /** - * Type of running profile - */ - type: string; - - /** - * Location where the profile is saved. - */ - file: string; - } - - export interface ProfilerStateUpdateEventParams { - /** - * Description of the current state - */ - label: string; - - /** - * Set to false if the profile has now ended - */ - running: boolean; - } - - export interface ProgressEndEventParams { - /** - * The ID that was introduced in the initial `ProgressStartEvent`. - */ - progressId: string; - - /** - * More detailed progress message. If omitted, the previous message (if any) is used. - */ - message?: string; - } - - export interface ProgressStartEventParams { - /** - * An ID that can be used in subsequent `progressUpdate` and `progressEnd` events to make them refer to the same progress reporting. - * IDs must be unique within a debug session. - */ - progressId: string; - - /** - * Short title of the progress reporting. Shown in the UI to describe the long running operation. - */ - title: string; - - /** - * The request ID that this progress report is related to. If specified a debug adapter is expected to emit progress events for the long running request until the request has been either completed or cancelled. - * If the request ID is omitted, the progress report is assumed to be related to some general activity of the debug adapter. - */ - requestId?: integer; - - /** - * If true, the request that reports progress may be cancelled with a `cancel` request. - * So this property basically controls whether the client should use UX that supports cancellation. - * Clients that don't support cancellation are allowed to ignore the setting. - */ - cancellable?: boolean; - - /** - * More detailed progress message. - */ - message?: string; - - /** - * Progress percentage to display (value range: 0 to 100). If omitted no percentage is shown. - */ - percentage?: number; - } - - export interface ProgressUpdateEventParams { - /** - * The ID that was introduced in the initial `progressStart` event. - */ - progressId: string; - - /** - * More detailed progress message. If omitted, the previous message (if any) is used. - */ - message?: string; - - /** - * Progress percentage to display (value range: 0 to 100). If omitted no percentage is shown. - */ - percentage?: number; - } - - export interface ReadMemoryParams { - /** - * Memory reference to the base location from which data should be read. - */ - memoryReference: string; - - /** - * Offset (in bytes) to be applied to the reference location before reading data. Can be negative. - */ - offset?: integer; - - /** - * Number of bytes to read at the specified location and offset. - */ - count: integer; - } - - export interface ReadMemoryResult { - /** - * The address of the first byte of data returned. - * Treated as a hex value if prefixed with `0x`, or as a decimal value otherwise. - */ - address: string; - - /** - * The number of unreadable bytes encountered after the last successfully read byte. - * This can be used to determine the number of bytes that should be skipped before a subsequent `readMemory` request succeeds. - */ - unreadableBytes?: integer; - - /** - * The bytes read from memory, encoded using base64. If the decoded length of `data` is less than the requested `count` in the original `readMemory` request, and `unreadableBytes` is zero or omitted, then the client should assume it's reached the end of readable memory. - */ - data?: string; - } - - export interface RemoteFileExistsParams { - localFilePath?: string; - } - - export interface RemoteFileExistsResult { - /** - * Does the file exist on the remote file system. - */ - doesExists: boolean; - } - - export interface RequestCDPProxyParams {} - - export interface RequestCDPProxyResult { - /** - * Name of the host, on which the CDP proxy is available through a WebSocket. - */ - host: string; - - /** - * Port on the host, under which the CDP proxy is available through a WebSocket. - */ - port: number; - - /** - * Websocket path to connect to. - */ - path: string; - } - - export interface RestartFrameParams { - /** - * Restart the stack frame identified by `frameId`. The `frameId` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. - */ - frameId: integer; - } - - export interface RestartFrameResult {} - - export interface RestartParams { - /** - * The latest version of the `launch` or `attach` configuration. - */ - arguments?: LaunchRequestArguments | AttachRequestArguments; - } - - export interface RestartResult {} - - export interface RevealLocationRequestedEventParams { - /** - * The source to reveal. - */ - source: Source; - - /** - * The line number to reveal. - */ - line?: integer; - - /** - * The column number to reveal. - */ - column?: integer; - } - - export interface RevealPageParams {} - - export interface RevealPageResult {} - - export interface ReverseContinueParams { - /** - * Specifies the active thread. If the debug adapter supports single thread execution (see `supportsSingleThreadExecutionRequests`) and the `singleThread` argument is true, only the thread with this ID is resumed. - */ - threadId: integer; - - /** - * If this flag is true, backward execution is resumed only for the thread with given `threadId`. - */ - singleThread?: boolean; - } - - export interface ReverseContinueResult {} - - export interface RunInTerminalParams { - /** - * What kind of terminal to launch. Defaults to `integrated` if not specified. - */ - kind?: string; - - /** - * Title of the terminal. - */ - title?: string; - - /** - * Working directory for the command. For non-empty, valid paths this typically results in execution of a change directory command. - */ - cwd: string; - - /** - * List of arguments. The first argument is the command to run. - */ - args: string[]; - - /** - * Environment key-value pairs that are added to or removed from the default environment. - */ - env?: object; - - /** - * This property should only be set if the corresponding capability `supportsArgsCanBeInterpretedByShell` is true. If the client uses an intermediary shell to launch the application, then the client must not attempt to escape characters with special meanings for the shell. The user is fully responsible for escaping as needed and that arguments using special characters may not be portable across shells. - */ - argsCanBeInterpretedByShell?: boolean; - } - - export interface RunInTerminalResult { - /** - * The process ID. The value should be less than or equal to 2147483647 (2^31-1). - */ - processId?: integer; - - /** - * The process ID of the terminal shell. The value should be less than or equal to 2147483647 (2^31-1). - */ - shellProcessId?: integer; - } - - export interface SaveDiagnosticLogsParams { - /** - * File where logs should be saved - */ - toFile: string; - } - - export interface SaveDiagnosticLogsResult {} - - export interface ScopesParams { - /** - * Retrieve the scopes for the stack frame identified by `frameId`. The `frameId` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. - */ - frameId: integer; - } - - export interface ScopesResult { - /** - * The scopes of the stack frame. If the array has length zero, there are no scopes available. - */ - scopes: Scope[]; - } - - export interface SetBreakpointsParams { - /** - * The source location of the breakpoints; either `source.path` or `source.sourceReference` must be specified. - */ - source: Source; - - /** - * The code locations of the breakpoints. - */ - breakpoints?: SourceBreakpoint[]; - - /** - * Deprecated: The code locations of the breakpoints. - */ - lines?: integer[]; - - /** - * A value of true indicates that the underlying source has been modified which results in new breakpoint locations. - */ - sourceModified?: boolean; - } - - export interface SetBreakpointsResult { - /** - * Information about the breakpoints. - * The array elements are in the same order as the elements of the `breakpoints` (or the deprecated `lines`) array in the arguments. - */ - breakpoints: Breakpoint[]; - } - - export interface SetDataBreakpointsParams { - /** - * The contents of this array replaces all existing data breakpoints. An empty array clears all data breakpoints. - */ - breakpoints: DataBreakpoint[]; - } - - export interface SetDataBreakpointsResult { - /** - * Information about the data breakpoints. The array elements correspond to the elements of the input argument `breakpoints` array. - */ - breakpoints: Breakpoint[]; - } - - export interface SetDebuggerPropertyParams { - params: SetDebuggerPropertyParams; - } - - export interface SetDebuggerPropertyResult {} - - export interface SetExceptionBreakpointsParams { - /** - * Set of exception filters specified by their ID. The set of all possible exception filters is defined by the `exceptionBreakpointFilters` capability. The `filter` and `filterOptions` sets are additive. - */ - filters: string[]; - - /** - * Set of exception filters and their options. The set of all possible exception filters is defined by the `exceptionBreakpointFilters` capability. This attribute is only honored by a debug adapter if the corresponding capability `supportsExceptionFilterOptions` is true. The `filter` and `filterOptions` sets are additive. - */ - filterOptions?: ExceptionFilterOptions[]; - - /** - * Configuration options for selected exceptions. - * The attribute is only honored by a debug adapter if the corresponding capability `supportsExceptionOptions` is true. - */ - exceptionOptions?: ExceptionOptions[]; - } - - export interface SetExceptionBreakpointsResult { - /** - * Information about the exception breakpoints or filters. - * The breakpoints returned are in the same order as the elements of the `filters`, `filterOptions`, `exceptionOptions` arrays in the arguments. If both `filters` and `filterOptions` are given, the returned array must start with `filters` information first, followed by `filterOptions` information. - */ - breakpoints?: Breakpoint[]; - } - - export interface SetExcludedCallersParams { - callers: ExcludedCaller[]; - } - - export interface SetExcludedCallersResult {} - - export interface SetExpressionParams { - /** - * The l-value expression to assign to. - */ - expression: string; - - /** - * The value expression to assign to the l-value expression. - */ - value: string; - - /** - * Evaluate the expressions in the scope of this stack frame. If not specified, the expressions are evaluated in the global scope. - */ - frameId?: integer; - - /** - * Specifies how the resulting value should be formatted. - */ - format?: ValueFormat; - } - - export interface SetExpressionResult { - /** - * The new value of the expression. - */ - value: string; - - /** - * The type of the value. - * This attribute should only be returned by a debug adapter if the corresponding capability `supportsVariableType` is true. - */ - type?: string; - - /** - * Properties of a value that can be used to determine how to render the result in the UI. - */ - presentationHint?: VariablePresentationHint; - - /** - * If `variablesReference` is > 0, the evaluate result is structured and its children can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. - */ - variablesReference?: integer; - - /** - * The number of named child variables. - * The client can use this information to present the variables in a paged UI and fetch them in chunks. - * The value should be less than or equal to 2147483647 (2^31-1). - */ - namedVariables?: integer; - - /** - * The number of indexed child variables. - * The client can use this information to present the variables in a paged UI and fetch them in chunks. - * The value should be less than or equal to 2147483647 (2^31-1). - */ - indexedVariables?: integer; - } - - export interface SetFunctionBreakpointsParams { - /** - * The function names of the breakpoints. - */ - breakpoints: FunctionBreakpoint[]; - } - - export interface SetFunctionBreakpointsResult { - /** - * Information about the breakpoints. The array elements correspond to the elements of the `breakpoints` array. - */ - breakpoints: Breakpoint[]; - } - - export interface SetInstructionBreakpointsParams { - /** - * The instruction references of the breakpoints - */ - breakpoints: InstructionBreakpoint[]; - } - - export interface SetInstructionBreakpointsResult { - /** - * Information about the breakpoints. The array elements correspond to the elements of the `breakpoints` array. - */ - breakpoints: Breakpoint[]; - } - - export interface SetSourceMapSteppingParams { - enabled: boolean; - } - - export interface SetSourceMapSteppingResult {} - - export interface SetSymbolOptionsParams {} - - export interface SetSymbolOptionsResult {} - - export interface SetVariableParams { - /** - * The reference of the variable container. The `variablesReference` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. - */ - variablesReference: integer; - - /** - * The name of the variable in the container. - */ - name: string; - - /** - * The value of the variable. - */ - value: string; - - /** - * Specifies details on how to format the response value. - */ - format?: ValueFormat; - } - - export interface SetVariableResult { - /** - * The new value of the variable. - */ - value: string; - - /** - * The type of the new value. Typically shown in the UI when hovering over the value. - */ - type?: string; - - /** - * If `variablesReference` is > 0, the new value is structured and its children can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. - */ - variablesReference?: integer; - - /** - * The number of named child variables. - * The client can use this information to present the variables in a paged UI and fetch them in chunks. - * The value should be less than or equal to 2147483647 (2^31-1). - */ - namedVariables?: integer; - - /** - * The number of indexed child variables. - * The client can use this information to present the variables in a paged UI and fetch them in chunks. - * The value should be less than or equal to 2147483647 (2^31-1). - */ - indexedVariables?: integer; - } - - export interface SourceParams { - /** - * Specifies the source content to load. Either `source.path` or `source.sourceReference` must be specified. - */ - source?: Source; - - /** - * The reference to the source. This is the same as `source.sourceReference`. - * This is provided for backward compatibility since old clients do not understand the `source` attribute. - */ - sourceReference: integer; - } - - export interface SourceResult { - /** - * Content of the source reference. - */ - content: string; - - /** - * Content type (MIME type) of the source. - */ - mimeType?: string; - } - - export interface StackTraceParams { - /** - * Retrieve the stacktrace for this thread. - */ - threadId: integer; - - /** - * The index of the first frame to return; if omitted frames start at 0. - */ - startFrame?: integer; - - /** - * The maximum number of frames to return. If levels is not specified or 0, all frames are returned. - */ - levels?: integer; - - /** - * Specifies details on how to format the stack frames. - * The attribute is only honored by a debug adapter if the corresponding capability `supportsValueFormattingOptions` is true. - */ - format?: StackFrameFormat; - } - - export interface StackTraceResult { - /** - * The frames of the stack frame. If the array has length zero, there are no stack frames available. - * This means that there is no location information available. - */ - stackFrames: StackFrame[]; - - /** - * The total number of frames available in the stack. If omitted or if `totalFrames` is larger than the available frames, a client is expected to request frames until a request returns less frames than requested (which indicates the end of the stack). Returning monotonically increasing `totalFrames` values for subsequent requests can be used to enforce paging in the client. - */ - totalFrames?: integer; - } - - export interface StartDebuggingParams { - /** - * Arguments passed to the new debug session. The arguments must only contain properties understood by the `launch` or `attach` requests of the debug adapter and they must not contain any client-specific properties (e.g. `type`) or client-specific features (e.g. substitutable 'variables'). - */ - configuration: object; - - /** - * Indicates whether the new debug session should be started with a `launch` or `attach` request. - */ - request: string; - } - - export interface StartDebuggingResult {} - - export interface StartProfileParams { - /** - * Breakpoints where we should stop once hit. - */ - stopAtBreakpoint?: number[]; - - /** - * Type of profile that should be taken - */ - type: string; - - /** - * Additional arguments for the type of profiler - */ - params?: object; - } - - export interface StartProfileResult {} - - export interface StartSelfProfileParams { - /** - * File where the profile should be saved - */ - file: string; - } - - export interface StartSelfProfileResult {} - - export interface StepBackParams { - /** - * Specifies the thread for which to resume execution for one step backwards (of the given granularity). - */ - threadId: integer; - - /** - * If this flag is true, all other suspended threads are not resumed. - */ - singleThread?: boolean; - - /** - * Stepping granularity to step. If no granularity is specified, a granularity of `statement` is assumed. - */ - granularity?: SteppingGranularity; - } - - export interface StepBackResult {} - - export interface StepInParams { - /** - * Specifies the thread for which to resume execution for one step-into (of the given granularity). - */ - threadId: integer; - - /** - * If this flag is true, all other suspended threads are not resumed. - */ - singleThread?: boolean; - - /** - * Id of the target to step into. - */ - targetId?: integer; - - /** - * Stepping granularity. If no granularity is specified, a granularity of `statement` is assumed. - */ - granularity?: SteppingGranularity; - } - - export interface StepInResult {} - - export interface StepInTargetsParams { - /** - * The stack frame for which to retrieve the possible step-in targets. - */ - frameId: integer; - } - - export interface StepInTargetsResult { - /** - * The possible step-in targets of the specified source location. - */ - targets: StepInTarget[]; - } - - export interface StepOutParams { - /** - * Specifies the thread for which to resume execution for one step-out (of the given granularity). - */ - threadId: integer; - - /** - * If this flag is true, all other suspended threads are not resumed. - */ - singleThread?: boolean; - - /** - * Stepping granularity. If no granularity is specified, a granularity of `statement` is assumed. - */ - granularity?: SteppingGranularity; - } - - export interface StepOutResult {} - - export interface StopProfileParams {} - - export interface StopProfileResult {} - - export interface StopSelfProfileParams {} - - export interface StopSelfProfileResult {} - - export interface StoppedEventParams { - /** - * The reason for the event. - * For backward compatibility this string is shown in the UI if the `description` attribute is missing (but it must not be translated). - */ - reason: - | 'step' - | 'breakpoint' - | 'exception' - | 'pause' - | 'entry' - | 'goto' - | 'function breakpoint' - | 'data breakpoint' - | 'instruction breakpoint'; - - /** - * The full reason for the event, e.g. 'Paused on exception'. This string is shown in the UI as is and can be translated. - */ - description?: string; - - /** - * The thread which was stopped. - */ - threadId?: integer; - - /** - * A value of true hints to the client that this event should not change the focus. - */ - preserveFocusHint?: boolean; - - /** - * Additional information. E.g. if reason is `exception`, text contains the exception name. This string is shown in the UI. - */ - text?: string; - - /** - * If `allThreadsStopped` is true, a debug adapter can announce that all threads have stopped. - * - The client should use this information to enable that all threads can be expanded to access their stacktraces. - * - If the attribute is missing or false, only the thread with the given `threadId` can be expanded. - */ - allThreadsStopped?: boolean; - - /** - * Ids of the breakpoints that triggered the event. In most cases there is only a single breakpoint but here are some examples for multiple breakpoints: - * - Different types of breakpoints map to the same location. - * - Multiple source breakpoints get collapsed to the same instruction by the compiler/runtime. - * - Multiple function breakpoints with different function names map to the same location. - */ - hitBreakpointIds?: integer[]; - } - - export interface SuggestDiagnosticToolEventParams {} - - export interface SuggestDisableSourcemapEventParams { - /** - * Source to be pretty printed. - */ - source: Source; - } - - export interface TerminateParams { - /** - * A value of true indicates that this `terminate` request is part of a restart sequence. - */ - restart?: boolean; - } - - export interface TerminateResult {} - - export interface TerminateThreadsParams { - /** - * Ids of threads to be terminated. - */ - threadIds?: integer[]; - } - - export interface TerminateThreadsResult {} - - export interface TerminatedEventParams { - /** - * A debug adapter may set `restart` to true (or to an arbitrary object) to request that the client restarts the session. - * The value is not interpreted by the client and passed unmodified as an attribute `__restart` to the `launch` and `attach` requests. - */ - restart?: any[] | boolean | integer | null | number | object | string; - } - - export interface ThreadEventParams { - /** - * The reason for the event. - */ - reason: 'started' | 'exited'; - - /** - * The identifier of the thread. - */ - threadId: integer; - } - - export interface ThreadsParams {} - - export interface ThreadsResult { - /** - * All threads. - */ - threads: Thread[]; - } - - export interface ToggleSkipFileStatusParams { - /** - * Url of file to be skipped. - */ - resource?: string; - - /** - * Source reference number of file. - */ - sourceReference?: number; - } - - export interface ToggleSkipFileStatusResult {} - - export interface VariablesParams { - /** - * The variable for which to retrieve its children. The `variablesReference` must have been obtained in the current suspended state. See 'Lifetime of Object References' in the Overview section for details. - */ - variablesReference: integer; - - /** - * Filter to limit the child variables to either named or indexed. If omitted, both types are fetched. - */ - filter?: string; - - /** - * The index of the first variable to return; if omitted children start at 0. - */ - start?: integer; - - /** - * The number of variables to return. If count is missing or 0, all variables are returned. - */ - count?: integer; - - /** - * Specifies details on how to format the Variable values. - * The attribute is only honored by a debug adapter if the corresponding capability `supportsValueFormattingOptions` is true. - */ - format?: ValueFormat; - } - - export interface VariablesResult { - /** - * All (or a range) of variables for the given variable reference. - */ - variables: Variable[]; - } - - export interface WriteMemoryParams { - /** - * Memory reference to the base location to which data should be written. - */ - memoryReference: string; - - /** - * Offset (in bytes) to be applied to the reference location before writing data. Can be negative. - */ - offset?: integer; - - /** - * Property to control partial writes. If true, the debug adapter should attempt to write memory even if the entire memory region is not writable. In such a case the debug adapter should stop after hitting the first byte of memory that cannot be written and return the number of bytes written in the response via the `offset` and `bytesWritten` properties. - * If false or missing, a debug adapter should attempt to verify the region is writable before writing, and fail the response if it is not. - */ - allowPartial?: boolean; - - /** - * Bytes to write, encoded using base64. - */ - data: string; - } - - export interface WriteMemoryResult { - /** - * Property that should be returned when `allowPartial` is true to indicate the offset of the first byte of data successfully written. Can be negative. - */ - offset?: integer; - - /** - * Property that should be returned when `allowPartial` is true to indicate the number of bytes starting from address that were successfully written. - */ - bytesWritten?: integer; - } - - /** - * A Variable is a name/value pair. - * The `type` attribute is shown if space permits or when hovering over the variable's name. - * The `kind` attribute is used to render additional properties of the variable, e.g. different icons can be used to indicate that a variable is public or private. - * If the value is structured (has children), a handle is provided to retrieve the children with the `variables` request. - * If the number of named or indexed children is large, the numbers should be returned via the `namedVariables` and `indexedVariables` attributes. - * The client can use this information to present the children in a paged UI and fetch them in chunks. - */ - export interface Variable { - /** - * The variable's name. - */ - name: string; - - /** - * The variable's value. - * This can be a multi-line text, e.g. for a function the body of a function. - * For structured variables (which do not have a simple value), it is recommended to provide a one-line representation of the structured object. This helps to identify the structured object in the collapsed state when its children are not yet visible. - * An empty string can be used if no value should be shown in the UI. - */ - value: string; - - /** - * The type of the variable's value. Typically shown in the UI when hovering over the value. - * This attribute should only be returned by a debug adapter if the corresponding capability `supportsVariableType` is true. - */ - type?: string; - - /** - * Properties of a variable that can be used to determine how to render the variable in the UI. - */ - presentationHint?: VariablePresentationHint; - - /** - * The evaluatable name of this variable which can be passed to the `evaluate` request to fetch the variable's value. - */ - evaluateName?: string; - - /** - * If `variablesReference` is > 0, the variable is structured and its children can be retrieved by passing `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. - */ - variablesReference: integer; - - /** - * The number of named child variables. - * The client can use this information to present the children in a paged UI and fetch them in chunks. - */ - namedVariables?: integer; - - /** - * The number of indexed child variables. - * The client can use this information to present the children in a paged UI and fetch them in chunks. - */ - indexedVariables?: integer; - - /** - * The memory reference for the variable if the variable represents executable code, such as a function pointer. - * This attribute is only required if the corresponding capability `supportsMemoryReferences` is true. - */ - memoryReference?: string; - } - - /** - * A Thread - */ - export interface Thread { - /** - * Unique identifier for the thread. - */ - id: integer; - - /** - * The name of the thread. - */ - name: string; - } - - /** - * A `StepInTarget` can be used in the `stepIn` request and determines into which single target the `stepIn` request should step. - */ - export interface StepInTarget { - /** - * Unique identifier for a step-in target. - */ - id: integer; - - /** - * The name of the step-in target (shown in the UI). - */ - label: string; - - /** - * The line of the step-in target. - */ - line?: integer; - - /** - * Start position of the range covered by the step in target. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - column?: integer; - - /** - * The end line of the range covered by the step-in target. - */ - endLine?: integer; - - /** - * End position of the range covered by the step in target. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - endColumn?: integer; - } - - /** - * A Stackframe contains the source location. - */ - export interface StackFrame { - /** - * An identifier for the stack frame. It must be unique across all threads. - * This id can be used to retrieve the scopes of the frame with the `scopes` request or to restart the execution of a stack frame. - */ - id: integer; - - /** - * The name of the stack frame, typically a method name. - */ - name: string; - - /** - * The source of the frame. - */ - source?: Source; - - /** - * The line within the source of the frame. If the source attribute is missing or doesn't exist, `line` is 0 and should be ignored by the client. - */ - line: integer; - - /** - * Start position of the range covered by the stack frame. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. If attribute `source` is missing or doesn't exist, `column` is 0 and should be ignored by the client. - */ - column: integer; - - /** - * The end line of the range covered by the stack frame. - */ - endLine?: integer; - - /** - * End position of the range covered by the stack frame. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - endColumn?: integer; - - /** - * Indicates whether this frame can be restarted with the `restart` request. Clients should only use this if the debug adapter supports the `restart` request and the corresponding capability `supportsRestartRequest` is true. If a debug adapter has this capability, then `canRestart` defaults to `true` if the property is absent. - */ - canRestart?: boolean; - - /** - * A memory reference for the current instruction pointer in this frame. - */ - instructionPointerReference?: string; - - /** - * The module associated with this frame, if any. - */ - moduleId?: integer | string; - - /** - * A hint for how to present this frame in the UI. - * A value of `label` can be used to indicate that the frame is an artificial frame that is used as a visual label or separator. A value of `subtle` can be used to change the appearance of a frame in a 'subtle' way. - */ - presentationHint?: string; - } - - export interface StackFrameFormat extends ValueFormat { - /** - * Displays parameters for the stack frame. - */ - parameters?: boolean; - - /** - * Displays the types of parameters for the stack frame. - */ - parameterTypes?: boolean; - - /** - * Displays the names of parameters for the stack frame. - */ - parameterNames?: boolean; - - /** - * Displays the values of parameters for the stack frame. - */ - parameterValues?: boolean; - - /** - * Displays the line number of the stack frame. - */ - line?: boolean; - - /** - * Displays the module of the stack frame. - */ - module?: boolean; - - /** - * Includes all stack frames, including those the debug adapter might otherwise hide. - */ - includeAll?: boolean; - } - - /** - * Properties of a breakpoint passed to the `setInstructionBreakpoints` request - */ - export interface InstructionBreakpoint { - /** - * The instruction reference of the breakpoint. - * This should be a memory or instruction pointer reference from an `EvaluateResponse`, `Variable`, `StackFrame`, `GotoTarget`, or `Breakpoint`. - */ - instructionReference: string; - - /** - * The offset from the instruction reference. - * This can be negative. - */ - offset?: integer; - - /** - * An expression for conditional breakpoints. - * It is only honored by a debug adapter if the corresponding capability `supportsConditionalBreakpoints` is true. - */ - condition?: string; - - /** - * An expression that controls how many hits of the breakpoint are ignored. - * The debug adapter is expected to interpret the expression as needed. - * The attribute is only honored by a debug adapter if the corresponding capability `supportsHitConditionalBreakpoints` is true. - */ - hitCondition?: string; - } - - /** - * Properties of a breakpoint passed to the `setFunctionBreakpoints` request. - */ - export interface FunctionBreakpoint { - /** - * The name of the function. - */ - name: string; - - /** - * An expression for conditional breakpoints. - * It is only honored by a debug adapter if the corresponding capability `supportsConditionalBreakpoints` is true. - */ - condition?: string; - - /** - * An expression that controls how many hits of the breakpoint are ignored. - * The debug adapter is expected to interpret the expression as needed. - * The attribute is only honored by a debug adapter if the corresponding capability `supportsHitConditionalBreakpoints` is true. - */ - hitCondition?: string; - } - - export interface ExcludedCaller { - target: CallerLocation; - - caller: CallerLocation; - } - - export interface CallerLocation { - line: integer; - - column: integer; - - /** - * Source to be pretty printed. - */ - source: Source; - } - - /** - * An `ExceptionOptions` assigns configuration options to a set of exceptions. - */ - export interface ExceptionOptions { - /** - * A path that selects a single or multiple exceptions in a tree. If `path` is missing, the whole tree is selected. - * By convention the first segment of the path is a category that is used to group exceptions in the UI. - */ - path?: ExceptionPathSegment[]; - - /** - * Condition when a thrown exception should result in a break. - */ - breakMode: ExceptionBreakMode; - } - - /** - * An `ExceptionPathSegment` represents a segment in a path that is used to match leafs or nodes in a tree of exceptions. - * If a segment consists of more than one name, it matches the names provided if `negate` is false or missing, or it matches anything except the names provided if `negate` is true. - */ - export interface ExceptionPathSegment { - /** - * If false or missing this segment matches the names provided, otherwise it matches anything except the names provided. - */ - negate?: boolean; - - /** - * Depending on the value of `negate` the names that should match or not match. - */ - names: string[]; - } - - /** - * An `ExceptionFilterOptions` is used to specify an exception filter together with a condition for the `setExceptionBreakpoints` request. - */ - export interface ExceptionFilterOptions { - /** - * ID of an exception filter returned by the `exceptionBreakpointFilters` capability. - */ - filterId: string; - - /** - * An expression for conditional exceptions. - * The exception breaks into the debugger if the result of the condition is true. - */ - condition?: string; - } - - /** - * Arguments for "setDebuggerProperty" request. Properties are determined by debugger. - */ - export interface SetDebuggerPropertyParams {} - - /** - * Properties of a data breakpoint passed to the `setDataBreakpoints` request. - */ - export interface DataBreakpoint { - /** - * An id representing the data. This id is returned from the `dataBreakpointInfo` request. - */ - dataId: string; - - /** - * The access type of the data. - */ - accessType?: DataBreakpointAccessType; - - /** - * An expression for conditional breakpoints. - */ - condition?: string; - - /** - * An expression that controls how many hits of the breakpoint are ignored. - * The debug adapter is expected to interpret the expression as needed. - */ - hitCondition?: string; - } - - /** - * Properties of a breakpoint or logpoint passed to the `setBreakpoints` request. - */ - export interface SourceBreakpoint { - /** - * The source line of the breakpoint or logpoint. - */ - line: integer; - - /** - * Start position within source line of the breakpoint or logpoint. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - column?: integer; - - /** - * The expression for conditional breakpoints. - * It is only honored by a debug adapter if the corresponding capability `supportsConditionalBreakpoints` is true. - */ - condition?: string; - - /** - * The expression that controls how many hits of the breakpoint are ignored. - * The debug adapter is expected to interpret the expression as needed. - * The attribute is only honored by a debug adapter if the corresponding capability `supportsHitConditionalBreakpoints` is true. - * If both this property and `condition` are specified, `hitCondition` should be evaluated only if the `condition` is met, and the debug adapter should stop only if both conditions are met. - */ - hitCondition?: string; - - /** - * If this attribute exists and is non-empty, the debug adapter must not 'break' (stop) - * but log the message instead. Expressions within `{}` are interpolated. - * The attribute is only honored by a debug adapter if the corresponding capability `supportsLogPoints` is true. - * If either `hitCondition` or `condition` is specified, then the message should only be logged if those conditions are met. - */ - logMessage?: string; - } - - /** - * A `Scope` is a named container for variables. Optionally a scope can map to a source or a range within a source. - */ - export interface Scope { - /** - * Name of the scope such as 'Arguments', 'Locals', or 'Registers'. This string is shown in the UI as is and can be translated. - */ - name: string; - - /** - * A hint for how to present this scope in the UI. If this attribute is missing, the scope is shown with a generic UI. - */ - presentationHint?: 'arguments' | 'locals' | 'registers'; - - /** - * The variables of this scope can be retrieved by passing the value of `variablesReference` to the `variables` request as long as execution remains suspended. See 'Lifetime of Object References' in the Overview section for details. - */ - variablesReference: integer; - - /** - * The number of named variables in this scope. - * The client can use this information to present the variables in a paged UI and fetch them in chunks. - */ - namedVariables?: integer; - - /** - * The number of indexed variables in this scope. - * The client can use this information to present the variables in a paged UI and fetch them in chunks. - */ - indexedVariables?: integer; - - /** - * If true, the number of variables in this scope is large or expensive to retrieve. - */ - expensive: boolean; - - /** - * The source for this scope. - */ - source?: Source; - - /** - * The start line of the range covered by this scope. - */ - line?: integer; - - /** - * Start position of the range covered by the scope. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - column?: integer; - - /** - * The end line of the range covered by this scope. - */ - endLine?: integer; - - /** - * End position of the range covered by the scope. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - endColumn?: integer; - } - - /** - * Arguments for `attach` request. Additional attributes are implementation specific. - */ - export interface AttachRequestArguments { - /** - * Arbitrary data from the previous, restarted session. - * The data is sent as the `restart` attribute of the `terminated` event. - * The client should leave the data intact. - */ - __restart?: any[] | boolean | integer | null | number | object | string; - } - - /** - * Arguments for `launch` request. Additional attributes are implementation specific. - */ - export interface LaunchRequestArguments { - /** - * If true, the launch request should launch the program without enabling debugging. - */ - noDebug?: boolean; - - /** - * Arbitrary data from the previous, restarted session. - * The data is sent as the `restart` attribute of the `terminated` event. - * The client should leave the data intact. - */ - __restart?: any[] | boolean | integer | null | number | object | string; - } - - /** - * The granularity of one 'step' in the stepping requests `next`, `stepIn`, `stepOut`, and `stepBack`. - */ - export type SteppingGranularity = string; - - /** - * A Module object represents a row in the modules view. - * The `id` attribute identifies a module in the modules view and is used in a `module` event for identifying a module for adding, updating or deleting. - * The `name` attribute is used to minimally render the module in the UI. - * - * Additional attributes can be added to the module. They show up in the module view if they have a corresponding `ColumnDescriptor`. - * - * To avoid an unnecessary proliferation of additional attributes with similar semantics but different names, we recommend to re-use attributes from the 'recommended' list below first, and only introduce new attributes if nothing appropriate could be found. - */ - export interface Module { - /** - * Unique identifier for the module. - */ - id: integer | string; - - /** - * A name of the module. - */ - name: string; - - /** - * Logical full path to the module. The exact definition is implementation defined, but usually this would be a full path to the on-disk file for the module. - */ - path?: string; - - /** - * True if the module is optimized. - */ - isOptimized?: boolean; - - /** - * True if the module is considered 'user code' by a debugger that supports 'Just My Code'. - */ - isUserCode?: boolean; - - /** - * Version of Module. - */ - version?: string; - - /** - * User-understandable description of if symbols were found for the module (ex: 'Symbols Loaded', 'Symbols not found', etc.) - */ - symbolStatus?: string; - - /** - * Logical full path to the symbol file. The exact definition is implementation defined. - */ - symbolFilePath?: string; - - /** - * Module created or modified, encoded as a RFC 3339 timestamp. - */ - dateTimeStamp?: string; - - /** - * Address range covered by this module. - */ - addressRange?: string; - } - - /** - * This interface represents a single command line argument split into a "prefix" and a "path" half. The optional "prefix" contains arbitrary text and the optional "path" contains a file system path. Concatenating both results in the original command line argument. - */ - export interface LaunchVSCodeArgument { - path?: string; - - prefix?: string; - } - - /** - * Logical areas that can be invalidated by the `invalidated` event. - */ - export type InvalidatedAreas = string; - - /** - * Names of checksum algorithms that may be supported by a debug adapter. - */ - export type ChecksumAlgorithm = string; - - /** - * A `ColumnDescriptor` specifies what module attribute to show in a column of the modules view, how to format it, - * and what the column's label should be. - * It is only used if the underlying UI actually supports this level of customization. - */ - export interface ColumnDescriptor { - /** - * Name of the attribute rendered in this column. - */ - attributeName: string; - - /** - * Header UI label of column. - */ - label: string; - - /** - * Format to use for the rendered values in this column. TBD how the format strings looks like. - */ - format?: string; - - /** - * Datatype of values in this column. Defaults to `string` if not specified. - */ - type?: string; - - /** - * Width of this column in characters (hint only). - */ - width?: integer; - } - - /** - * An `ExceptionBreakpointsFilter` is shown in the UI as an filter option for configuring how exceptions are dealt with. - */ - export interface ExceptionBreakpointsFilter { - /** - * The internal ID of the filter option. This value is passed to the `setExceptionBreakpoints` request. - */ - filter: string; - - /** - * The name of the filter option. This is shown in the UI. - */ - label: string; - - /** - * A help text providing additional information about the exception filter. This string is typically shown as a hover and can be translated. - */ - description?: string; - - /** - * Initial value of the filter option. If not specified a value false is assumed. - */ - default?: boolean; - - /** - * Controls whether a condition can be specified for this filter option. If false or missing, a condition can not be set. - */ - supportsCondition?: boolean; - - /** - * A help text providing information about the condition. This string is shown as the placeholder text for a text box and can be translated. - */ - conditionDescription?: string; - } - - /** - * A `GotoTarget` describes a code location that can be used as a target in the `goto` request. - * The possible goto targets can be determined via the `gotoTargets` request. - */ - export interface GotoTarget { - /** - * Unique identifier for a goto target. This is used in the `goto` request. - */ - id: integer; - - /** - * The name of the goto target (shown in the UI). - */ - label: string; - - /** - * The line of the goto target. - */ - line: integer; - - /** - * The column of the goto target. - */ - column?: integer; - - /** - * The end line of the range covered by the goto target. - */ - endLine?: integer; - - /** - * The end column of the range covered by the goto target. - */ - endColumn?: integer; - - /** - * A memory reference for the instruction pointer value represented by this target. - */ - instructionPointerReference?: string; - } - - /** - * Detailed information about an exception that has occurred. - */ - export interface ExceptionDetails { - /** - * Message contained in the exception. - */ - message?: string; - - /** - * Short type name of the exception object. - */ - typeName?: string; - - /** - * Fully-qualified type name of the exception object. - */ - fullTypeName?: string; - - /** - * An expression that can be evaluated in the current scope to obtain the exception object. - */ - evaluateName?: string; - - /** - * Stack trace at the time the exception was thrown. - */ - stackTrace?: string; - - /** - * Details of the exception contained by this exception, if any. - */ - innerException?: ExceptionDetails[]; - } - - /** - * This enumeration defines all possible conditions when a thrown exception should result in a break. - * never: never breaks, - * always: always breaks, - * unhandled: breaks when exception unhandled, - * userUnhandled: breaks if the exception is not handled by user code. - */ - export type ExceptionBreakMode = string; - - export interface StackTraceParamsExtended extends StackTraceParams { - noFuncEval?: boolean; - } - - export interface VariablesParamsExtended extends VariablesParams { - evaluationOptions?: EvaluationOptions; - } - - /** - * Options passed to expression evaluation commands ("evaluate" and "variables") to control how the evaluation occurs. - */ - export interface EvaluationOptions { - /** - * Evaluate the expression as a statement. - */ - treatAsStatement?: boolean; - - /** - * Allow variables to be declared as part of the expression. - */ - allowImplicitVars?: boolean; - - /** - * Evaluate without side effects. - */ - noSideEffects?: boolean; - - /** - * Exclude funceval during evaluation. - */ - noFuncEval?: boolean; - - /** - * Exclude calling `ToString` during evaluation. - */ - noToString?: boolean; - - /** - * Evaluation should take place immediately if possible. - */ - forceEvaluationNow?: boolean; - - /** - * Exclude interpretation from evaluation methods. - */ - forceRealFuncEval?: boolean; - - /** - * Allow all threads to run during the evaluation. - */ - runAllThreads?: boolean; - - /** - * The 'raw' view of objects and structions should be shown - visualization improvements should be disabled. - */ - rawStructures?: boolean; - - /** - * Variables responses containing favorites should be filtered to only those items - */ - filterToFavorites?: boolean; - - /** - * Auto generated display strings for variables with favorites should not include field names. - */ - simpleDisplayString?: boolean; - } - - export interface EvaluateParamsExtended extends EvaluateParams { - evaluationOptions?: EvaluationOptions; - } - - /** - * Properties of a variable that can be used to determine how to render the variable in the UI. - */ - export interface VariablePresentationHint { - /** - * The kind of variable. Before introducing additional values, try to use the listed values. - */ - kind?: - | 'property' - | 'method' - | 'class' - | 'data' - | 'event' - | 'baseClass' - | 'innerClass' - | 'interface' - | 'mostDerivedClass' - | 'virtual' - | 'dataBreakpoint'; - - /** - * Set of attributes represented as an array of strings. Before introducing additional values, try to use the listed values. - */ - attributes?: ( - | 'static' - | 'constant' - | 'readOnly' - | 'rawString' - | 'hasObjectId' - | 'canHaveObjectId' - | 'hasSideEffects' - | 'hasDataBreakpoint' - )[]; - - /** - * Visibility of variable. Before introducing additional values, try to use the listed values. - */ - visibility?: 'public' | 'private' | 'protected' | 'internal' | 'final'; - - /** - * If true, clients can present the variable with a UI that supports a specific gesture to trigger its evaluation. - * This mechanism can be used for properties that require executing code when retrieving their value and where the code execution can be expensive and/or produce side-effects. A typical example are properties based on a getter function. - * Please note that in addition to the `lazy` flag, the variable's `variablesReference` is expected to refer to a variable that will provide the value through another `variable` request. - */ - lazy?: boolean; - } - - /** - * Provides formatting information for a value. - */ - export interface ValueFormat { - /** - * Display the value in hex. - */ - hex?: boolean; - } - - /** - * Represents a single disassembled instruction. - */ - export interface DisassembledInstruction { - /** - * The address of the instruction. Treated as a hex value if prefixed with `0x`, or as a decimal value otherwise. - */ - address: string; - - /** - * Raw bytes representing the instruction and its operands, in an implementation-defined format. - */ - instructionBytes?: string; - - /** - * Text representing the instruction and its operands, in an implementation-defined format. - */ - instruction: string; - - /** - * Name of the symbol that corresponds with the location of this instruction, if any. - */ - symbol?: string; - - /** - * Source location that corresponds to this instruction, if any. - * Should always be set (if available) on the first instruction returned, - * but can be omitted afterwards if this instruction maps to the same source file as the previous instruction. - */ - location?: Source; - - /** - * The line within the source location that corresponds to this instruction, if any. - */ - line?: integer; - - /** - * The column within the line that corresponds to this instruction, if any. - */ - column?: integer; - - /** - * The end line of the range that corresponds to this instruction, if any. - */ - endLine?: integer; - - /** - * The end column of the range that corresponds to this instruction, if any. - */ - endColumn?: integer; - } - - /** - * This enumeration defines all possible access types for data breakpoints. - */ - export type DataBreakpointAccessType = string; - - /** - * `CompletionItems` are the suggestions returned from the `completions` request. - */ - export interface CompletionItem { - /** - * The label of this completion item. By default this is also the text that is inserted when selecting this completion. - */ - label: string; - - /** - * If text is returned and not an empty string, then it is inserted instead of the label. - */ - text?: string; - - /** - * A string that should be used when comparing this item with other items. If not returned or an empty string, the `label` is used instead. - */ - sortText?: string; - - /** - * A human-readable string with additional information about this item, like type or symbol information. - */ - detail?: string; - - /** - * The item's type. Typically the client uses this information to render the item in the UI with an icon. - */ - type?: CompletionItemType; - - /** - * Start position (within the `text` attribute of the `completions` request) where the completion text is added. The position is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. If the start position is omitted the text is added at the location specified by the `column` attribute of the `completions` request. - */ - start?: integer; - - /** - * Length determines how many characters are overwritten by the completion text and it is measured in UTF-16 code units. If missing the value 0 is assumed which results in the completion text being inserted. - */ - length?: integer; - - /** - * Determines the start of the new selection after the text has been inserted (or replaced). `selectionStart` is measured in UTF-16 code units and must be in the range 0 and length of the completion text. If omitted the selection starts at the end of the completion text. - */ - selectionStart?: integer; - - /** - * Determines the length of the new selection after the text has been inserted (or replaced) and it is measured in UTF-16 code units. The selection can not extend beyond the bounds of the completion text. If omitted the length is assumed to be 0. - */ - selectionLength?: integer; - } - - /** - * Some predefined types for the CompletionItem. Please note that not all clients have specific icons for all of them. - */ - export type CompletionItemType = string; - - export interface CapabilitiesExtended extends Capabilities { - supportsDebuggerProperties?: boolean; - - supportsEvaluationOptions?: boolean; - - /** - * The debug adapter supports the set symbol options request - */ - supportsSetSymbolOptions?: boolean; - } - - /** - * Information about the capabilities of a debug adapter. - */ - export interface Capabilities { - /** - * The debug adapter supports the `configurationDone` request. - */ - supportsConfigurationDoneRequest?: boolean; - - /** - * The debug adapter supports function breakpoints. - */ - supportsFunctionBreakpoints?: boolean; - - /** - * The debug adapter supports conditional breakpoints. - */ - supportsConditionalBreakpoints?: boolean; - - /** - * The debug adapter supports breakpoints that break execution after a specified number of hits. - */ - supportsHitConditionalBreakpoints?: boolean; - - /** - * The debug adapter supports a (side effect free) `evaluate` request for data hovers. - */ - supportsEvaluateForHovers?: boolean; - - /** - * Available exception filter options for the `setExceptionBreakpoints` request. - */ - exceptionBreakpointFilters?: ExceptionBreakpointsFilter[]; - - /** - * The debug adapter supports stepping back via the `stepBack` and `reverseContinue` requests. - */ - supportsStepBack?: boolean; - - /** - * The debug adapter supports setting a variable to a value. - */ - supportsSetVariable?: boolean; - - /** - * The debug adapter supports restarting a frame. - */ - supportsRestartFrame?: boolean; - - /** - * The debug adapter supports the `gotoTargets` request. - */ - supportsGotoTargetsRequest?: boolean; - - /** - * The debug adapter supports the `stepInTargets` request. - */ - supportsStepInTargetsRequest?: boolean; - - /** - * The debug adapter supports the `completions` request. - */ - supportsCompletionsRequest?: boolean; - - /** - * The set of characters that should trigger completion in a REPL. If not specified, the UI should assume the `.` character. - */ - completionTriggerCharacters?: string[]; - - /** - * The debug adapter supports the `modules` request. - */ - supportsModulesRequest?: boolean; - - /** - * The set of additional module information exposed by the debug adapter. - */ - additionalModuleColumns?: ColumnDescriptor[]; - - /** - * Checksum algorithms supported by the debug adapter. - */ - supportedChecksumAlgorithms?: ChecksumAlgorithm[]; - - /** - * The debug adapter supports the `restart` request. In this case a client should not implement `restart` by terminating and relaunching the adapter but by calling the `restart` request. - */ - supportsRestartRequest?: boolean; - - /** - * The debug adapter supports `exceptionOptions` on the `setExceptionBreakpoints` request. - */ - supportsExceptionOptions?: boolean; - - /** - * The debug adapter supports a `format` attribute on the `stackTrace`, `variables`, and `evaluate` requests. - */ - supportsValueFormattingOptions?: boolean; - - /** - * The debug adapter supports the `exceptionInfo` request. - */ - supportsExceptionInfoRequest?: boolean; - - /** - * The debug adapter supports the `terminateDebuggee` attribute on the `disconnect` request. - */ - supportTerminateDebuggee?: boolean; - - /** - * The debug adapter supports the `suspendDebuggee` attribute on the `disconnect` request. - */ - supportSuspendDebuggee?: boolean; - - /** - * The debug adapter supports the delayed loading of parts of the stack, which requires that both the `startFrame` and `levels` arguments and the `totalFrames` result of the `stackTrace` request are supported. - */ - supportsDelayedStackTraceLoading?: boolean; - - /** - * The debug adapter supports the `loadedSources` request. - */ - supportsLoadedSourcesRequest?: boolean; - - /** - * The debug adapter supports log points by interpreting the `logMessage` attribute of the `SourceBreakpoint`. - */ - supportsLogPoints?: boolean; - - /** - * The debug adapter supports the `terminateThreads` request. - */ - supportsTerminateThreadsRequest?: boolean; - - /** - * The debug adapter supports the `setExpression` request. - */ - supportsSetExpression?: boolean; - - /** - * The debug adapter supports the `terminate` request. - */ - supportsTerminateRequest?: boolean; - - /** - * The debug adapter supports data breakpoints. - */ - supportsDataBreakpoints?: boolean; - - /** - * The debug adapter supports the `readMemory` request. - */ - supportsReadMemoryRequest?: boolean; - - /** - * The debug adapter supports the `writeMemory` request. - */ - supportsWriteMemoryRequest?: boolean; - - /** - * The debug adapter supports the `disassemble` request. - */ - supportsDisassembleRequest?: boolean; - - /** - * The debug adapter supports the `cancel` request. - */ - supportsCancelRequest?: boolean; - - /** - * The debug adapter supports the `breakpointLocations` request. - */ - supportsBreakpointLocationsRequest?: boolean; - - /** - * The debug adapter supports the `clipboard` context value in the `evaluate` request. - */ - supportsClipboardContext?: boolean; - - /** - * The debug adapter supports stepping granularities (argument `granularity`) for the stepping requests. - */ - supportsSteppingGranularity?: boolean; - - /** - * The debug adapter supports adding breakpoints based on instruction references. - */ - supportsInstructionBreakpoints?: boolean; - - /** - * The debug adapter supports `filterOptions` as an argument on the `setExceptionBreakpoints` request. - */ - supportsExceptionFilterOptions?: boolean; - - /** - * The debug adapter supports the `singleThread` property on the execution requests (`continue`, `next`, `stepIn`, `stepOut`, `reverseContinue`, `stepBack`). - */ - supportsSingleThreadExecutionRequests?: boolean; - } - - /** - * Properties of a breakpoint location returned from the `breakpointLocations` request. - */ - export interface BreakpointLocation { - /** - * Start line of breakpoint location. - */ - line: integer; - - /** - * The start position of a breakpoint location. Position is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - column?: integer; - - /** - * The end line of breakpoint location if the location covers a range. - */ - endLine?: integer; - - /** - * The end position of a breakpoint location (if the location covers a range). Position is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - endColumn?: integer; - } - - /** - * A `Source` is a descriptor for source code. - * It is returned from the debug adapter as part of a `StackFrame` and it is used by clients when specifying breakpoints. - */ - export interface Source { - /** - * The short name of the source. Every source returned from the debug adapter has a name. - * When sending a source to the debug adapter this name is optional. - */ - name?: string; - - /** - * The path of the source to be shown in the UI. - * It is only used to locate and load the content of the source if no `sourceReference` is specified (or its value is 0). - */ - path?: string; - - /** - * If the value > 0 the contents of the source must be retrieved through the `source` request (even if a path is specified). - * Since a `sourceReference` is only valid for a session, it can not be used to persist a source. - * The value should be less than or equal to 2147483647 (2^31-1). - */ - sourceReference?: integer; - - /** - * A hint for how to present the source in the UI. - * A value of `deemphasize` can be used to indicate that the source is not available or that it is skipped on stepping. - */ - presentationHint?: string; - - /** - * The origin of this source. For example, 'internal module', 'inlined content from source map', etc. - */ - origin?: string; - - /** - * A list of sources that are related to this source. These may be the source that generated this source. - */ - sources?: Source[]; - - /** - * Additional data that a debug adapter might want to loop through the client. - * The client should leave the data intact and persist it across sessions. The client should not interpret the data. - */ - adapterData?: any[] | boolean | integer | null | number | object | string; - - /** - * The checksums associated with this file. - */ - checksums?: Checksum[]; - } - - /** - * The checksum of an item calculated by the specified algorithm. - */ - export interface Checksum { - /** - * The algorithm used to calculate this checksum. - */ - algorithm: ChecksumAlgorithm; - - /** - * Value of the checksum, encoded as a hexadecimal value. - */ - checksum: string; - } - - /** - * Information about a breakpoint created in `setBreakpoints`, `setFunctionBreakpoints`, `setInstructionBreakpoints`, or `setDataBreakpoints` requests. - */ - export interface Breakpoint { - /** - * The identifier for the breakpoint. It is needed if breakpoint events are used to update or remove breakpoints. - */ - id?: integer; - - /** - * If true, the breakpoint could be set (but not necessarily at the desired location). - */ - verified: boolean; - - /** - * A message about the state of the breakpoint. - * This is shown to the user and can be used to explain why a breakpoint could not be verified. - */ - message?: string; - - /** - * The source where the breakpoint is located. - */ - source?: Source; - - /** - * The start line of the actual range covered by the breakpoint. - */ - line?: integer; - - /** - * Start position of the source range covered by the breakpoint. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - */ - column?: integer; - - /** - * The end line of the actual range covered by the breakpoint. - */ - endLine?: integer; - - /** - * End position of the source range covered by the breakpoint. It is measured in UTF-16 code units and the client capability `columnsStartAt1` determines whether it is 0- or 1-based. - * If no end line is given, then the end column is assumed to be in the start line. - */ - endColumn?: integer; - - /** - * A memory reference to where the breakpoint is set. - */ - instructionReference?: string; - - /** - * The offset from the instruction reference. - * This can be negative. - */ - offset?: integer; - } -} - -export default DAP;
\ No newline at end of file diff --git a/packages/bun-vscode/types/jsc.d.ts b/packages/bun-vscode/types/jsc.d.ts deleted file mode 100644 index 2b905ae1e..000000000 --- a/packages/bun-vscode/types/jsc.d.ts +++ /dev/null @@ -1,1999 +0,0 @@ -// GENERATED - DO NOT EDIT -export namespace JSC { - export namespace Console { - /** Channels for different types of log messages. */ - export type ChannelSource = - | "xml" - | "javascript" - | "network" - | "console-api" - | "storage" - | "appcache" - | "rendering" - | "css" - | "security" - | "content-blocker" - | "media" - | "mediasource" - | "webrtc" - | "itp-debug" - | "private-click-measurement" - | "payment-request" - | "other"; - /** Level of logging. */ - export type ChannelLevel = "off" | "basic" | "verbose"; - /** The reason the console is being cleared. */ - export type ClearReason = "console-api" | "main-frame-navigation"; - /** Logging channel. */ - export type Channel = { - source: ChannelSource; - level: ChannelLevel; - }; - /** Console message. */ - export type ConsoleMessage = { - source: ChannelSource; - /** Message severity. */ - level: "log" | "info" | "warning" | "error" | "debug"; - /** Message text. */ - text: string; - /** Console message type. */ - type?: - | "log" - | "dir" - | "dirxml" - | "table" - | "trace" - | "clear" - | "startGroup" - | "startGroupCollapsed" - | "endGroup" - | "assert" - | "timing" - | "profile" - | "profileEnd" - | "image"; - /** URL of the message origin. */ - url?: string; - /** Line number in the resource that generated this message. */ - line?: number; - /** Column number on the line in the resource that generated this message. */ - column?: number; - /** Repeat count for repeated messages. */ - repeatCount?: number; - /** Message parameters in case of the formatted message. */ - parameters?: Array<Runtime.RemoteObject>; - /** JavaScript stack trace for assertions and error messages. */ - stackTrace?: StackTrace; - /** Identifier of the network request associated with this message. */ - networkRequestId?: Network.RequestId; - /** Time when this message was added. Currently only used when an expensive operation happens to make sure that the frontend can account for it. */ - timestamp?: number; - }; - /** Stack entry for console errors and assertions. */ - export type CallFrame = { - /** JavaScript function name. */ - functionName: string; - /** JavaScript script name or url. */ - url: string; - /** Script identifier. */ - scriptId: Debugger.ScriptId; - /** JavaScript script line number. */ - lineNumber: number; - /** JavaScript script column number. */ - columnNumber: number; - }; - /** Call frames for async function calls, console assertions, and error messages. */ - export type StackTrace = { - callFrames: Array<CallFrame>; - /** Whether the first item in <code>callFrames</code> is the native function that scheduled the asynchronous operation (e.g. setTimeout). */ - topCallFrameIsBoundary?: boolean; - /** Whether one or more frames have been truncated from the bottom of the stack. */ - truncated?: boolean; - /** Parent StackTrace. */ - parentStackTrace?: StackTrace; - }; - /** `Console.messageAdded` */ - export type MessageAddedEvent = { - /** Console message that has been added. */ - message: ConsoleMessage; - }; - /** `Console.messageRepeatCountUpdated` */ - export type MessageRepeatCountUpdatedEvent = { - /** New repeat count value. */ - count: number; - /** Timestamp of the latest message. */ - timestamp?: number; - }; - /** `Console.messagesCleared` */ - export type MessagesClearedEvent = { - /** The reason the console is being cleared. */ - reason: ClearReason; - }; - /** `Console.heapSnapshot` */ - export type HeapSnapshotEvent = { - timestamp: number; - /** Snapshot at the end of tracking. */ - snapshotData: Heap.HeapSnapshotData; - /** Optional title provided to console.takeHeapSnapshot. */ - title?: string; - }; - /** `Console.enable` */ - export type EnableRequest = {}; - /** `Console.enable` */ - export type EnableResponse = {}; - /** `Console.disable` */ - export type DisableRequest = {}; - /** `Console.disable` */ - export type DisableResponse = {}; - /** `Console.clearMessages` */ - export type ClearMessagesRequest = {}; - /** `Console.clearMessages` */ - export type ClearMessagesResponse = {}; - /** `Console.getLoggingChannels` */ - export type GetLoggingChannelsRequest = {}; - /** `Console.getLoggingChannels` */ - export type GetLoggingChannelsResponse = { - /** Logging channels. */ - channels: Array<Channel>; - }; - /** `Console.setLoggingChannelLevel` */ - export type SetLoggingChannelLevelRequest = { - /** Logging channel to modify. */ - source: ChannelSource; - /** New level. */ - level: ChannelLevel; - }; - /** `Console.setLoggingChannelLevel` */ - export type SetLoggingChannelLevelResponse = {}; - } - export namespace Debugger { - /** Breakpoint identifier. */ - export type BreakpointId = string; - /** Breakpoint action identifier. */ - export type BreakpointActionIdentifier = number; - /** Unique script identifier. */ - export type ScriptId = string; - /** Call frame identifier. */ - export type CallFrameId = string; - /** Location in the source code. */ - export type Location = { - /** Script identifier as reported in the <code>Debugger.scriptParsed</code>. */ - scriptId: ScriptId; - /** Line number in the script (0-based). */ - lineNumber: number; - /** Column number in the script (0-based). */ - columnNumber?: number; - }; - /** Action to perform when a breakpoint is triggered. */ - export type BreakpointAction = { - /** Different kinds of breakpoint actions. */ - type: "log" | "evaluate" | "sound" | "probe"; - /** Data associated with this breakpoint type (e.g. for type "eval" this is the JavaScript string to evaluate). */ - data?: string; - /** A frontend-assigned identifier for this breakpoint action. */ - id?: BreakpointActionIdentifier; - /** Indicates whether this action should be executed with a user gesture or not. Defaults to <code>false<code>. */ - emulateUserGesture?: boolean; - }; - /** Extra options that modify breakpoint behavior. */ - export type BreakpointOptions = { - /** Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. */ - condition?: string; - /** Actions to perform automatically when the breakpoint is triggered. */ - actions?: Array<BreakpointAction>; - /** Automatically continue after hitting this breakpoint and running actions. */ - autoContinue?: boolean; - /** Number of times to ignore this breakpoint, before stopping on the breakpoint and running actions. */ - ignoreCount?: number; - }; - /** Information about the function. */ - export type FunctionDetails = { - /** Location of the function. */ - location: Location; - /** Name of the function. Not present for anonymous functions. */ - name?: string; - /** Display name of the function(specified in 'displayName' property on the function object). */ - displayName?: string; - /** Scope chain for this closure. */ - scopeChain?: Array<Scope>; - }; - /** JavaScript call frame. Array of call frames form the call stack. */ - export type CallFrame = { - /** Call frame identifier. This identifier is only valid while the virtual machine is paused. */ - callFrameId: CallFrameId; - /** Name of the JavaScript function called on this call frame. */ - functionName: string; - /** Location in the source code. */ - location: Location; - /** Scope chain for this call frame. */ - scopeChain: Array<Scope>; - /** <code>this</code> object for this call frame. */ - this: Runtime.RemoteObject; - /** Is the current frame tail deleted from a tail call. */ - isTailDeleted: boolean; - }; - /** Scope description. */ - export type Scope = { - /** Object representing the scope. For <code>global</code> and <code>with</code> scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. */ - object: Runtime.RemoteObject; - /** Scope type. */ - type: - | "global" - | "with" - | "closure" - | "catch" - | "functionName" - | "globalLexicalEnvironment" - | "nestedLexical"; - /** Name associated with the scope. */ - name?: string; - /** Location if available of the scope definition. */ - location?: Location; - /** Whether the scope has any variables. */ - empty?: boolean; - }; - /** A sample collected by evaluating a probe breakpoint action. */ - export type ProbeSample = { - /** Identifier of the probe breakpoint action that created the sample. */ - probeId: BreakpointActionIdentifier; - /** Unique identifier for this sample. */ - sampleId: number; - /** A batch identifier which is the same for all samples taken at the same breakpoint hit. */ - batchId: number; - /** Timestamp of when the sample was taken. */ - timestamp: number; - /** Contents of the sample. */ - payload: Runtime.RemoteObject; - }; - /** The pause reason auxiliary data when paused because of an assertion. */ - export type AssertPauseReason = { - /** The console.assert message string if provided. */ - message?: string; - }; - /** The pause reason auxiliary data when paused because of hitting a breakpoint. */ - export type BreakpointPauseReason = { - /** The identifier of the breakpoint causing the pause. */ - breakpointId: string; - }; - /** The pause reason auxiliary data when paused because of a Content Security Policy directive. */ - export type CSPViolationPauseReason = { - /** The CSP directive that blocked script execution. */ - directive: string; - }; - /** `Debugger.globalObjectCleared` */ - export type GlobalObjectClearedEvent = {}; - /** `Debugger.scriptParsed` */ - export type ScriptParsedEvent = { - /** Identifier of the script parsed. */ - scriptId: ScriptId; - /** URL of the script parsed (if any). */ - url: string; - /** Line offset of the script within the resource with given URL (for script tags). */ - startLine: number; - /** Column offset of the script within the resource with given URL. */ - startColumn: number; - /** Last line of the script. */ - endLine: number; - /** Length of the last line of the script. */ - endColumn: number; - /** Determines whether this script is a user extension script. */ - isContentScript?: boolean; - /** sourceURL name of the script (if any). */ - sourceURL?: string; - /** URL of source map associated with script (if any). */ - sourceMapURL?: string; - /** True if this script was parsed as a module. */ - module?: boolean; - }; - /** `Debugger.scriptFailedToParse` */ - export type ScriptFailedToParseEvent = { - /** URL of the script that failed to parse. */ - url: string; - /** Source text of the script that failed to parse. */ - scriptSource: string; - /** Line offset of the script within the resource. */ - startLine: number; - /** Line with error. */ - errorLine: number; - /** Parse error message. */ - errorMessage: string; - }; - /** `Debugger.breakpointResolved` */ - export type BreakpointResolvedEvent = { - /** Breakpoint unique identifier. */ - breakpointId: BreakpointId; - /** Actual breakpoint location. */ - location: Location; - }; - /** `Debugger.paused` */ - export type PausedEvent = { - /** Call stack the virtual machine stopped on. */ - callFrames: Array<CallFrame>; - /** Pause reason. */ - reason: - | "URL" - | "DOM" - | "AnimationFrame" - | "Interval" - | "Listener" - | "Timeout" - | "exception" - | "assert" - | "CSPViolation" - | "DebuggerStatement" - | "Breakpoint" - | "PauseOnNextStatement" - | "Microtask" - | "FunctionCall" - | "BlackboxedScript" - | "other"; - /** Object containing break-specific auxiliary properties. */ - data?: Record<string, unknown>; - /** Linked list of asynchronous StackTraces. */ - asyncStackTrace?: Console.StackTrace; - }; - /** `Debugger.resumed` */ - export type ResumedEvent = {}; - /** `Debugger.didSampleProbe` */ - export type DidSampleProbeEvent = { - /** A collected probe sample. */ - sample: ProbeSample; - }; - /** `Debugger.playBreakpointActionSound` */ - export type PlayBreakpointActionSoundEvent = { - /** Breakpoint action identifier. */ - breakpointActionId: BreakpointActionIdentifier; - }; - /** `Debugger.enable` */ - export type EnableRequest = {}; - /** `Debugger.enable` */ - export type EnableResponse = {}; - /** `Debugger.disable` */ - export type DisableRequest = {}; - /** `Debugger.disable` */ - export type DisableResponse = {}; - /** `Debugger.setAsyncStackTraceDepth` */ - export type SetAsyncStackTraceDepthRequest = { - /** Async stack trace depth. */ - depth: number; - }; - /** `Debugger.setAsyncStackTraceDepth` */ - export type SetAsyncStackTraceDepthResponse = {}; - /** `Debugger.setBreakpointsActive` */ - export type SetBreakpointsActiveRequest = { - /** New value for breakpoints active state. */ - active: boolean; - }; - /** `Debugger.setBreakpointsActive` */ - export type SetBreakpointsActiveResponse = {}; - /** `Debugger.setBreakpointByUrl` */ - export type SetBreakpointByUrlRequest = { - /** Line number to set breakpoint at. */ - lineNumber: number; - /** URL of the resources to set breakpoint on. */ - url?: string; - /** Regex pattern for the URLs of the resources to set breakpoints on. Either <code>url</code> or <code>urlRegex</code> must be specified. */ - urlRegex?: string; - /** Offset in the line to set breakpoint at. */ - columnNumber?: number; - /** Options to apply to this breakpoint to modify its behavior. */ - options?: BreakpointOptions; - }; - /** `Debugger.setBreakpointByUrl` */ - export type SetBreakpointByUrlResponse = { - /** Id of the created breakpoint for further reference. */ - breakpointId: BreakpointId; - /** List of the locations this breakpoint resolved into upon addition. */ - locations: Array<Location>; - }; - /** `Debugger.setBreakpoint` */ - export type SetBreakpointRequest = { - /** Location to set breakpoint in. */ - location: Location; - /** Options to apply to this breakpoint to modify its behavior. */ - options?: BreakpointOptions; - }; - /** `Debugger.setBreakpoint` */ - export type SetBreakpointResponse = { - /** Id of the created breakpoint for further reference. */ - breakpointId: BreakpointId; - /** Location this breakpoint resolved into. */ - actualLocation: Location; - }; - /** `Debugger.removeBreakpoint` */ - export type RemoveBreakpointRequest = { - breakpointId: BreakpointId; - }; - /** `Debugger.removeBreakpoint` */ - export type RemoveBreakpointResponse = {}; - /** `Debugger.addSymbolicBreakpoint` */ - export type AddSymbolicBreakpointRequest = { - /** The name of the function to pause in when called. */ - symbol: string; - /** If true, symbol is case sensitive. Defaults to true. */ - caseSensitive?: boolean; - /** If true, treats symbol as a regex. Defaults to false. */ - isRegex?: boolean; - /** Options to apply to this breakpoint to modify its behavior. */ - options?: BreakpointOptions; - }; - /** `Debugger.addSymbolicBreakpoint` */ - export type AddSymbolicBreakpointResponse = {}; - /** `Debugger.removeSymbolicBreakpoint` */ - export type RemoveSymbolicBreakpointRequest = { - /** The name of the function to pause in when called. */ - symbol: string; - /** If true, symbol is case sensitive. Defaults to true. */ - caseSensitive?: boolean; - /** If true, treats symbol as a regex. Defaults to false. */ - isRegex?: boolean; - }; - /** `Debugger.removeSymbolicBreakpoint` */ - export type RemoveSymbolicBreakpointResponse = {}; - /** `Debugger.continueUntilNextRunLoop` */ - export type ContinueUntilNextRunLoopRequest = {}; - /** `Debugger.continueUntilNextRunLoop` */ - export type ContinueUntilNextRunLoopResponse = {}; - /** `Debugger.continueToLocation` */ - export type ContinueToLocationRequest = { - /** Location to continue to. */ - location: Location; - }; - /** `Debugger.continueToLocation` */ - export type ContinueToLocationResponse = {}; - /** `Debugger.stepNext` */ - export type StepNextRequest = {}; - /** `Debugger.stepNext` */ - export type StepNextResponse = {}; - /** `Debugger.stepOver` */ - export type StepOverRequest = {}; - /** `Debugger.stepOver` */ - export type StepOverResponse = {}; - /** `Debugger.stepInto` */ - export type StepIntoRequest = {}; - /** `Debugger.stepInto` */ - export type StepIntoResponse = {}; - /** `Debugger.stepOut` */ - export type StepOutRequest = {}; - /** `Debugger.stepOut` */ - export type StepOutResponse = {}; - /** `Debugger.pause` */ - export type PauseRequest = {}; - /** `Debugger.pause` */ - export type PauseResponse = {}; - /** `Debugger.resume` */ - export type ResumeRequest = {}; - /** `Debugger.resume` */ - export type ResumeResponse = {}; - /** `Debugger.searchInContent` */ - export type SearchInContentRequest = { - /** Id of the script to search in. */ - scriptId: ScriptId; - /** String to search for. */ - query: string; - /** If true, search is case sensitive. */ - caseSensitive?: boolean; - /** If true, treats string parameter as regex. */ - isRegex?: boolean; - }; - /** `Debugger.searchInContent` */ - export type SearchInContentResponse = { - /** List of search matches. */ - result: Array<GenericTypes.SearchMatch>; - }; - /** `Debugger.getScriptSource` */ - export type GetScriptSourceRequest = { - /** Id of the script to get source for. */ - scriptId: ScriptId; - }; - /** `Debugger.getScriptSource` */ - export type GetScriptSourceResponse = { - /** Script source. */ - scriptSource: string; - }; - /** `Debugger.getFunctionDetails` */ - export type GetFunctionDetailsRequest = { - /** Id of the function to get location for. */ - functionId: Runtime.RemoteObjectId; - }; - /** `Debugger.getFunctionDetails` */ - export type GetFunctionDetailsResponse = { - /** Information about the function. */ - details: FunctionDetails; - }; - /** `Debugger.getBreakpointLocations` */ - export type GetBreakpointLocationsRequest = { - /** Starting location to look for breakpoint locations after (inclusive). Must have same scriptId as end. */ - start: Location; - /** Ending location to look for breakpoint locations before (exclusive). Must have same scriptId as start. */ - end: Location; - }; - /** `Debugger.getBreakpointLocations` */ - export type GetBreakpointLocationsResponse = { - /** List of resolved breakpoint locations. */ - locations: Array<Location>; - }; - /** `Debugger.setPauseOnDebuggerStatements` */ - export type SetPauseOnDebuggerStatementsRequest = { - enabled: boolean; - /** Options to apply to this breakpoint to modify its behavior. */ - options?: BreakpointOptions; - }; - /** `Debugger.setPauseOnDebuggerStatements` */ - export type SetPauseOnDebuggerStatementsResponse = {}; - /** `Debugger.setPauseOnExceptions` */ - export type SetPauseOnExceptionsRequest = { - /** Pause on exceptions mode. */ - state: "none" | "uncaught" | "all"; - /** Options to apply to this breakpoint to modify its behavior. */ - options?: BreakpointOptions; - }; - /** `Debugger.setPauseOnExceptions` */ - export type SetPauseOnExceptionsResponse = {}; - /** `Debugger.setPauseOnAssertions` */ - export type SetPauseOnAssertionsRequest = { - enabled: boolean; - /** Options to apply to this breakpoint to modify its behavior. */ - options?: BreakpointOptions; - }; - /** `Debugger.setPauseOnAssertions` */ - export type SetPauseOnAssertionsResponse = {}; - /** `Debugger.setPauseOnMicrotasks` */ - export type SetPauseOnMicrotasksRequest = { - enabled: boolean; - /** Options to apply to this breakpoint to modify its behavior. */ - options?: BreakpointOptions; - }; - /** `Debugger.setPauseOnMicrotasks` */ - export type SetPauseOnMicrotasksResponse = {}; - /** `Debugger.setPauseForInternalScripts` */ - export type SetPauseForInternalScriptsRequest = { - shouldPause: boolean; - }; - /** `Debugger.setPauseForInternalScripts` */ - export type SetPauseForInternalScriptsResponse = {}; - /** `Debugger.evaluateOnCallFrame` */ - export type EvaluateOnCallFrameRequest = { - /** Call frame identifier to evaluate on. */ - callFrameId: CallFrameId; - /** Expression to evaluate. */ - expression: string; - /** String object group name to put result into (allows rapid releasing resulting object handles using <code>releaseObjectGroup</code>). */ - objectGroup?: string; - /** Specifies whether command line API should be available to the evaluated expression, defaults to false. */ - includeCommandLineAPI?: boolean; - /** Specifies whether evaluation should stop on exceptions and mute console. Overrides setPauseOnException state. */ - doNotPauseOnExceptionsAndMuteConsole?: boolean; - /** Whether the result is expected to be a JSON object that should be sent by value. */ - returnByValue?: boolean; - /** Whether preview should be generated for the result. */ - generatePreview?: boolean; - /** Whether the resulting value should be considered for saving in the $n history. */ - saveResult?: boolean; - /** Whether the expression should be considered to be in a user gesture or not. */ - emulateUserGesture?: boolean; - }; - /** `Debugger.evaluateOnCallFrame` */ - export type EvaluateOnCallFrameResponse = { - /** Object wrapper for the evaluation result. */ - result: Runtime.RemoteObject; - /** True if the result was thrown during the evaluation. */ - wasThrown?: boolean; - /** If the result was saved, this is the $n index that can be used to access the value. */ - savedResultIndex?: number; - }; - /** `Debugger.setShouldBlackboxURL` */ - export type SetShouldBlackboxURLRequest = { - url: string; - shouldBlackbox: boolean; - /** If true, <code>url</code> is case sensitive. */ - caseSensitive?: boolean; - /** If true, treat <code>url</code> as regular expression. */ - isRegex?: boolean; - }; - /** `Debugger.setShouldBlackboxURL` */ - export type SetShouldBlackboxURLResponse = {}; - /** `Debugger.setBlackboxBreakpointEvaluations` */ - export type SetBlackboxBreakpointEvaluationsRequest = { - blackboxBreakpointEvaluations: boolean; - }; - /** `Debugger.setBlackboxBreakpointEvaluations` */ - export type SetBlackboxBreakpointEvaluationsResponse = {}; - } - export namespace GenericTypes { - /** Search match in a resource. */ - export type SearchMatch = { - /** Line number in resource content. */ - lineNumber: number; - /** Line with match content. */ - lineContent: string; - }; - } - export namespace Heap { - /** Information about a garbage collection. */ - export type GarbageCollection = { - /** The type of garbage collection. */ - type: "full" | "partial"; - startTime: number; - endTime: number; - }; - /** JavaScriptCore HeapSnapshot JSON data. */ - export type HeapSnapshotData = string; - /** `Heap.garbageCollected` */ - export type GarbageCollectedEvent = { - collection: GarbageCollection; - }; - /** `Heap.trackingStart` */ - export type TrackingStartEvent = { - timestamp: number; - /** Snapshot at the start of tracking. */ - snapshotData: HeapSnapshotData; - }; - /** `Heap.trackingComplete` */ - export type TrackingCompleteEvent = { - timestamp: number; - /** Snapshot at the end of tracking. */ - snapshotData: HeapSnapshotData; - }; - /** `Heap.enable` */ - export type EnableRequest = {}; - /** `Heap.enable` */ - export type EnableResponse = {}; - /** `Heap.disable` */ - export type DisableRequest = {}; - /** `Heap.disable` */ - export type DisableResponse = {}; - /** `Heap.gc` */ - export type GcRequest = {}; - /** `Heap.gc` */ - export type GcResponse = {}; - /** `Heap.snapshot` */ - export type SnapshotRequest = {}; - /** `Heap.snapshot` */ - export type SnapshotResponse = { - timestamp: number; - snapshotData: HeapSnapshotData; - }; - /** `Heap.startTracking` */ - export type StartTrackingRequest = {}; - /** `Heap.startTracking` */ - export type StartTrackingResponse = {}; - /** `Heap.stopTracking` */ - export type StopTrackingRequest = {}; - /** `Heap.stopTracking` */ - export type StopTrackingResponse = {}; - /** `Heap.getPreview` */ - export type GetPreviewRequest = { - /** Identifier of the heap object within the snapshot. */ - heapObjectId: number; - }; - /** `Heap.getPreview` */ - export type GetPreviewResponse = { - /** String value. */ - string?: string; - /** Function details. */ - functionDetails?: Debugger.FunctionDetails; - /** Object preview. */ - preview?: Runtime.ObjectPreview; - }; - /** `Heap.getRemoteObject` */ - export type GetRemoteObjectRequest = { - /** Identifier of the heap object within the snapshot. */ - heapObjectId: number; - /** Symbolic group name that can be used to release multiple objects. */ - objectGroup?: string; - }; - /** `Heap.getRemoteObject` */ - export type GetRemoteObjectResponse = { - /** Resulting object. */ - result: Runtime.RemoteObject; - }; - } - export namespace Network { - /** Unique loader identifier. */ - export type LoaderId = string; - /** Unique frame identifier. */ - export type FrameId = string; - /** Unique request identifier. */ - export type RequestId = string; - /** Elapsed seconds since frontend connected. */ - export type Timestamp = number; - /** Number of seconds since epoch. */ - export type Walltime = number; - /** Controls how much referrer information is sent with the request */ - export type ReferrerPolicy = - | "empty-string" - | "no-referrer" - | "no-referrer-when-downgrade" - | "same-origin" - | "origin" - | "strict-origin" - | "origin-when-cross-origin" - | "strict-origin-when-cross-origin" - | "unsafe-url"; - /** Request / response headers as keys / values of JSON object. */ - export type Headers = Record<string, unknown>; - /** Timing information for the request. */ - export type ResourceTiming = { - /** Request is initiated */ - startTime: Timestamp; - /** Started redirect resolution. */ - redirectStart: Timestamp; - /** Finished redirect resolution. */ - redirectEnd: Timestamp; - /** Resource fetching started. */ - fetchStart: Timestamp; - /** Started DNS address resolve in milliseconds relative to fetchStart. */ - domainLookupStart: number; - /** Finished DNS address resolve in milliseconds relative to fetchStart. */ - domainLookupEnd: number; - /** Started connecting to the remote host in milliseconds relative to fetchStart. */ - connectStart: number; - /** Connected to the remote host in milliseconds relative to fetchStart. */ - connectEnd: number; - /** Started SSL handshake in milliseconds relative to fetchStart. */ - secureConnectionStart: number; - /** Started sending request in milliseconds relative to fetchStart. */ - requestStart: number; - /** Started receiving response headers in milliseconds relative to fetchStart. */ - responseStart: number; - /** Finished receiving response headers in milliseconds relative to fetchStart. */ - responseEnd: number; - }; - /** HTTP request data. */ - export type Request = { - /** Request URL. */ - url: string; - /** HTTP request method. */ - method: string; - /** HTTP request headers. */ - headers: Headers; - /** HTTP POST request data. */ - postData?: string; - /** The level of included referrer information. */ - referrerPolicy?: ReferrerPolicy; - /** The base64 cryptographic hash of the resource. */ - integrity?: string; - }; - /** HTTP response data. */ - export type Response = { - /** Response URL. This URL can be different from CachedResource.url in case of redirect. */ - url: string; - /** HTTP response status code. */ - status: number; - /** HTTP response status text. */ - statusText: string; - /** HTTP response headers. */ - headers: Headers; - /** Resource mimeType as determined by the browser. */ - mimeType: string; - /** Specifies where the response came from. */ - source: - | "unknown" - | "network" - | "memory-cache" - | "disk-cache" - | "service-worker" - | "inspector-override"; - /** Refined HTTP request headers that were actually transmitted over the network. */ - requestHeaders?: Headers; - /** Timing information for the given request. */ - timing?: ResourceTiming; - /** The security information for the given request. */ - security?: unknown; - }; - /** Network load metrics. */ - export type Metrics = { - /** Network protocol. ALPN Protocol ID Identification Sequence, as per RFC 7301 (for example, http/2, http/1.1, spdy/3.1) */ - protocol?: string; - /** Network priority. */ - priority?: "low" | "medium" | "high"; - /** Connection identifier. */ - connectionIdentifier?: string; - /** Remote IP address. */ - remoteAddress?: string; - /** Refined HTTP request headers that were actually transmitted over the network. */ - requestHeaders?: Headers; - /** Total HTTP request header bytes sent over the network. */ - requestHeaderBytesSent?: number; - /** Total HTTP request body bytes sent over the network. */ - requestBodyBytesSent?: number; - /** Total HTTP response header bytes received over the network. */ - responseHeaderBytesReceived?: number; - /** Total HTTP response body bytes received over the network. */ - responseBodyBytesReceived?: number; - /** Total decoded response body size in bytes. */ - responseBodyDecodedSize?: number; - /** Connection information for the completed request. */ - securityConnection?: unknown; - /** Whether or not the connection was proxied through a server. If <code>true</code>, the <code>remoteAddress</code> will be for the proxy server, not the server that provided the resource to the proxy server. */ - isProxyConnection?: boolean; - }; - /** WebSocket request data. */ - export type WebSocketRequest = { - /** HTTP response headers. */ - headers: Headers; - }; - /** WebSocket response data. */ - export type WebSocketResponse = { - /** HTTP response status code. */ - status: number; - /** HTTP response status text. */ - statusText: string; - /** HTTP response headers. */ - headers: Headers; - }; - /** WebSocket frame data. */ - export type WebSocketFrame = { - /** WebSocket frame opcode. */ - opcode: number; - /** WebSocket frame mask. */ - mask: boolean; - /** WebSocket frame payload data, binary frames (opcode = 2) are base64-encoded. */ - payloadData: string; - /** WebSocket frame payload length in bytes. */ - payloadLength: number; - }; - /** Information about the cached resource. */ - export type CachedResource = { - /** Resource URL. This is the url of the original network request. */ - url: string; - /** Type of this resource. */ - type: unknown; - /** Cached response data. */ - response?: Response; - /** Cached response body size. */ - bodySize: number; - /** URL of source map associated with this resource (if any). */ - sourceMapURL?: string; - }; - /** Information about the request initiator. */ - export type Initiator = { - /** Type of this initiator. */ - type: "parser" | "script" | "other"; - /** Initiator JavaScript stack trace, set for Script only. */ - stackTrace?: Console.StackTrace; - /** Initiator URL, set for Parser type only. */ - url?: string; - /** Initiator line number, set for Parser type only. */ - lineNumber?: number; - /** Set if the load was triggered by a DOM node, in addition to the other initiator information. */ - nodeId?: unknown; - }; - /** Different stages of a network request. */ - export type NetworkStage = "request" | "response"; - /** Different stages of a network request. */ - export type ResourceErrorType = - | "General" - | "AccessControl" - | "Cancellation" - | "Timeout"; - /** `Network.requestWillBeSent` */ - export type RequestWillBeSentEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Frame identifier. */ - frameId: FrameId; - /** Loader identifier. */ - loaderId: LoaderId; - /** URL of the document this request is loaded for. */ - documentURL: string; - /** Request data. */ - request: Request; - timestamp: Timestamp; - walltime: Walltime; - /** Request initiator. */ - initiator: Initiator; - /** Redirect response data. */ - redirectResponse?: Response; - /** Resource type. */ - type?: unknown; - /** Identifier for the context of where the load originated. In general this is the target identifier. For Workers this will be the workerId. */ - targetId?: string; - }; - /** `Network.responseReceived` */ - export type ResponseReceivedEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Frame identifier. */ - frameId: FrameId; - /** Loader identifier. */ - loaderId: LoaderId; - /** Timestamp. */ - timestamp: Timestamp; - /** Resource type. */ - type: unknown; - /** Response data. */ - response: Response; - }; - /** `Network.dataReceived` */ - export type DataReceivedEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Timestamp. */ - timestamp: Timestamp; - /** Data chunk length. */ - dataLength: number; - /** Actual bytes received (might be less than dataLength for compressed encodings). */ - encodedDataLength: number; - }; - /** `Network.loadingFinished` */ - export type LoadingFinishedEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Timestamp. */ - timestamp: Timestamp; - /** URL of source map associated with this resource (if any). */ - sourceMapURL?: string; - /** Network metrics. */ - metrics?: Metrics; - }; - /** `Network.loadingFailed` */ - export type LoadingFailedEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Timestamp. */ - timestamp: Timestamp; - /** User friendly error message. */ - errorText: string; - /** True if loading was canceled. */ - canceled?: boolean; - }; - /** `Network.requestServedFromMemoryCache` */ - export type RequestServedFromMemoryCacheEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Frame identifier. */ - frameId: FrameId; - /** Loader identifier. */ - loaderId: LoaderId; - /** URL of the document this request is loaded for. */ - documentURL: string; - /** Timestamp. */ - timestamp: Timestamp; - /** Request initiator. */ - initiator: Initiator; - /** Cached resource data. */ - resource: CachedResource; - }; - /** `Network.requestIntercepted` */ - export type RequestInterceptedEvent = { - /** Identifier for this intercepted network. Corresponds with an earlier <code>Network.requestWillBeSent</code>. */ - requestId: RequestId; - /** Original request content that would proceed if this is continued. */ - request: Request; - }; - /** `Network.responseIntercepted` */ - export type ResponseInterceptedEvent = { - /** Identifier for this intercepted network. Corresponds with an earlier <code>Network.requestWillBeSent</code>. */ - requestId: RequestId; - /** Original response content that would proceed if this is continued. */ - response: Response; - }; - /** `Network.webSocketWillSendHandshakeRequest` */ - export type WebSocketWillSendHandshakeRequestEvent = { - /** Request identifier. */ - requestId: RequestId; - timestamp: Timestamp; - walltime: Walltime; - /** WebSocket request data. */ - request: WebSocketRequest; - }; - /** `Network.webSocketHandshakeResponseReceived` */ - export type WebSocketHandshakeResponseReceivedEvent = { - /** Request identifier. */ - requestId: RequestId; - timestamp: Timestamp; - /** WebSocket response data. */ - response: WebSocketResponse; - }; - /** `Network.webSocketCreated` */ - export type WebSocketCreatedEvent = { - /** Request identifier. */ - requestId: RequestId; - /** WebSocket request URL. */ - url: string; - }; - /** `Network.webSocketClosed` */ - export type WebSocketClosedEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Timestamp. */ - timestamp: Timestamp; - }; - /** `Network.webSocketFrameReceived` */ - export type WebSocketFrameReceivedEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Timestamp. */ - timestamp: Timestamp; - /** WebSocket response data. */ - response: WebSocketFrame; - }; - /** `Network.webSocketFrameError` */ - export type WebSocketFrameErrorEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Timestamp. */ - timestamp: Timestamp; - /** WebSocket frame error message. */ - errorMessage: string; - }; - /** `Network.webSocketFrameSent` */ - export type WebSocketFrameSentEvent = { - /** Request identifier. */ - requestId: RequestId; - /** Timestamp. */ - timestamp: Timestamp; - /** WebSocket response data. */ - response: WebSocketFrame; - }; - /** `Network.enable` */ - export type EnableRequest = {}; - /** `Network.enable` */ - export type EnableResponse = {}; - /** `Network.disable` */ - export type DisableRequest = {}; - /** `Network.disable` */ - export type DisableResponse = {}; - /** `Network.setExtraHTTPHeaders` */ - export type SetExtraHTTPHeadersRequest = { - /** Map with extra HTTP headers. */ - headers: Headers; - }; - /** `Network.setExtraHTTPHeaders` */ - export type SetExtraHTTPHeadersResponse = {}; - /** `Network.getResponseBody` */ - export type GetResponseBodyRequest = { - /** Identifier of the network request to get content for. */ - requestId: RequestId; - }; - /** `Network.getResponseBody` */ - export type GetResponseBodyResponse = { - /** Response body. */ - body: string; - /** True, if content was sent as base64. */ - base64Encoded: boolean; - }; - /** `Network.setResourceCachingDisabled` */ - export type SetResourceCachingDisabledRequest = { - /** Whether to prevent usage of the resource cache. */ - disabled: boolean; - }; - /** `Network.setResourceCachingDisabled` */ - export type SetResourceCachingDisabledResponse = {}; - /** `Network.loadResource` */ - export type LoadResourceRequest = { - /** Frame to load the resource from. */ - frameId: FrameId; - /** URL of the resource to load. */ - url: string; - }; - /** `Network.loadResource` */ - export type LoadResourceResponse = { - /** Resource content. */ - content: string; - /** Resource mimeType. */ - mimeType: string; - /** HTTP response status code. */ - status: number; - }; - /** `Network.getSerializedCertificate` */ - export type GetSerializedCertificateRequest = { - requestId: RequestId; - }; - /** `Network.getSerializedCertificate` */ - export type GetSerializedCertificateResponse = { - /** Represents a base64 encoded WebCore::CertificateInfo object. */ - serializedCertificate: string; - }; - /** `Network.resolveWebSocket` */ - export type ResolveWebSocketRequest = { - /** Identifier of the WebSocket resource to resolve. */ - requestId: RequestId; - /** Symbolic group name that can be used to release multiple objects. */ - objectGroup?: string; - }; - /** `Network.resolveWebSocket` */ - export type ResolveWebSocketResponse = { - /** JavaScript object wrapper for given node. */ - object: Runtime.RemoteObject; - }; - /** `Network.setInterceptionEnabled` */ - export type SetInterceptionEnabledRequest = { - enabled: boolean; - }; - /** `Network.setInterceptionEnabled` */ - export type SetInterceptionEnabledResponse = {}; - /** `Network.addInterception` */ - export type AddInterceptionRequest = { - /** URL pattern to intercept, intercept everything if not specified or empty */ - url: string; - /** Stage to intercept. */ - stage: NetworkStage; - /** If false, ignores letter casing of `url` parameter. */ - caseSensitive?: boolean; - /** If true, treats `url` parameter as a regular expression. */ - isRegex?: boolean; - }; - /** `Network.addInterception` */ - export type AddInterceptionResponse = {}; - /** `Network.removeInterception` */ - export type RemoveInterceptionRequest = { - url: string; - /** Stage to intercept. */ - stage: NetworkStage; - /** If false, ignores letter casing of `url` parameter. */ - caseSensitive?: boolean; - /** If true, treats `url` parameter as a regular expression. */ - isRegex?: boolean; - }; - /** `Network.removeInterception` */ - export type RemoveInterceptionResponse = {}; - /** `Network.interceptContinue` */ - export type InterceptContinueRequest = { - /** Identifier for the intercepted Network request or response to continue. */ - requestId: RequestId; - /** Stage to continue. */ - stage: NetworkStage; - }; - /** `Network.interceptContinue` */ - export type InterceptContinueResponse = {}; - /** `Network.interceptWithRequest` */ - export type InterceptWithRequestRequest = { - /** Identifier for the intercepted Network request or response to continue. */ - requestId: RequestId; - /** HTTP request url. */ - url?: string; - /** HTTP request method. */ - method?: string; - /** HTTP response headers. Pass through original values if unmodified. */ - headers?: Headers; - /** HTTP POST request data, base64-encoded. */ - postData?: string; - }; - /** `Network.interceptWithRequest` */ - export type InterceptWithRequestResponse = {}; - /** `Network.interceptWithResponse` */ - export type InterceptWithResponseRequest = { - /** Identifier for the intercepted Network response to modify. */ - requestId: RequestId; - content: string; - /** True, if content was sent as base64. */ - base64Encoded: boolean; - /** MIME Type for the data. */ - mimeType?: string; - /** HTTP response status code. Pass through original values if unmodified. */ - status?: number; - /** HTTP response status text. Pass through original values if unmodified. */ - statusText?: string; - /** HTTP response headers. Pass through original values if unmodified. */ - headers?: Headers; - }; - /** `Network.interceptWithResponse` */ - export type InterceptWithResponseResponse = {}; - /** `Network.interceptRequestWithResponse` */ - export type InterceptRequestWithResponseRequest = { - /** Identifier for the intercepted Network response to modify. */ - requestId: RequestId; - content: string; - /** True, if content was sent as base64. */ - base64Encoded: boolean; - /** MIME Type for the data. */ - mimeType: string; - /** HTTP response status code. */ - status: number; - /** HTTP response status text. */ - statusText: string; - /** HTTP response headers. */ - headers: Headers; - }; - /** `Network.interceptRequestWithResponse` */ - export type InterceptRequestWithResponseResponse = {}; - /** `Network.interceptRequestWithError` */ - export type InterceptRequestWithErrorRequest = { - /** Identifier for the intercepted Network request to fail. */ - requestId: RequestId; - /** Deliver error reason for the request failure. */ - errorType: ResourceErrorType; - }; - /** `Network.interceptRequestWithError` */ - export type InterceptRequestWithErrorResponse = {}; - /** `Network.setEmulatedConditions` */ - export type SetEmulatedConditionsRequest = { - /** Limits the bytes per second of requests if positive. Removes any limits if zero or not provided. */ - bytesPerSecondLimit?: number; - }; - /** `Network.setEmulatedConditions` */ - export type SetEmulatedConditionsResponse = {}; - } - export namespace Runtime { - /** Unique object identifier. */ - export type RemoteObjectId = string; - /** Mirror object referencing original JavaScript object. */ - export type RemoteObject = { - /** Object type. */ - type: - | "object" - | "function" - | "undefined" - | "string" - | "number" - | "boolean" - | "symbol" - | "bigint"; - /** Object subtype hint. Specified for <code>object</code> <code>function</code> (for class) type values only. */ - subtype?: - | "array" - | "null" - | "node" - | "regexp" - | "date" - | "error" - | "map" - | "set" - | "weakmap" - | "weakset" - | "iterator" - | "class" - | "proxy" - | "weakref"; - /** Object class (constructor) name. Specified for <code>object</code> type values only. */ - className?: string; - /** Remote object value (in case of primitive values or JSON values if it was requested). */ - value?: any; - /** String representation of the object. */ - description?: string; - /** Unique object identifier (for non-primitive values). */ - objectId?: RemoteObjectId; - /** Size of the array/collection. Specified for array/map/set/weakmap/weakset object type values only. */ - size?: number; - /** Remote object for the class prototype. Specified for class object type values only. */ - classPrototype?: RemoteObject; - /** Preview containing abbreviated property values. Specified for <code>object</code> type values only. */ - preview?: ObjectPreview; - }; - /** Object containing abbreviated remote object value. */ - export type ObjectPreview = { - /** Object type. */ - type: - | "object" - | "function" - | "undefined" - | "string" - | "number" - | "boolean" - | "symbol" - | "bigint"; - /** Object subtype hint. Specified for <code>object</code> type values only. */ - subtype?: - | "array" - | "null" - | "node" - | "regexp" - | "date" - | "error" - | "map" - | "set" - | "weakmap" - | "weakset" - | "iterator" - | "class" - | "proxy" - | "weakref"; - /** String representation of the object. */ - description?: string; - /** Determines whether preview is lossless (contains all information of the original object). */ - lossless: boolean; - /** True iff some of the properties of the original did not fit. */ - overflow?: boolean; - /** List of the properties. */ - properties?: Array<PropertyPreview>; - /** List of the entries. Specified for <code>map</code> and <code>set</code> subtype values only. */ - entries?: Array<EntryPreview>; - /** Size of the array/collection. Specified for array/map/set/weakmap/weakset object type values only. */ - size?: number; - }; - export type PropertyPreview = { - /** Property name. */ - name: string; - /** Object type. */ - type: - | "object" - | "function" - | "undefined" - | "string" - | "number" - | "boolean" - | "symbol" - | "bigint" - | "accessor"; - /** Object subtype hint. Specified for <code>object</code> type values only. */ - subtype?: - | "array" - | "null" - | "node" - | "regexp" - | "date" - | "error" - | "map" - | "set" - | "weakmap" - | "weakset" - | "iterator" - | "class" - | "proxy" - | "weakref"; - /** User-friendly property value string. */ - value?: string; - /** Nested value preview. */ - valuePreview?: ObjectPreview; - /** True if this is a private field. */ - isPrivate?: boolean; - /** True if this is an internal property. */ - internal?: boolean; - }; - export type EntryPreview = { - /** Entry key. Specified for map-like collection entries. */ - key?: ObjectPreview; - /** Entry value. */ - value: ObjectPreview; - }; - export type CollectionEntry = { - /** Entry key of a map-like collection, otherwise not provided. */ - key?: Runtime.RemoteObject; - /** Entry value. */ - value: Runtime.RemoteObject; - }; - /** Object property descriptor. */ - export type PropertyDescriptor = { - /** Property name or symbol description. */ - name: string; - /** The value associated with the property. */ - value?: RemoteObject; - /** True if the value associated with the property may be changed (data descriptors only). */ - writable?: boolean; - /** A function which serves as a getter for the property, or <code>undefined</code> if there is no getter (accessor descriptors only). */ - get?: RemoteObject; - /** A function which serves as a setter for the property, or <code>undefined</code> if there is no setter (accessor descriptors only). */ - set?: RemoteObject; - /** True if the result was thrown during the evaluation. */ - wasThrown?: boolean; - /** True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. */ - configurable?: boolean; - /** True if this property shows up during enumeration of the properties on the corresponding object. */ - enumerable?: boolean; - /** True if the property is owned for the object. */ - isOwn?: boolean; - /** Property symbol object, if the property is a symbol. */ - symbol?: Runtime.RemoteObject; - /** True if the property is a private field. */ - isPrivate?: boolean; - /** True if the property value came from a native getter. */ - nativeGetter?: boolean; - }; - /** Object internal property descriptor. This property isn't normally visible in JavaScript code. */ - export type InternalPropertyDescriptor = { - /** Conventional property name. */ - name: string; - /** The value associated with the property. */ - value?: RemoteObject; - }; - /** Represents function call argument. Either remote object id <code>objectId</code> or primitive <code>value</code> or neither of (for undefined) them should be specified. */ - export type CallArgument = { - /** Primitive value. */ - value?: any; - /** Remote object handle. */ - objectId?: RemoteObjectId; - }; - /** Id of an execution context. */ - export type ExecutionContextId = number; - /** Type of the execution context. */ - export type ExecutionContextType = "normal" | "user" | "internal"; - /** Description of an isolated world. */ - export type ExecutionContextDescription = { - /** Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. */ - id: ExecutionContextId; - type: ExecutionContextType; - /** Human readable name describing given context. */ - name: string; - /** Id of the owning frame. */ - frameId: Network.FrameId; - }; - /** Syntax error type: "none" for no error, "irrecoverable" for unrecoverable errors, "unterminated-literal" for when there is an unterminated literal, "recoverable" for when the expression is unfinished but valid so far. */ - export type SyntaxErrorType = - | "none" - | "irrecoverable" - | "unterminated-literal" - | "recoverable"; - /** Range of an error in source code. */ - export type ErrorRange = { - /** Start offset of range (inclusive). */ - startOffset: number; - /** End offset of range (exclusive). */ - endOffset: number; - }; - export type StructureDescription = { - /** Array of strings, where the strings represent object properties. */ - fields?: Array<string>; - /** Array of strings, where the strings represent optional object properties. */ - optionalFields?: Array<string>; - /** Name of the constructor. */ - constructorName?: string; - /** Pointer to the StructureRepresentation of the protoype if one exists. */ - prototypeStructure?: StructureDescription; - /** If true, it indicates that the fields in this StructureDescription may be inaccurate. I.e, there might have been fields that have been deleted before it was profiled or it has fields we haven't profiled. */ - isImprecise?: boolean; - }; - export type TypeSet = { - /** Indicates if this type description has been type Function. */ - isFunction: boolean; - /** Indicates if this type description has been type Undefined. */ - isUndefined: boolean; - /** Indicates if this type description has been type Null. */ - isNull: boolean; - /** Indicates if this type description has been type Boolean. */ - isBoolean: boolean; - /** Indicates if this type description has been type Integer. */ - isInteger: boolean; - /** Indicates if this type description has been type Number. */ - isNumber: boolean; - /** Indicates if this type description has been type String. */ - isString: boolean; - /** Indicates if this type description has been type Object. */ - isObject: boolean; - /** Indicates if this type description has been type Symbol. */ - isSymbol: boolean; - /** Indicates if this type description has been type BigInt. */ - isBigInt: boolean; - }; - /** Container for type information that has been gathered. */ - export type TypeDescription = { - /** If true, we were able to correlate the offset successfuly with a program location. If false, the offset may be bogus or the offset may be from a CodeBlock that hasn't executed. */ - isValid: boolean; - /** Least common ancestor of all Constructors if the TypeDescription has seen any structures. This string is the display name of the shared constructor function. */ - leastCommonAncestor?: string; - /** Set of booleans for determining the aggregate type of this type description. */ - typeSet?: TypeSet; - /** Array of descriptions for all structures seen for this variable. */ - structures?: Array<StructureDescription>; - /** If true, this indicates that no more structures are being profiled because some maximum threshold has been reached and profiling has stopped because of memory pressure. */ - isTruncated?: boolean; - }; - /** Describes the location of an expression we want type information for. */ - export type TypeLocation = { - /** What kind of type information do we want (normal, function return values, 'this' statement). */ - typeInformationDescriptor: number; - /** sourceID uniquely identifying a script */ - sourceID: string; - /** character offset for assignment range */ - divot: number; - }; - /** From Wikipedia: a basic block is a portion of the code within a program with only one entry point and only one exit point. This type gives the location of a basic block and if that basic block has executed. */ - export type BasicBlock = { - /** Start offset of the basic block. */ - startOffset: number; - /** End offset of the basic block. */ - endOffset: number; - /** Indicates if the basic block has executed before. */ - hasExecuted: boolean; - /** Indicates how many times the basic block has executed. */ - executionCount: number; - }; - /** `Runtime.executionContextCreated` */ - export type ExecutionContextCreatedEvent = { - /** A newly created execution context. */ - context: ExecutionContextDescription; - }; - /** `Runtime.parse` */ - export type ParseRequest = { - /** Source code to parse. */ - source: string; - }; - /** `Runtime.parse` */ - export type ParseResponse = { - /** Parse result. */ - result: SyntaxErrorType; - /** Parse error message. */ - message?: string; - /** Range in the source where the error occurred. */ - range?: ErrorRange; - }; - /** `Runtime.evaluate` */ - export type EvaluateRequest = { - /** Expression to evaluate. */ - expression: string; - /** Symbolic group name that can be used to release multiple objects. */ - objectGroup?: string; - /** Determines whether Command Line API should be available during the evaluation. */ - includeCommandLineAPI?: boolean; - /** Specifies whether evaluation should stop on exceptions and mute console. Overrides setPauseOnException state. */ - doNotPauseOnExceptionsAndMuteConsole?: boolean; - /** Specifies in which isolated context to perform evaluation. Each content script lives in an isolated context and this parameter may be used to specify one of those contexts. If the parameter is omitted or 0 the evaluation will be performed in the context of the inspected page. */ - contextId?: Runtime.ExecutionContextId; - /** Whether the result is expected to be a JSON object that should be sent by value. */ - returnByValue?: boolean; - /** Whether preview should be generated for the result. */ - generatePreview?: boolean; - /** Whether the resulting value should be considered for saving in the $n history. */ - saveResult?: boolean; - /** Whether the expression should be considered to be in a user gesture or not. */ - emulateUserGesture?: boolean; - }; - /** `Runtime.evaluate` */ - export type EvaluateResponse = { - /** Evaluation result. */ - result: RemoteObject; - /** True if the result was thrown during the evaluation. */ - wasThrown?: boolean; - /** If the result was saved, this is the $n index that can be used to access the value. */ - savedResultIndex?: number; - }; - /** `Runtime.awaitPromise` */ - export type AwaitPromiseRequest = { - /** Identifier of the promise. */ - promiseObjectId: RemoteObjectId; - /** Whether the result is expected to be a JSON object that should be sent by value. */ - returnByValue?: boolean; - /** Whether preview should be generated for the result. */ - generatePreview?: boolean; - /** Whether the resulting value should be considered for saving in the $n history. */ - saveResult?: boolean; - }; - /** `Runtime.awaitPromise` */ - export type AwaitPromiseResponse = { - /** Evaluation result. */ - result: RemoteObject; - /** True if the result was thrown during the evaluation. */ - wasThrown?: boolean; - /** If the result was saved, this is the $n index that can be used to access the value. */ - savedResultIndex?: number; - }; - /** `Runtime.callFunctionOn` */ - export type CallFunctionOnRequest = { - /** Identifier of the object to call function on. */ - objectId: RemoteObjectId; - /** Declaration of the function to call. */ - functionDeclaration: string; - /** Call arguments. All call arguments must belong to the same JavaScript world as the target object. */ - arguments?: Array<CallArgument>; - /** Specifies whether function call should stop on exceptions and mute console. Overrides setPauseOnException state. */ - doNotPauseOnExceptionsAndMuteConsole?: boolean; - /** Whether the result is expected to be a JSON object which should be sent by value. */ - returnByValue?: boolean; - /** Whether preview should be generated for the result. */ - generatePreview?: boolean; - /** Whether the expression should be considered to be in a user gesture or not. */ - emulateUserGesture?: boolean; - }; - /** `Runtime.callFunctionOn` */ - export type CallFunctionOnResponse = { - /** Call result. */ - result: RemoteObject; - /** True if the result was thrown during the evaluation. */ - wasThrown?: boolean; - }; - /** `Runtime.getPreview` */ - export type GetPreviewRequest = { - /** Identifier of the object to return a preview for. */ - objectId: RemoteObjectId; - }; - /** `Runtime.getPreview` */ - export type GetPreviewResponse = { - preview: ObjectPreview; - }; - /** `Runtime.getProperties` */ - export type GetPropertiesRequest = { - /** Identifier of the object to return properties for. */ - objectId: RemoteObjectId; - /** If true, returns properties belonging only to the object itself, not to its prototype chain. */ - ownProperties?: boolean; - /** If provided skip to this value before collecting values. Otherwise, start at the beginning. Has no effect when the `objectId` is for a `iterator`/`WeakMap`/`WeakSet` object. */ - fetchStart?: number; - /** If provided only return `fetchCount` values. Otherwise, return values all the way to the end. */ - fetchCount?: number; - /** Whether preview should be generated for property values. */ - generatePreview?: boolean; - }; - /** `Runtime.getProperties` */ - export type GetPropertiesResponse = { - /** Object properties. */ - properties: Array<PropertyDescriptor>; - /** Internal object properties. Only included if `fetchStart` is 0. */ - internalProperties?: Array<InternalPropertyDescriptor>; - }; - /** `Runtime.getDisplayableProperties` */ - export type GetDisplayablePropertiesRequest = { - /** Identifier of the object to return properties for. */ - objectId: RemoteObjectId; - /** If provided skip to this value before collecting values. Otherwise, start at the beginning. Has no effect when the `objectId` is for a `iterator`/`WeakMap`/`WeakSet` object. */ - fetchStart?: number; - /** If provided only return `fetchCount` values. Otherwise, return values all the way to the end. */ - fetchCount?: number; - /** Whether preview should be generated for property values. */ - generatePreview?: boolean; - }; - /** `Runtime.getDisplayableProperties` */ - export type GetDisplayablePropertiesResponse = { - /** Object properties. */ - properties: Array<PropertyDescriptor>; - /** Internal object properties. Only included if `fetchStart` is 0. */ - internalProperties?: Array<InternalPropertyDescriptor>; - }; - /** `Runtime.getCollectionEntries` */ - export type GetCollectionEntriesRequest = { - /** Id of the collection to get entries for. */ - objectId: Runtime.RemoteObjectId; - /** Symbolic group name that can be used to release multiple. If not provided, it will be the same objectGroup as the RemoteObject determined from <code>objectId</code>. This is useful for WeakMap to release the collection entries. */ - objectGroup?: string; - /** If provided skip to this value before collecting values. Otherwise, start at the beginning. Has no effect when the `objectId<` is for a `iterator<`/`WeakMap<`/`WeakSet<` object. */ - fetchStart?: number; - /** If provided only return `fetchCount` values. Otherwise, return values all the way to the end. */ - fetchCount?: number; - }; - /** `Runtime.getCollectionEntries` */ - export type GetCollectionEntriesResponse = { - /** Array of collection entries. */ - entries: Array<CollectionEntry>; - }; - /** `Runtime.saveResult` */ - export type SaveResultRequest = { - /** Id or value of the object to save. */ - value: CallArgument; - /** Unique id of the execution context. To specify in which execution context script evaluation should be performed. If not provided, determine from the CallArgument's objectId. */ - contextId?: ExecutionContextId; - }; - /** `Runtime.saveResult` */ - export type SaveResultResponse = { - /** If the value was saved, this is the $n index that can be used to access the value. */ - savedResultIndex?: number; - }; - /** `Runtime.setSavedResultAlias` */ - export type SetSavedResultAliasRequest = { - /** Passing an empty/null string will clear the alias. */ - alias?: string; - }; - /** `Runtime.setSavedResultAlias` */ - export type SetSavedResultAliasResponse = {}; - /** `Runtime.releaseObject` */ - export type ReleaseObjectRequest = { - /** Identifier of the object to release. */ - objectId: RemoteObjectId; - }; - /** `Runtime.releaseObject` */ - export type ReleaseObjectResponse = {}; - /** `Runtime.releaseObjectGroup` */ - export type ReleaseObjectGroupRequest = { - /** Symbolic object group name. */ - objectGroup: string; - }; - /** `Runtime.releaseObjectGroup` */ - export type ReleaseObjectGroupResponse = {}; - /** `Runtime.enable` */ - export type EnableRequest = {}; - /** `Runtime.enable` */ - export type EnableResponse = {}; - /** `Runtime.disable` */ - export type DisableRequest = {}; - /** `Runtime.disable` */ - export type DisableResponse = {}; - /** `Runtime.getRuntimeTypesForVariablesAtOffsets` */ - export type GetRuntimeTypesForVariablesAtOffsetsRequest = { - /** An array of type locations we're requesting information for. Results are expected in the same order they're sent in. */ - locations: Array<TypeLocation>; - }; - /** `Runtime.getRuntimeTypesForVariablesAtOffsets` */ - export type GetRuntimeTypesForVariablesAtOffsetsResponse = { - types: Array<TypeDescription>; - }; - /** `Runtime.enableTypeProfiler` */ - export type EnableTypeProfilerRequest = {}; - /** `Runtime.enableTypeProfiler` */ - export type EnableTypeProfilerResponse = {}; - /** `Runtime.disableTypeProfiler` */ - export type DisableTypeProfilerRequest = {}; - /** `Runtime.disableTypeProfiler` */ - export type DisableTypeProfilerResponse = {}; - /** `Runtime.enableControlFlowProfiler` */ - export type EnableControlFlowProfilerRequest = {}; - /** `Runtime.enableControlFlowProfiler` */ - export type EnableControlFlowProfilerResponse = {}; - /** `Runtime.disableControlFlowProfiler` */ - export type DisableControlFlowProfilerRequest = {}; - /** `Runtime.disableControlFlowProfiler` */ - export type DisableControlFlowProfilerResponse = {}; - /** `Runtime.getBasicBlocks` */ - export type GetBasicBlocksRequest = { - /** Indicates which sourceID information is requested for. */ - sourceID: string; - }; - /** `Runtime.getBasicBlocks` */ - export type GetBasicBlocksResponse = { - basicBlocks: Array<BasicBlock>; - }; - } - export namespace ScriptProfiler { - export type EventType = "API" | "Microtask" | "Other"; - export type Event = { - startTime: number; - endTime: number; - type: EventType; - }; - export type ExpressionLocation = { - /** 1-based. */ - line: number; - /** 1-based. */ - column: number; - }; - export type StackFrame = { - /** Unique script identifier. */ - sourceID: Debugger.ScriptId; - /** A displayable name for the stack frame. i.e function name, (program), etc. */ - name: string; - /** -1 if unavailable. 1-based if available. */ - line: number; - /** -1 if unavailable. 1-based if available. */ - column: number; - url: string; - expressionLocation?: ExpressionLocation; - }; - export type StackTrace = { - timestamp: number; - /** First array item is the bottom of the call stack and last array item is the top of the call stack. */ - stackFrames: Array<StackFrame>; - }; - export type Samples = { - stackTraces: Array<StackTrace>; - }; - /** `ScriptProfiler.trackingStart` */ - export type TrackingStartEvent = { - timestamp: number; - }; - /** `ScriptProfiler.trackingUpdate` */ - export type TrackingUpdateEvent = { - event: Event; - }; - /** `ScriptProfiler.trackingComplete` */ - export type TrackingCompleteEvent = { - timestamp: number; - /** Stack traces. */ - samples?: Samples; - }; - /** `ScriptProfiler.startTracking` */ - export type StartTrackingRequest = { - /** Start the sampling profiler, defaults to false. */ - includeSamples?: boolean; - }; - /** `ScriptProfiler.startTracking` */ - export type StartTrackingResponse = {}; - /** `ScriptProfiler.stopTracking` */ - export type StopTrackingRequest = {}; - /** `ScriptProfiler.stopTracking` */ - export type StopTrackingResponse = {}; - } - export type EventMap = { - "Console.messageAdded": Console.MessageAddedEvent; - "Console.messageRepeatCountUpdated": Console.MessageRepeatCountUpdatedEvent; - "Console.messagesCleared": Console.MessagesClearedEvent; - "Console.heapSnapshot": Console.HeapSnapshotEvent; - "Debugger.globalObjectCleared": Debugger.GlobalObjectClearedEvent; - "Debugger.scriptParsed": Debugger.ScriptParsedEvent; - "Debugger.scriptFailedToParse": Debugger.ScriptFailedToParseEvent; - "Debugger.breakpointResolved": Debugger.BreakpointResolvedEvent; - "Debugger.paused": Debugger.PausedEvent; - "Debugger.resumed": Debugger.ResumedEvent; - "Debugger.didSampleProbe": Debugger.DidSampleProbeEvent; - "Debugger.playBreakpointActionSound": Debugger.PlayBreakpointActionSoundEvent; - "Heap.garbageCollected": Heap.GarbageCollectedEvent; - "Heap.trackingStart": Heap.TrackingStartEvent; - "Heap.trackingComplete": Heap.TrackingCompleteEvent; - "Network.requestWillBeSent": Network.RequestWillBeSentEvent; - "Network.responseReceived": Network.ResponseReceivedEvent; - "Network.dataReceived": Network.DataReceivedEvent; - "Network.loadingFinished": Network.LoadingFinishedEvent; - "Network.loadingFailed": Network.LoadingFailedEvent; - "Network.requestServedFromMemoryCache": Network.RequestServedFromMemoryCacheEvent; - "Network.requestIntercepted": Network.RequestInterceptedEvent; - "Network.responseIntercepted": Network.ResponseInterceptedEvent; - "Network.webSocketWillSendHandshakeRequest": Network.WebSocketWillSendHandshakeRequestEvent; - "Network.webSocketHandshakeResponseReceived": Network.WebSocketHandshakeResponseReceivedEvent; - "Network.webSocketCreated": Network.WebSocketCreatedEvent; - "Network.webSocketClosed": Network.WebSocketClosedEvent; - "Network.webSocketFrameReceived": Network.WebSocketFrameReceivedEvent; - "Network.webSocketFrameError": Network.WebSocketFrameErrorEvent; - "Network.webSocketFrameSent": Network.WebSocketFrameSentEvent; - "Runtime.executionContextCreated": Runtime.ExecutionContextCreatedEvent; - "ScriptProfiler.trackingStart": ScriptProfiler.TrackingStartEvent; - "ScriptProfiler.trackingUpdate": ScriptProfiler.TrackingUpdateEvent; - "ScriptProfiler.trackingComplete": ScriptProfiler.TrackingCompleteEvent; - }; - export type RequestMap = { - "Console.enable": Console.EnableRequest; - "Console.disable": Console.DisableRequest; - "Console.clearMessages": Console.ClearMessagesRequest; - "Console.getLoggingChannels": Console.GetLoggingChannelsRequest; - "Console.setLoggingChannelLevel": Console.SetLoggingChannelLevelRequest; - "Debugger.enable": Debugger.EnableRequest; - "Debugger.disable": Debugger.DisableRequest; - "Debugger.setAsyncStackTraceDepth": Debugger.SetAsyncStackTraceDepthRequest; - "Debugger.setBreakpointsActive": Debugger.SetBreakpointsActiveRequest; - "Debugger.setBreakpointByUrl": Debugger.SetBreakpointByUrlRequest; - "Debugger.setBreakpoint": Debugger.SetBreakpointRequest; - "Debugger.removeBreakpoint": Debugger.RemoveBreakpointRequest; - "Debugger.addSymbolicBreakpoint": Debugger.AddSymbolicBreakpointRequest; - "Debugger.removeSymbolicBreakpoint": Debugger.RemoveSymbolicBreakpointRequest; - "Debugger.continueUntilNextRunLoop": Debugger.ContinueUntilNextRunLoopRequest; - "Debugger.continueToLocation": Debugger.ContinueToLocationRequest; - "Debugger.stepNext": Debugger.StepNextRequest; - "Debugger.stepOver": Debugger.StepOverRequest; - "Debugger.stepInto": Debugger.StepIntoRequest; - "Debugger.stepOut": Debugger.StepOutRequest; - "Debugger.pause": Debugger.PauseRequest; - "Debugger.resume": Debugger.ResumeRequest; - "Debugger.searchInContent": Debugger.SearchInContentRequest; - "Debugger.getScriptSource": Debugger.GetScriptSourceRequest; - "Debugger.getFunctionDetails": Debugger.GetFunctionDetailsRequest; - "Debugger.getBreakpointLocations": Debugger.GetBreakpointLocationsRequest; - "Debugger.setPauseOnDebuggerStatements": Debugger.SetPauseOnDebuggerStatementsRequest; - "Debugger.setPauseOnExceptions": Debugger.SetPauseOnExceptionsRequest; - "Debugger.setPauseOnAssertions": Debugger.SetPauseOnAssertionsRequest; - "Debugger.setPauseOnMicrotasks": Debugger.SetPauseOnMicrotasksRequest; - "Debugger.setPauseForInternalScripts": Debugger.SetPauseForInternalScriptsRequest; - "Debugger.evaluateOnCallFrame": Debugger.EvaluateOnCallFrameRequest; - "Debugger.setShouldBlackboxURL": Debugger.SetShouldBlackboxURLRequest; - "Debugger.setBlackboxBreakpointEvaluations": Debugger.SetBlackboxBreakpointEvaluationsRequest; - "Heap.enable": Heap.EnableRequest; - "Heap.disable": Heap.DisableRequest; - "Heap.gc": Heap.GcRequest; - "Heap.snapshot": Heap.SnapshotRequest; - "Heap.startTracking": Heap.StartTrackingRequest; - "Heap.stopTracking": Heap.StopTrackingRequest; - "Heap.getPreview": Heap.GetPreviewRequest; - "Heap.getRemoteObject": Heap.GetRemoteObjectRequest; - "Network.enable": Network.EnableRequest; - "Network.disable": Network.DisableRequest; - "Network.setExtraHTTPHeaders": Network.SetExtraHTTPHeadersRequest; - "Network.getResponseBody": Network.GetResponseBodyRequest; - "Network.setResourceCachingDisabled": Network.SetResourceCachingDisabledRequest; - "Network.loadResource": Network.LoadResourceRequest; - "Network.getSerializedCertificate": Network.GetSerializedCertificateRequest; - "Network.resolveWebSocket": Network.ResolveWebSocketRequest; - "Network.setInterceptionEnabled": Network.SetInterceptionEnabledRequest; - "Network.addInterception": Network.AddInterceptionRequest; - "Network.removeInterception": Network.RemoveInterceptionRequest; - "Network.interceptContinue": Network.InterceptContinueRequest; - "Network.interceptWithRequest": Network.InterceptWithRequestRequest; - "Network.interceptWithResponse": Network.InterceptWithResponseRequest; - "Network.interceptRequestWithResponse": Network.InterceptRequestWithResponseRequest; - "Network.interceptRequestWithError": Network.InterceptRequestWithErrorRequest; - "Network.setEmulatedConditions": Network.SetEmulatedConditionsRequest; - "Runtime.parse": Runtime.ParseRequest; - "Runtime.evaluate": Runtime.EvaluateRequest; - "Runtime.awaitPromise": Runtime.AwaitPromiseRequest; - "Runtime.callFunctionOn": Runtime.CallFunctionOnRequest; - "Runtime.getPreview": Runtime.GetPreviewRequest; - "Runtime.getProperties": Runtime.GetPropertiesRequest; - "Runtime.getDisplayableProperties": Runtime.GetDisplayablePropertiesRequest; - "Runtime.getCollectionEntries": Runtime.GetCollectionEntriesRequest; - "Runtime.saveResult": Runtime.SaveResultRequest; - "Runtime.setSavedResultAlias": Runtime.SetSavedResultAliasRequest; - "Runtime.releaseObject": Runtime.ReleaseObjectRequest; - "Runtime.releaseObjectGroup": Runtime.ReleaseObjectGroupRequest; - "Runtime.enable": Runtime.EnableRequest; - "Runtime.disable": Runtime.DisableRequest; - "Runtime.getRuntimeTypesForVariablesAtOffsets": Runtime.GetRuntimeTypesForVariablesAtOffsetsRequest; - "Runtime.enableTypeProfiler": Runtime.EnableTypeProfilerRequest; - "Runtime.disableTypeProfiler": Runtime.DisableTypeProfilerRequest; - "Runtime.enableControlFlowProfiler": Runtime.EnableControlFlowProfilerRequest; - "Runtime.disableControlFlowProfiler": Runtime.DisableControlFlowProfilerRequest; - "Runtime.getBasicBlocks": Runtime.GetBasicBlocksRequest; - "ScriptProfiler.startTracking": ScriptProfiler.StartTrackingRequest; - "ScriptProfiler.stopTracking": ScriptProfiler.StopTrackingRequest; - }; - export type ResponseMap = { - "Console.enable": Console.EnableResponse; - "Console.disable": Console.DisableResponse; - "Console.clearMessages": Console.ClearMessagesResponse; - "Console.getLoggingChannels": Console.GetLoggingChannelsResponse; - "Console.setLoggingChannelLevel": Console.SetLoggingChannelLevelResponse; - "Debugger.enable": Debugger.EnableResponse; - "Debugger.disable": Debugger.DisableResponse; - "Debugger.setAsyncStackTraceDepth": Debugger.SetAsyncStackTraceDepthResponse; - "Debugger.setBreakpointsActive": Debugger.SetBreakpointsActiveResponse; - "Debugger.setBreakpointByUrl": Debugger.SetBreakpointByUrlResponse; - "Debugger.setBreakpoint": Debugger.SetBreakpointResponse; - "Debugger.removeBreakpoint": Debugger.RemoveBreakpointResponse; - "Debugger.addSymbolicBreakpoint": Debugger.AddSymbolicBreakpointResponse; - "Debugger.removeSymbolicBreakpoint": Debugger.RemoveSymbolicBreakpointResponse; - "Debugger.continueUntilNextRunLoop": Debugger.ContinueUntilNextRunLoopResponse; - "Debugger.continueToLocation": Debugger.ContinueToLocationResponse; - "Debugger.stepNext": Debugger.StepNextResponse; - "Debugger.stepOver": Debugger.StepOverResponse; - "Debugger.stepInto": Debugger.StepIntoResponse; - "Debugger.stepOut": Debugger.StepOutResponse; - "Debugger.pause": Debugger.PauseResponse; - "Debugger.resume": Debugger.ResumeResponse; - "Debugger.searchInContent": Debugger.SearchInContentResponse; - "Debugger.getScriptSource": Debugger.GetScriptSourceResponse; - "Debugger.getFunctionDetails": Debugger.GetFunctionDetailsResponse; - "Debugger.getBreakpointLocations": Debugger.GetBreakpointLocationsResponse; - "Debugger.setPauseOnDebuggerStatements": Debugger.SetPauseOnDebuggerStatementsResponse; - "Debugger.setPauseOnExceptions": Debugger.SetPauseOnExceptionsResponse; - "Debugger.setPauseOnAssertions": Debugger.SetPauseOnAssertionsResponse; - "Debugger.setPauseOnMicrotasks": Debugger.SetPauseOnMicrotasksResponse; - "Debugger.setPauseForInternalScripts": Debugger.SetPauseForInternalScriptsResponse; - "Debugger.evaluateOnCallFrame": Debugger.EvaluateOnCallFrameResponse; - "Debugger.setShouldBlackboxURL": Debugger.SetShouldBlackboxURLResponse; - "Debugger.setBlackboxBreakpointEvaluations": Debugger.SetBlackboxBreakpointEvaluationsResponse; - "Heap.enable": Heap.EnableResponse; - "Heap.disable": Heap.DisableResponse; - "Heap.gc": Heap.GcResponse; - "Heap.snapshot": Heap.SnapshotResponse; - "Heap.startTracking": Heap.StartTrackingResponse; - "Heap.stopTracking": Heap.StopTrackingResponse; - "Heap.getPreview": Heap.GetPreviewResponse; - "Heap.getRemoteObject": Heap.GetRemoteObjectResponse; - "Network.enable": Network.EnableResponse; - "Network.disable": Network.DisableResponse; - "Network.setExtraHTTPHeaders": Network.SetExtraHTTPHeadersResponse; - "Network.getResponseBody": Network.GetResponseBodyResponse; - "Network.setResourceCachingDisabled": Network.SetResourceCachingDisabledResponse; - "Network.loadResource": Network.LoadResourceResponse; - "Network.getSerializedCertificate": Network.GetSerializedCertificateResponse; - "Network.resolveWebSocket": Network.ResolveWebSocketResponse; - "Network.setInterceptionEnabled": Network.SetInterceptionEnabledResponse; - "Network.addInterception": Network.AddInterceptionResponse; - "Network.removeInterception": Network.RemoveInterceptionResponse; - "Network.interceptContinue": Network.InterceptContinueResponse; - "Network.interceptWithRequest": Network.InterceptWithRequestResponse; - "Network.interceptWithResponse": Network.InterceptWithResponseResponse; - "Network.interceptRequestWithResponse": Network.InterceptRequestWithResponseResponse; - "Network.interceptRequestWithError": Network.InterceptRequestWithErrorResponse; - "Network.setEmulatedConditions": Network.SetEmulatedConditionsResponse; - "Runtime.parse": Runtime.ParseResponse; - "Runtime.evaluate": Runtime.EvaluateResponse; - "Runtime.awaitPromise": Runtime.AwaitPromiseResponse; - "Runtime.callFunctionOn": Runtime.CallFunctionOnResponse; - "Runtime.getPreview": Runtime.GetPreviewResponse; - "Runtime.getProperties": Runtime.GetPropertiesResponse; - "Runtime.getDisplayableProperties": Runtime.GetDisplayablePropertiesResponse; - "Runtime.getCollectionEntries": Runtime.GetCollectionEntriesResponse; - "Runtime.saveResult": Runtime.SaveResultResponse; - "Runtime.setSavedResultAlias": Runtime.SetSavedResultAliasResponse; - "Runtime.releaseObject": Runtime.ReleaseObjectResponse; - "Runtime.releaseObjectGroup": Runtime.ReleaseObjectGroupResponse; - "Runtime.enable": Runtime.EnableResponse; - "Runtime.disable": Runtime.DisableResponse; - "Runtime.getRuntimeTypesForVariablesAtOffsets": Runtime.GetRuntimeTypesForVariablesAtOffsetsResponse; - "Runtime.enableTypeProfiler": Runtime.EnableTypeProfilerResponse; - "Runtime.disableTypeProfiler": Runtime.DisableTypeProfilerResponse; - "Runtime.enableControlFlowProfiler": Runtime.EnableControlFlowProfilerResponse; - "Runtime.disableControlFlowProfiler": Runtime.DisableControlFlowProfilerResponse; - "Runtime.getBasicBlocks": Runtime.GetBasicBlocksResponse; - "ScriptProfiler.startTracking": ScriptProfiler.StartTrackingResponse; - "ScriptProfiler.stopTracking": ScriptProfiler.StopTrackingResponse; - }; - export type Event<T extends keyof EventMap = keyof EventMap> = { - method: T; - params: EventMap[T]; - }; - export type Request<T extends keyof RequestMap = keyof RequestMap> = { - id: number; - method: T; - params: RequestMap[T]; - }; - export type Response<T extends keyof ResponseMap = keyof ResponseMap> = { - id: number; - } & ( - | { - method?: T; - result: ResponseMap[T]; - } - | { - error: { - code?: string; - message: string; - }; - } - ); -} |