From 2c598532017ce56abbb253e52a3157747e4b8311 Mon Sep 17 00:00:00 2001 From: Francesco Novy Date: Tue, 20 Feb 2024 11:39:24 +0100 Subject: [PATCH 1/2] feat(node-experimental): Move integrations from node --- .../node-hapi-app/src/app.js | 2 +- .../tracing-experimental/hapi/scenario.js | 1 + packages/node-experimental/package.json | 1 - packages/node-experimental/src/index.ts | 21 +- .../src/integrations/anr/common.ts | 44 + .../src/integrations/anr/index.ts | 160 + .../src/integrations/anr/worker-script.ts | 2 + .../src/integrations/anr/worker.ts | 248 ++ .../src/integrations/console.ts | 36 + .../src/integrations/context.ts | 452 +++ .../src/integrations/contextlines.ts | 146 + .../integrations/local-variables/common.ts | 119 + .../src/integrations/local-variables/index.ts | 3 + .../local-variables/inspector.d.ts | 3387 +++++++++++++++++ .../local-variables/local-variables-async.ts | 267 ++ .../local-variables/local-variables-sync.ts | 409 ++ .../src/integrations/modules.ts | 96 + .../src/integrations/node-fetch.ts | 6 +- .../src/integrations/onuncaughtexception.ts | 171 + .../src/integrations/onunhandledrejection.ts | 95 + .../src/integrations/spotlight.ts | 116 + .../src/integrations/tracing/hapi.ts | 22 - .../src/integrations/tracing/hapi/index.ts | 76 + .../src/integrations/tracing/hapi/types.ts | 279 ++ packages/node-experimental/src/nodeVersion.ts | 7 + packages/node-experimental/src/sdk/init.ts | 34 +- .../src/utils/errorhandling.ts | 40 + ...ions.ts => getDefaultNodeClientOptions.ts} | 0 .../test/integrations/context.test.ts | 22 + .../test/integrations/contextlines.test.ts | 150 + .../test/integrations/localvariables.test.ts | 140 + .../test/integrations/spotlight.test.ts | 181 + .../node-experimental/test/sdk/client.test.ts | 2 +- .../test/sdk/handlers/errorHandler.test.ts | 2 +- packages/node-experimental/tsconfig.json | 2 +- 35 files changed, 6693 insertions(+), 46 deletions(-) create mode 100644 packages/node-experimental/src/integrations/anr/common.ts create mode 100644 packages/node-experimental/src/integrations/anr/index.ts create mode 100644 packages/node-experimental/src/integrations/anr/worker-script.ts create mode 100644 packages/node-experimental/src/integrations/anr/worker.ts create mode 100644 packages/node-experimental/src/integrations/console.ts create mode 100644 packages/node-experimental/src/integrations/context.ts create mode 100644 packages/node-experimental/src/integrations/contextlines.ts create mode 100644 packages/node-experimental/src/integrations/local-variables/common.ts create mode 100644 packages/node-experimental/src/integrations/local-variables/index.ts create mode 100644 packages/node-experimental/src/integrations/local-variables/inspector.d.ts create mode 100644 packages/node-experimental/src/integrations/local-variables/local-variables-async.ts create mode 100644 packages/node-experimental/src/integrations/local-variables/local-variables-sync.ts create mode 100644 packages/node-experimental/src/integrations/modules.ts create mode 100644 packages/node-experimental/src/integrations/onuncaughtexception.ts create mode 100644 packages/node-experimental/src/integrations/onunhandledrejection.ts create mode 100644 packages/node-experimental/src/integrations/spotlight.ts delete mode 100644 packages/node-experimental/src/integrations/tracing/hapi.ts create mode 100644 packages/node-experimental/src/integrations/tracing/hapi/index.ts create mode 100644 packages/node-experimental/src/integrations/tracing/hapi/types.ts create mode 100644 packages/node-experimental/src/nodeVersion.ts create mode 100644 packages/node-experimental/src/utils/errorhandling.ts rename packages/node-experimental/test/helpers/{getDefaultNodePreviewClientOptions.ts => getDefaultNodeClientOptions.ts} (100%) create mode 100644 packages/node-experimental/test/integrations/context.test.ts create mode 100644 packages/node-experimental/test/integrations/contextlines.test.ts create mode 100644 packages/node-experimental/test/integrations/localvariables.test.ts create mode 100644 packages/node-experimental/test/integrations/spotlight.test.ts diff --git a/dev-packages/e2e-tests/test-applications/node-hapi-app/src/app.js b/dev-packages/e2e-tests/test-applications/node-hapi-app/src/app.js index 4c71802c9be2..896479d3d338 100644 --- a/dev-packages/e2e-tests/test-applications/node-hapi-app/src/app.js +++ b/dev-packages/e2e-tests/test-applications/node-hapi-app/src/app.js @@ -10,7 +10,7 @@ Sentry.init({ environment: 'qa', // dynamic sampling bias to keep transactions dsn: process.env.E2E_TEST_DSN, includeLocalVariables: true, - integrations: [new Sentry.Integrations.Hapi({ server })], + integrations: [new Sentry.hapiIntegration({ server })], debug: true, tunnel: `http://localhost:3031/`, // proxy server tracesSampleRate: 1, diff --git a/dev-packages/node-integration-tests/suites/tracing-experimental/hapi/scenario.js b/dev-packages/node-integration-tests/suites/tracing-experimental/hapi/scenario.js index 8ec0015d744e..2c86ac704618 100644 --- a/dev-packages/node-integration-tests/suites/tracing-experimental/hapi/scenario.js +++ b/dev-packages/node-integration-tests/suites/tracing-experimental/hapi/scenario.js @@ -26,6 +26,7 @@ const init = async () => { }, }); + await Sentry.setupHapiErrorHandler(server); await server.start(); sendPortToRunner(port); diff --git a/packages/node-experimental/package.json b/packages/node-experimental/package.json index e3805a603faa..62c1072001cc 100644 --- a/packages/node-experimental/package.json +++ b/packages/node-experimental/package.json @@ -50,7 +50,6 @@ "@opentelemetry/semantic-conventions": "1.21.0", "@prisma/instrumentation": "5.9.0", "@sentry/core": "7.100.0", - "@sentry/node": "7.100.0", "@sentry/opentelemetry": "7.100.0", "@sentry/types": "7.100.0", "@sentry/utils": "7.100.0", diff --git a/packages/node-experimental/src/index.ts b/packages/node-experimental/src/index.ts index 5d30e3280ef1..ef9605afabe7 100644 --- a/packages/node-experimental/src/index.ts +++ b/packages/node-experimental/src/index.ts @@ -2,6 +2,15 @@ export { errorHandler } from './sdk/handlers/errorHandler'; export { httpIntegration } from './integrations/http'; export { nativeNodeFetchIntegration } from './integrations/node-fetch'; + +export { consoleIntegration } from './integrations/console'; +export { nodeContextIntegration } from './integrations/context'; +export { contextLinesIntegration } from './integrations/contextlines'; +export { localVariablesIntegration } from './integrations/local-variables'; +export { modulesIntegration } from './integrations/modules'; +export { onUncaughtExceptionIntegration } from './integrations/onuncaughtexception'; +export { onUnhandledRejectionIntegration } from './integrations/onunhandledrejection'; + export { expressIntegration } from './integrations/tracing/express'; export { fastifyIntegration } from './integrations/tracing/fastify'; export { graphqlIntegration } from './integrations/tracing/graphql'; @@ -12,6 +21,7 @@ export { mysql2Integration } from './integrations/tracing/mysql2'; export { nestIntegration } from './integrations/tracing/nest'; export { postgresIntegration } from './integrations/tracing/postgres'; export { prismaIntegration } from './integrations/tracing/prisma'; +export { hapiIntegration, setupHapiErrorHandler } from './integrations/tracing/hapi'; export { init, getDefaultIntegrations } from './sdk/init'; export { getAutoPerformanceIntegrations } from './integrations/tracing'; @@ -28,17 +38,6 @@ export { startSpan, startSpanManual, startInactiveSpan, getActiveSpan, withActiv export { addRequestDataToEvent, DEFAULT_USER_INCLUDES, extractRequestData } from '@sentry/utils'; -export { - hapiErrorPlugin, - consoleIntegration, - onUncaughtExceptionIntegration, - onUnhandledRejectionIntegration, - modulesIntegration, - contextLinesIntegration, - nodeContextIntegration, - localVariablesIntegration, -} from '@sentry/node'; - export { addBreadcrumb, isInitialized, diff --git a/packages/node-experimental/src/integrations/anr/common.ts b/packages/node-experimental/src/integrations/anr/common.ts new file mode 100644 index 000000000000..5617871ccb24 --- /dev/null +++ b/packages/node-experimental/src/integrations/anr/common.ts @@ -0,0 +1,44 @@ +import type { Contexts, DsnComponents, Primitive, SdkMetadata } from '@sentry/types'; + +export interface AnrIntegrationOptions { + /** + * Interval to send heartbeat messages to the ANR worker. + * + * Defaults to 50ms. + */ + pollInterval: number; + /** + * Threshold in milliseconds to trigger an ANR event. + * + * Defaults to 5000ms. + */ + anrThreshold: number; + /** + * Whether to capture a stack trace when the ANR event is triggered. + * + * Defaults to `false`. + * + * This uses the node debugger which enables the inspector API and opens the required ports. + */ + captureStackTrace: boolean; + /** + * Tags to include with ANR events. + */ + staticTags: { [key: string]: Primitive }; + /** + * @ignore Internal use only. + * + * If this is supplied, stack frame filenames will be rewritten to be relative to this path. + */ + appRootPath: string | undefined; +} + +export interface WorkerStartData extends AnrIntegrationOptions { + debug: boolean; + sdkMetadata: SdkMetadata; + dsn: DsnComponents; + release: string | undefined; + environment: string; + dist: string | undefined; + contexts: Contexts; +} diff --git a/packages/node-experimental/src/integrations/anr/index.ts b/packages/node-experimental/src/integrations/anr/index.ts new file mode 100644 index 000000000000..30ff52011d31 --- /dev/null +++ b/packages/node-experimental/src/integrations/anr/index.ts @@ -0,0 +1,160 @@ +import { URL } from 'url'; +import { defineIntegration, getCurrentScope } from '@sentry/core'; +import type { Contexts, Event, EventHint, IntegrationFn } from '@sentry/types'; +import { dynamicRequire, logger } from '@sentry/utils'; +import type { Worker, WorkerOptions } from 'worker_threads'; +import { NODE_MAJOR, NODE_VERSION } from '../../nodeVersion'; +import type { NodeClient } from '../../sdk/client'; +import type { AnrIntegrationOptions, WorkerStartData } from './common'; +import { base64WorkerScript } from './worker-script'; + +const DEFAULT_INTERVAL = 50; +const DEFAULT_HANG_THRESHOLD = 5000; + +type WorkerNodeV14 = Worker & { new (filename: string | URL, options?: WorkerOptions): Worker }; + +type WorkerThreads = { + Worker: WorkerNodeV14; +}; + +function log(message: string, ...args: unknown[]): void { + logger.log(`[ANR] ${message}`, ...args); +} + +/** + * We need to use dynamicRequire because worker_threads is not available in node < v12 and webpack error will when + * targeting those versions + */ +function getWorkerThreads(): WorkerThreads { + return dynamicRequire(module, 'worker_threads'); +} + +/** + * Gets contexts by calling all event processors. This relies on being called after all integrations are setup + */ +async function getContexts(client: NodeClient): Promise { + let event: Event | null = { message: 'ANR' }; + const eventHint: EventHint = {}; + + for (const processor of client.getEventProcessors()) { + if (event === null) break; + event = await processor(event, eventHint); + } + + return event?.contexts || {}; +} + +interface InspectorApi { + open: (port: number) => void; + url: () => string | undefined; +} + +const INTEGRATION_NAME = 'Anr'; + +const _anrIntegration = ((options: Partial = {}) => { + return { + name: INTEGRATION_NAME, + setup(client: NodeClient) { + if (NODE_MAJOR < 16 || (NODE_MAJOR === 16 && (NODE_VERSION.minor || 0) < 17)) { + throw new Error('ANR detection requires Node 16.17.0 or later'); + } + + // setImmediate is used to ensure that all other integrations have been setup + setImmediate(() => _startWorker(client, options)); + }, + }; +}) satisfies IntegrationFn; + +export const anrIntegration = defineIntegration(_anrIntegration); + +/** + * Starts the ANR worker thread + */ +async function _startWorker(client: NodeClient, _options: Partial): Promise { + const contexts = await getContexts(client); + const dsn = client.getDsn(); + + if (!dsn) { + return; + } + + // These will not be accurate if sent later from the worker thread + delete contexts.app?.app_memory; + delete contexts.device?.free_memory; + + const initOptions = client.getOptions(); + + const sdkMetadata = client.getSdkMetadata() || {}; + if (sdkMetadata.sdk) { + sdkMetadata.sdk.integrations = initOptions.integrations.map(i => i.name); + } + + const options: WorkerStartData = { + debug: logger.isEnabled(), + dsn, + environment: initOptions.environment || 'production', + release: initOptions.release, + dist: initOptions.dist, + sdkMetadata, + appRootPath: _options.appRootPath, + pollInterval: _options.pollInterval || DEFAULT_INTERVAL, + anrThreshold: _options.anrThreshold || DEFAULT_HANG_THRESHOLD, + captureStackTrace: !!_options.captureStackTrace, + staticTags: _options.staticTags || {}, + contexts, + }; + + if (options.captureStackTrace) { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const inspector: InspectorApi = require('inspector'); + if (!inspector.url()) { + inspector.open(0); + } + } + + const { Worker } = getWorkerThreads(); + + const worker = new Worker(new URL(`data:application/javascript;base64,${base64WorkerScript}`), { + workerData: options, + }); + + process.on('exit', () => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + worker.terminate(); + }); + + const timer = setInterval(() => { + try { + const currentSession = getCurrentScope().getSession(); + // We need to copy the session object and remove the toJSON method so it can be sent to the worker + // serialized without making it a SerializedSession + const session = currentSession ? { ...currentSession, toJSON: undefined } : undefined; + // message the worker to tell it the main event loop is still running + worker.postMessage({ session }); + } catch (_) { + // + } + }, options.pollInterval); + // Timer should not block exit + timer.unref(); + + worker.on('message', (msg: string) => { + if (msg === 'session-ended') { + log('ANR event sent from ANR worker. Clearing session in this thread.'); + getCurrentScope().setSession(undefined); + } + }); + + worker.once('error', (err: Error) => { + clearInterval(timer); + log('ANR worker error', err); + }); + + worker.once('exit', (code: number) => { + clearInterval(timer); + log('ANR worker exit', code); + }); + + // Ensure this thread can't block app exit + worker.unref(); +} diff --git a/packages/node-experimental/src/integrations/anr/worker-script.ts b/packages/node-experimental/src/integrations/anr/worker-script.ts new file mode 100644 index 000000000000..16394eaacfe1 --- /dev/null +++ b/packages/node-experimental/src/integrations/anr/worker-script.ts @@ -0,0 +1,2 @@ +// This file is a placeholder that gets overwritten in the build directory. +export const base64WorkerScript = ''; diff --git a/packages/node-experimental/src/integrations/anr/worker.ts b/packages/node-experimental/src/integrations/anr/worker.ts new file mode 100644 index 000000000000..8bc6e1455cfb --- /dev/null +++ b/packages/node-experimental/src/integrations/anr/worker.ts @@ -0,0 +1,248 @@ +import { + createEventEnvelope, + createSessionEnvelope, + getEnvelopeEndpointWithUrlEncodedAuth, + makeSession, + updateSession, +} from '@sentry/core'; +import type { Event, Session, StackFrame, TraceContext } from '@sentry/types'; +import { + callFrameToStackFrame, + normalizeUrlToBase, + stripSentryFramesAndReverse, + uuid4, + watchdogTimer, +} from '@sentry/utils'; +import { Session as InspectorSession } from 'inspector'; +import { parentPort, workerData } from 'worker_threads'; + +import { makeNodeTransport } from '../../transports'; +import { createGetModuleFromFilename } from '../../utils/module'; +import type { WorkerStartData } from './common'; + +type VoidFunction = () => void; +type InspectorSessionNodeV12 = InspectorSession & { connectToMainThread: VoidFunction }; + +const options: WorkerStartData = workerData; +let session: Session | undefined; +let hasSentAnrEvent = false; + +function log(msg: string): void { + if (options.debug) { + // eslint-disable-next-line no-console + console.log(`[ANR Worker] ${msg}`); + } +} + +const url = getEnvelopeEndpointWithUrlEncodedAuth(options.dsn); +const transport = makeNodeTransport({ + url, + recordDroppedEvent: () => { + // + }, +}); + +async function sendAbnormalSession(): Promise { + // of we have an existing session passed from the main thread, send it as abnormal + if (session) { + log('Sending abnormal session'); + updateSession(session, { status: 'abnormal', abnormal_mechanism: 'anr_foreground' }); + + const envelope = createSessionEnvelope(session, options.dsn, options.sdkMetadata); + // Log the envelope so to aid in testing + log(JSON.stringify(envelope)); + + await transport.send(envelope); + + try { + // Notify the main process that the session has ended so the session can be cleared from the scope + parentPort?.postMessage('session-ended'); + } catch (_) { + // ignore + } + } +} + +log('Started'); + +function prepareStackFrames(stackFrames: StackFrame[] | undefined): StackFrame[] | undefined { + if (!stackFrames) { + return undefined; + } + + // Strip Sentry frames and reverse the stack frames so they are in the correct order + const strippedFrames = stripSentryFramesAndReverse(stackFrames); + + // If we have an app root path, rewrite the filenames to be relative to the app root + if (options.appRootPath) { + for (const frame of strippedFrames) { + if (!frame.filename) { + continue; + } + + frame.filename = normalizeUrlToBase(frame.filename, options.appRootPath); + } + } + + return strippedFrames; +} + +async function sendAnrEvent(frames?: StackFrame[], traceContext?: TraceContext): Promise { + if (hasSentAnrEvent) { + return; + } + + hasSentAnrEvent = true; + + await sendAbnormalSession(); + + log('Sending event'); + + const event: Event = { + event_id: uuid4(), + contexts: { ...options.contexts, trace: traceContext }, + release: options.release, + environment: options.environment, + dist: options.dist, + platform: 'node', + level: 'error', + exception: { + values: [ + { + type: 'ApplicationNotResponding', + value: `Application Not Responding for at least ${options.anrThreshold} ms`, + stacktrace: { frames: prepareStackFrames(frames) }, + // This ensures the UI doesn't say 'Crashed in' for the stack trace + mechanism: { type: 'ANR' }, + }, + ], + }, + tags: options.staticTags, + }; + + const envelope = createEventEnvelope(event, options.dsn, options.sdkMetadata); + // Log the envelope so to aid in testing + log(JSON.stringify(envelope)); + + await transport.send(envelope); + await transport.flush(2000); + + // Delay for 5 seconds so that stdio can flush in the main event loop ever restarts. + // This is mainly for the benefit of logging/debugging issues. + setTimeout(() => { + process.exit(0); + }, 5_000); +} + +let debuggerPause: VoidFunction | undefined; + +if (options.captureStackTrace) { + log('Connecting to debugger'); + + const session = new InspectorSession() as InspectorSessionNodeV12; + session.connectToMainThread(); + + log('Connected to debugger'); + + // Collect scriptId -> url map so we can look up the filenames later + const scripts = new Map(); + + session.on('Debugger.scriptParsed', event => { + scripts.set(event.params.scriptId, event.params.url); + }); + + session.on('Debugger.paused', event => { + if (event.params.reason !== 'other') { + return; + } + + try { + log('Debugger paused'); + + // copy the frames + const callFrames = [...event.params.callFrames]; + + const getModuleName = options.appRootPath ? createGetModuleFromFilename(options.appRootPath) : () => undefined; + const stackFrames = callFrames.map(frame => + callFrameToStackFrame(frame, scripts.get(frame.location.scriptId), getModuleName), + ); + + // Evaluate a script in the currently paused context + session.post( + 'Runtime.evaluate', + { + // Grab the trace context from the current scope + expression: + 'const ctx = __SENTRY__.acs?.getCurrentScope().getPropagationContext() || {}; ctx.traceId + "-" + ctx.spanId + "-" + ctx.parentSpanId', + // Don't re-trigger the debugger if this causes an error + silent: true, + }, + (_, param) => { + const traceId = param && param.result ? (param.result.value as string) : '--'; + const [trace_id, span_id, parent_span_id] = traceId.split('-') as (string | undefined)[]; + + session.post('Debugger.resume'); + session.post('Debugger.disable'); + + const context = trace_id?.length && span_id?.length ? { trace_id, span_id, parent_span_id } : undefined; + sendAnrEvent(stackFrames, context).then(null, () => { + log('Sending ANR event failed.'); + }); + }, + ); + } catch (e) { + session.post('Debugger.resume'); + session.post('Debugger.disable'); + throw e; + } + }); + + debuggerPause = () => { + try { + session.post('Debugger.enable', () => { + session.post('Debugger.pause'); + }); + } catch (_) { + // + } + }; +} + +function createHrTimer(): { getTimeMs: () => number; reset: VoidFunction } { + // TODO (v8): We can use process.hrtime.bigint() after we drop node v8 + let lastPoll = process.hrtime(); + + return { + getTimeMs: (): number => { + const [seconds, nanoSeconds] = process.hrtime(lastPoll); + return Math.floor(seconds * 1e3 + nanoSeconds / 1e6); + }, + reset: (): void => { + lastPoll = process.hrtime(); + }, + }; +} + +function watchdogTimeout(): void { + log('Watchdog timeout'); + + if (debuggerPause) { + log('Pausing debugger to capture stack trace'); + debuggerPause(); + } else { + log('Capturing event without a stack trace'); + sendAnrEvent().then(null, () => { + log('Sending ANR event failed on watchdog timeout.'); + }); + } +} + +const { poll } = watchdogTimer(createHrTimer, options.pollInterval, options.anrThreshold, watchdogTimeout); + +parentPort?.on('message', (msg: { session: Session | undefined }) => { + if (msg.session) { + session = makeSession(msg.session); + } + + poll(); +}); diff --git a/packages/node-experimental/src/integrations/console.ts b/packages/node-experimental/src/integrations/console.ts new file mode 100644 index 000000000000..0b3d27fe8510 --- /dev/null +++ b/packages/node-experimental/src/integrations/console.ts @@ -0,0 +1,36 @@ +import * as util from 'util'; +import { addBreadcrumb, defineIntegration, getClient } from '@sentry/core'; +import type { IntegrationFn } from '@sentry/types'; +import { addConsoleInstrumentationHandler, severityLevelFromString } from '@sentry/utils'; + +const INTEGRATION_NAME = 'Console'; + +const _consoleIntegration = (() => { + return { + name: INTEGRATION_NAME, + setup(client) { + addConsoleInstrumentationHandler(({ args, level }) => { + if (getClient() !== client) { + return; + } + + addBreadcrumb( + { + category: 'console', + level: severityLevelFromString(level), + message: util.format.apply(undefined, args), + }, + { + input: [...args], + level, + }, + ); + }); + }, + }; +}) satisfies IntegrationFn; + +/** + * Capture console logs as breadcrumbs. + */ +export const consoleIntegration = defineIntegration(_consoleIntegration); diff --git a/packages/node-experimental/src/integrations/context.ts b/packages/node-experimental/src/integrations/context.ts new file mode 100644 index 000000000000..c33d97e79044 --- /dev/null +++ b/packages/node-experimental/src/integrations/context.ts @@ -0,0 +1,452 @@ +import { execFile } from 'child_process'; +import { readFile, readdir } from 'fs'; +import * as os from 'os'; +import { join } from 'path'; +import { promisify } from 'util'; +import { defineIntegration } from '@sentry/core'; +import type { + AppContext, + CloudResourceContext, + Contexts, + CultureContext, + DeviceContext, + Event, + IntegrationFn, + OsContext, +} from '@sentry/types'; + +export const readFileAsync = promisify(readFile); +export const readDirAsync = promisify(readdir); + +const INTEGRATION_NAME = 'Context'; + +interface DeviceContextOptions { + cpu?: boolean; + memory?: boolean; +} + +interface ContextOptions { + app?: boolean; + os?: boolean; + device?: DeviceContextOptions | boolean; + culture?: boolean; + cloudResource?: boolean; +} + +const _nodeContextIntegration = ((options: ContextOptions = {}) => { + let cachedContext: Promise | undefined; + + const _options = { + app: true, + os: true, + device: true, + culture: true, + cloudResource: true, + ...options, + }; + + /** Add contexts to the event. Caches the context so we only look it up once. */ + async function addContext(event: Event): Promise { + if (cachedContext === undefined) { + cachedContext = _getContexts(); + } + + const updatedContext = _updateContext(await cachedContext); + + event.contexts = { + ...event.contexts, + app: { ...updatedContext.app, ...event.contexts?.app }, + os: { ...updatedContext.os, ...event.contexts?.os }, + device: { ...updatedContext.device, ...event.contexts?.device }, + culture: { ...updatedContext.culture, ...event.contexts?.culture }, + cloud_resource: { ...updatedContext.cloud_resource, ...event.contexts?.cloud_resource }, + }; + + return event; + } + + /** Get the contexts from node. */ + async function _getContexts(): Promise { + const contexts: Contexts = {}; + + if (_options.os) { + contexts.os = await getOsContext(); + } + + if (_options.app) { + contexts.app = getAppContext(); + } + + if (_options.device) { + contexts.device = getDeviceContext(_options.device); + } + + if (_options.culture) { + const culture = getCultureContext(); + + if (culture) { + contexts.culture = culture; + } + } + + if (_options.cloudResource) { + contexts.cloud_resource = getCloudResourceContext(); + } + + return contexts; + } + + return { + name: INTEGRATION_NAME, + processEvent(event) { + return addContext(event); + }, + }; +}) satisfies IntegrationFn; + +/** + * Capture context about the environment and the device that the client is running on, to events. + */ +export const nodeContextIntegration = defineIntegration(_nodeContextIntegration); + +/** + * Updates the context with dynamic values that can change + */ +function _updateContext(contexts: Contexts): Contexts { + // Only update properties if they exist + if (contexts?.app?.app_memory) { + contexts.app.app_memory = process.memoryUsage().rss; + } + + if (contexts?.device?.free_memory) { + contexts.device.free_memory = os.freemem(); + } + + return contexts; +} + +/** + * Returns the operating system context. + * + * Based on the current platform, this uses a different strategy to provide the + * most accurate OS information. Since this might involve spawning subprocesses + * or accessing the file system, this should only be executed lazily and cached. + * + * - On macOS (Darwin), this will execute the `sw_vers` utility. The context + * has a `name`, `version`, `build` and `kernel_version` set. + * - On Linux, this will try to load a distribution release from `/etc` and set + * the `name`, `version` and `kernel_version` fields. + * - On all other platforms, only a `name` and `version` will be returned. Note + * that `version` might actually be the kernel version. + */ +async function getOsContext(): Promise { + const platformId = os.platform(); + switch (platformId) { + case 'darwin': + return getDarwinInfo(); + case 'linux': + return getLinuxInfo(); + default: + return { + name: PLATFORM_NAMES[platformId] || platformId, + version: os.release(), + }; + } +} + +function getCultureContext(): CultureContext | undefined { + try { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + if (typeof (process.versions as unknown as any).icu !== 'string') { + // Node was built without ICU support + return; + } + + // Check that node was built with full Intl support. Its possible it was built without support for non-English + // locales which will make resolvedOptions inaccurate + // + // https://nodejs.org/api/intl.html#detecting-internationalization-support + const january = new Date(9e8); + const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); + if (spanish.format(january) === 'enero') { + const options = Intl.DateTimeFormat().resolvedOptions(); + + return { + locale: options.locale, + timezone: options.timeZone, + }; + } + } catch (err) { + // + } + + return; +} + +function getAppContext(): AppContext { + const app_memory = process.memoryUsage().rss; + const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString(); + + return { app_start_time, app_memory }; +} + +/** + * Gets device information from os + */ +export function getDeviceContext(deviceOpt: DeviceContextOptions | true): DeviceContext { + const device: DeviceContext = {}; + + // Sometimes os.uptime() throws due to lacking permissions: https://github.com/getsentry/sentry-javascript/issues/8202 + let uptime; + try { + uptime = os.uptime && os.uptime(); + } catch (e) { + // noop + } + + // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions). + // Hence, we only set boot time, if we get a valid uptime value. + // @see https://github.com/getsentry/sentry-javascript/issues/5856 + if (typeof uptime === 'number') { + device.boot_time = new Date(Date.now() - uptime * 1000).toISOString(); + } + + device.arch = os.arch(); + + if (deviceOpt === true || deviceOpt.memory) { + device.memory_size = os.totalmem(); + device.free_memory = os.freemem(); + } + + if (deviceOpt === true || deviceOpt.cpu) { + const cpuInfo: os.CpuInfo[] | undefined = os.cpus(); + if (cpuInfo && cpuInfo.length) { + const firstCpu = cpuInfo[0]; + + device.processor_count = cpuInfo.length; + device.cpu_description = firstCpu.model; + device.processor_frequency = firstCpu.speed; + } + } + + return device; +} + +/** Mapping of Node's platform names to actual OS names. */ +const PLATFORM_NAMES: { [platform: string]: string } = { + aix: 'IBM AIX', + freebsd: 'FreeBSD', + openbsd: 'OpenBSD', + sunos: 'SunOS', + win32: 'Windows', +}; + +/** Linux version file to check for a distribution. */ +interface DistroFile { + /** The file name, located in `/etc`. */ + name: string; + /** Potential distributions to check. */ + distros: string[]; +} + +/** Mapping of linux release files located in /etc to distributions. */ +const LINUX_DISTROS: DistroFile[] = [ + { name: 'fedora-release', distros: ['Fedora'] }, + { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] }, + { name: 'redhat_version', distros: ['Red Hat Linux'] }, + { name: 'SuSE-release', distros: ['SUSE Linux'] }, + { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] }, + { name: 'debian_version', distros: ['Debian'] }, + { name: 'debian_release', distros: ['Debian'] }, + { name: 'arch-release', distros: ['Arch Linux'] }, + { name: 'gentoo-release', distros: ['Gentoo Linux'] }, + { name: 'novell-release', distros: ['SUSE Linux'] }, + { name: 'alpine-release', distros: ['Alpine Linux'] }, +]; + +/** Functions to extract the OS version from Linux release files. */ +const LINUX_VERSIONS: { + [identifier: string]: (content: string) => string | undefined; +} = { + alpine: content => content, + arch: content => matchFirst(/distrib_release=(.*)/, content), + centos: content => matchFirst(/release ([^ ]+)/, content), + debian: content => content, + fedora: content => matchFirst(/release (..)/, content), + mint: content => matchFirst(/distrib_release=(.*)/, content), + red: content => matchFirst(/release ([^ ]+)/, content), + suse: content => matchFirst(/VERSION = (.*)\n/, content), + ubuntu: content => matchFirst(/distrib_release=(.*)/, content), +}; + +/** + * Executes a regular expression with one capture group. + * + * @param regex A regular expression to execute. + * @param text Content to execute the RegEx on. + * @returns The captured string if matched; otherwise undefined. + */ +function matchFirst(regex: RegExp, text: string): string | undefined { + const match = regex.exec(text); + return match ? match[1] : undefined; +} + +/** Loads the macOS operating system context. */ +async function getDarwinInfo(): Promise { + // Default values that will be used in case no operating system information + // can be loaded. The default version is computed via heuristics from the + // kernel version, but the build ID is missing. + const darwinInfo: OsContext = { + kernel_version: os.release(), + name: 'Mac OS X', + version: `10.${Number(os.release().split('.')[0]) - 4}`, + }; + + try { + // We try to load the actual macOS version by executing the `sw_vers` tool. + // This tool should be available on every standard macOS installation. In + // case this fails, we stick with the values computed above. + + const output = await new Promise((resolve, reject) => { + execFile('/usr/bin/sw_vers', (error: Error | null, stdout: string) => { + if (error) { + reject(error); + return; + } + resolve(stdout); + }); + }); + + darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output); + darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output); + darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output); + } catch (e) { + // ignore + } + + return darwinInfo; +} + +/** Returns a distribution identifier to look up version callbacks. */ +function getLinuxDistroId(name: string): string { + return name.split(' ')[0].toLowerCase(); +} + +/** Loads the Linux operating system context. */ +async function getLinuxInfo(): Promise { + // By default, we cannot assume anything about the distribution or Linux + // version. `os.release()` returns the kernel version and we assume a generic + // "Linux" name, which will be replaced down below. + const linuxInfo: OsContext = { + kernel_version: os.release(), + name: 'Linux', + }; + + try { + // We start guessing the distribution by listing files in the /etc + // directory. This is were most Linux distributions (except Knoppix) store + // release files with certain distribution-dependent meta data. We search + // for exactly one known file defined in `LINUX_DISTROS` and exit if none + // are found. In case there are more than one file, we just stick with the + // first one. + const etcFiles = await readDirAsync('/etc'); + const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name)); + if (!distroFile) { + return linuxInfo; + } + + // Once that file is known, load its contents. To make searching in those + // files easier, we lowercase the file contents. Since these files are + // usually quite small, this should not allocate too much memory and we only + // hold on to it for a very short amount of time. + const distroPath = join('/etc', distroFile.name); + const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) as string).toLowerCase(); + + // Some Linux distributions store their release information in the same file + // (e.g. RHEL and Centos). In those cases, we scan the file for an + // identifier, that basically consists of the first word of the linux + // distribution name (e.g. "red" for Red Hat). In case there is no match, we + // just assume the first distribution in our list. + const { distros } = distroFile; + linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0]; + + // Based on the found distribution, we can now compute the actual version + // number. This is different for every distribution, so several strategies + // are computed in `LINUX_VERSIONS`. + const id = getLinuxDistroId(linuxInfo.name); + linuxInfo.version = LINUX_VERSIONS[id](contents); + } catch (e) { + // ignore + } + + return linuxInfo; +} + +/** + * Grabs some information about hosting provider based on best effort. + */ +function getCloudResourceContext(): CloudResourceContext | undefined { + if (process.env.VERCEL) { + // https://vercel.com/docs/concepts/projects/environment-variables/system-environment-variables#system-environment-variables + return { + 'cloud.provider': 'vercel', + 'cloud.region': process.env.VERCEL_REGION, + }; + } else if (process.env.AWS_REGION) { + // https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html + return { + 'cloud.provider': 'aws', + 'cloud.region': process.env.AWS_REGION, + 'cloud.platform': process.env.AWS_EXECUTION_ENV, + }; + } else if (process.env.GCP_PROJECT) { + // https://cloud.google.com/composer/docs/how-to/managing/environment-variables#reserved_variables + return { + 'cloud.provider': 'gcp', + }; + } else if (process.env.ALIYUN_REGION_ID) { + // TODO: find where I found these environment variables - at least gc.github.com returns something + return { + 'cloud.provider': 'alibaba_cloud', + 'cloud.region': process.env.ALIYUN_REGION_ID, + }; + } else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) { + // https://learn.microsoft.com/en-us/azure/app-service/reference-app-settings?tabs=kudu%2Cdotnet#app-environment + return { + 'cloud.provider': 'azure', + 'cloud.region': process.env.REGION_NAME, + }; + } else if (process.env.IBM_CLOUD_REGION) { + // TODO: find where I found these environment variables - at least gc.github.com returns something + return { + 'cloud.provider': 'ibm_cloud', + 'cloud.region': process.env.IBM_CLOUD_REGION, + }; + } else if (process.env.TENCENTCLOUD_REGION) { + // https://www.tencentcloud.com/document/product/583/32748 + return { + 'cloud.provider': 'tencent_cloud', + 'cloud.region': process.env.TENCENTCLOUD_REGION, + 'cloud.account.id': process.env.TENCENTCLOUD_APPID, + 'cloud.availability_zone': process.env.TENCENTCLOUD_ZONE, + }; + } else if (process.env.NETLIFY) { + // https://docs.netlify.com/configure-builds/environment-variables/#read-only-variables + return { + 'cloud.provider': 'netlify', + }; + } else if (process.env.FLY_REGION) { + // https://fly.io/docs/reference/runtime-environment/ + return { + 'cloud.provider': 'fly.io', + 'cloud.region': process.env.FLY_REGION, + }; + } else if (process.env.DYNO) { + // https://devcenter.heroku.com/articles/dynos#local-environment-variables + return { + 'cloud.provider': 'heroku', + }; + } else { + return undefined; + } +} diff --git a/packages/node-experimental/src/integrations/contextlines.ts b/packages/node-experimental/src/integrations/contextlines.ts new file mode 100644 index 000000000000..3755e164e5ea --- /dev/null +++ b/packages/node-experimental/src/integrations/contextlines.ts @@ -0,0 +1,146 @@ +import { promises } from 'fs'; +import { defineIntegration } from '@sentry/core'; +import type { Event, IntegrationFn, StackFrame } from '@sentry/types'; +import { LRUMap, addContextToFrame } from '@sentry/utils'; + +const FILE_CONTENT_CACHE = new LRUMap(100); +const DEFAULT_LINES_OF_CONTEXT = 7; +const INTEGRATION_NAME = 'ContextLines'; + +const readFileAsync = promises.readFile; + +/** + * Resets the file cache. Exists for testing purposes. + * @hidden + */ +export function resetFileContentCache(): void { + FILE_CONTENT_CACHE.clear(); +} + +interface ContextLinesOptions { + /** + * Sets the number of context lines for each frame when loading a file. + * Defaults to 7. + * + * Set to 0 to disable loading and inclusion of source files. + **/ + frameContextLines?: number; +} + +/** Exported only for tests, as a type-safe variant. */ +export const _contextLinesIntegration = ((options: ContextLinesOptions = {}) => { + const contextLines = options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; + + return { + name: INTEGRATION_NAME, + processEvent(event) { + return addSourceContext(event, contextLines); + }, + }; +}) satisfies IntegrationFn; + +/** + * Capture the lines before and after the frame's context. + */ +export const contextLinesIntegration = defineIntegration(_contextLinesIntegration); + +async function addSourceContext(event: Event, contextLines: number): Promise { + // keep a lookup map of which files we've already enqueued to read, + // so we don't enqueue the same file multiple times which would cause multiple i/o reads + const enqueuedReadSourceFileTasks: Record = {}; + const readSourceFileTasks: Promise[] = []; + + if (contextLines > 0 && event.exception?.values) { + for (const exception of event.exception.values) { + if (!exception.stacktrace?.frames) { + continue; + } + + // We want to iterate in reverse order as calling cache.get will bump the file in our LRU cache. + // This ends up prioritizes source context for frames at the top of the stack instead of the bottom. + for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) { + const frame = exception.stacktrace.frames[i]; + // Call cache.get to bump the file to the top of the cache and ensure we have not already + // enqueued a read operation for this filename + if (frame.filename && !enqueuedReadSourceFileTasks[frame.filename] && !FILE_CONTENT_CACHE.get(frame.filename)) { + readSourceFileTasks.push(_readSourceFile(frame.filename)); + enqueuedReadSourceFileTasks[frame.filename] = 1; + } + } + } + } + + // check if files to read > 0, if so, await all of them to be read before adding source contexts. + // Normally, Promise.all here could be short circuited if one of the promises rejects, but we + // are guarding from that by wrapping the i/o read operation in a try/catch. + if (readSourceFileTasks.length > 0) { + await Promise.all(readSourceFileTasks); + } + + // Perform the same loop as above, but this time we can assume all files are in the cache + // and attempt to add source context to frames. + if (contextLines > 0 && event.exception?.values) { + for (const exception of event.exception.values) { + if (exception.stacktrace && exception.stacktrace.frames) { + await addSourceContextToFrames(exception.stacktrace.frames, contextLines); + } + } + } + + return event; +} + +/** Adds context lines to frames */ +function addSourceContextToFrames(frames: StackFrame[], contextLines: number): void { + for (const frame of frames) { + // Only add context if we have a filename and it hasn't already been added + if (frame.filename && frame.context_line === undefined) { + const sourceFileLines = FILE_CONTENT_CACHE.get(frame.filename); + + if (sourceFileLines) { + try { + addContextToFrame(sourceFileLines, frame, contextLines); + } catch (e) { + // anomaly, being defensive in case + // unlikely to ever happen in practice but can definitely happen in theory + } + } + } + } +} + +/** + * Reads file contents and caches them in a global LRU cache. + * If reading fails, mark the file as null in the cache so we don't try again. + * + * @param filename filepath to read content from. + */ +async function _readSourceFile(filename: string): Promise { + const cachedFile = FILE_CONTENT_CACHE.get(filename); + + // We have already attempted to read this file and failed, do not try again + if (cachedFile === null) { + return null; + } + + // We have a cache hit, return it + if (cachedFile !== undefined) { + return cachedFile; + } + + // Guard from throwing if readFile fails, this enables us to use Promise.all and + // not have it short circuiting if one of the promises rejects + since context lines are added + // on a best effort basis, we want to throw here anyways. + + // If we made it to here, it means that our file is not cache nor marked as failed, so attempt to read it + let content: string[] | null = null; + try { + const rawFileContents = await readFileAsync(filename, 'utf-8'); + content = rawFileContents.split('\n'); + } catch (_) { + // if we fail, we will mark the file as null in the cache and short circuit next time we try to read it + } + + FILE_CONTENT_CACHE.set(filename, content); + return content; +} diff --git a/packages/node-experimental/src/integrations/local-variables/common.ts b/packages/node-experimental/src/integrations/local-variables/common.ts new file mode 100644 index 000000000000..3ffee8c0a824 --- /dev/null +++ b/packages/node-experimental/src/integrations/local-variables/common.ts @@ -0,0 +1,119 @@ +import type { StackFrame, StackParser } from '@sentry/types'; +import type { Debugger } from 'inspector'; + +export type Variables = Record; + +export type RateLimitIncrement = () => void; + +/** + * Creates a rate limiter that will call the disable callback when the rate limit is reached and the enable callback + * when a timeout has occurred. + * @param maxPerSecond Maximum number of calls per second + * @param enable Callback to enable capture + * @param disable Callback to disable capture + * @returns A function to call to increment the rate limiter count + */ +export function createRateLimiter( + maxPerSecond: number, + enable: () => void, + disable: (seconds: number) => void, +): RateLimitIncrement { + let count = 0; + let retrySeconds = 5; + let disabledTimeout = 0; + + setInterval(() => { + if (disabledTimeout === 0) { + if (count > maxPerSecond) { + retrySeconds *= 2; + disable(retrySeconds); + + // Cap at one day + if (retrySeconds > 86400) { + retrySeconds = 86400; + } + disabledTimeout = retrySeconds; + } + } else { + disabledTimeout -= 1; + + if (disabledTimeout === 0) { + enable(); + } + } + + count = 0; + }, 1_000).unref(); + + return () => { + count += 1; + }; +} + +// Add types for the exception event data +export type PausedExceptionEvent = Debugger.PausedEventDataType & { + data: { + // This contains error.stack + description: string; + }; +}; + +/** Could this be an anonymous function? */ +export function isAnonymous(name: string | undefined): boolean { + return name !== undefined && (name.length === 0 || name === '?' || name === ''); +} + +/** Do the function names appear to match? */ +export function functionNamesMatch(a: string | undefined, b: string | undefined): boolean { + return a === b || (isAnonymous(a) && isAnonymous(b)); +} + +/** Creates a unique hash from stack frames */ +export function hashFrames(frames: StackFrame[] | undefined): string | undefined { + if (frames === undefined) { + return; + } + + // Only hash the 10 most recent frames (ie. the last 10) + return frames.slice(-10).reduce((acc, frame) => `${acc},${frame.function},${frame.lineno},${frame.colno}`, ''); +} + +/** + * We use the stack parser to create a unique hash from the exception stack trace + * This is used to lookup vars when the exception passes through the event processor + */ +export function hashFromStack(stackParser: StackParser, stack: string | undefined): string | undefined { + if (stack === undefined) { + return undefined; + } + + return hashFrames(stackParser(stack, 1)); +} + +export interface FrameVariables { + function: string; + vars?: Variables; +} + +export interface LocalVariablesIntegrationOptions { + /** + * Capture local variables for both caught and uncaught exceptions + * + * - When false, only uncaught exceptions will have local variables + * - When true, both caught and uncaught exceptions will have local variables. + * + * Defaults to `true`. + * + * Capturing local variables for all exceptions can be expensive since the debugger pauses for every throw to collect + * local variables. + * + * To reduce the likelihood of this feature impacting app performance or throughput, this feature is rate-limited. + * Once the rate limit is reached, local variables will only be captured for uncaught exceptions until a timeout has + * been reached. + */ + captureAllExceptions?: boolean; + /** + * Maximum number of exceptions to capture local variables for per second before rate limiting is triggered. + */ + maxExceptionsPerSecond?: number; +} diff --git a/packages/node-experimental/src/integrations/local-variables/index.ts b/packages/node-experimental/src/integrations/local-variables/index.ts new file mode 100644 index 000000000000..60649b03118f --- /dev/null +++ b/packages/node-experimental/src/integrations/local-variables/index.ts @@ -0,0 +1,3 @@ +import { localVariablesSyncIntegration } from './local-variables-sync'; + +export const localVariablesIntegration = localVariablesSyncIntegration; diff --git a/packages/node-experimental/src/integrations/local-variables/inspector.d.ts b/packages/node-experimental/src/integrations/local-variables/inspector.d.ts new file mode 100644 index 000000000000..fca628d8405d --- /dev/null +++ b/packages/node-experimental/src/integrations/local-variables/inspector.d.ts @@ -0,0 +1,3387 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/no-unused-vars */ +/* eslint-disable @typescript-eslint/unified-signatures */ +/* eslint-disable @typescript-eslint/explicit-member-accessibility */ +/* eslint-disable max-lines */ +/* eslint-disable @typescript-eslint/ban-types */ +// Type definitions for inspector + +// These definitions were copied from: +// https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/d37bf642ed2f3fe403e405892e2eb4240a191bb0/types/node/inspector.d.ts + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface 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 undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | 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; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * 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; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: 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. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * 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; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: 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. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: 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 execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface 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. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with 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; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * 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 url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * 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; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * 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; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.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; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * 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 releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: 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. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name 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; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name 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; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post( + method: 'Schema.getDomains', + callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void, + ): void; + /** + * Evaluates expression on global object. + */ + post( + method: 'Runtime.evaluate', + params?: Runtime.EvaluateParameterType, + callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void, + ): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post( + method: 'Runtime.awaitPromise', + params?: Runtime.AwaitPromiseParameterType, + callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void, + ): void; + post( + method: 'Runtime.awaitPromise', + callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void, + ): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post( + method: 'Runtime.callFunctionOn', + params?: Runtime.CallFunctionOnParameterType, + callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void, + ): void; + post( + method: 'Runtime.callFunctionOn', + callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void, + ): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post( + method: 'Runtime.getProperties', + params?: Runtime.GetPropertiesParameterType, + callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void, + ): void; + post( + method: 'Runtime.getProperties', + callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void, + ): void; + /** + * Releases remote object with given id. + */ + post( + method: 'Runtime.releaseObject', + params?: Runtime.ReleaseObjectParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post( + method: 'Runtime.releaseObjectGroup', + params?: Runtime.ReleaseObjectGroupParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post( + method: 'Runtime.setCustomObjectFormatterEnabled', + params?: Runtime.SetCustomObjectFormatterEnabledParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post( + method: 'Runtime.compileScript', + params?: Runtime.CompileScriptParameterType, + callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void, + ): void; + post( + method: 'Runtime.compileScript', + callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void, + ): void; + /** + * Runs script with given id in a given context. + */ + post( + method: 'Runtime.runScript', + params?: Runtime.RunScriptParameterType, + callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void, + ): void; + post( + method: 'Runtime.runScript', + callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void, + ): void; + post( + method: 'Runtime.queryObjects', + params?: Runtime.QueryObjectsParameterType, + callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void, + ): void; + post( + method: 'Runtime.queryObjects', + callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void, + ): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void, + ): void; + post( + method: 'Runtime.globalLexicalScopeNames', + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void, + ): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post( + method: 'Debugger.setBreakpointsActive', + params?: Debugger.SetBreakpointsActiveParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post( + method: 'Debugger.setSkipAllPauses', + params?: Debugger.SetSkipAllPausesParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * 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 locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post( + method: 'Debugger.setBreakpointByUrl', + params?: Debugger.SetBreakpointByUrlParameterType, + callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void, + ): void; + post( + method: 'Debugger.setBreakpointByUrl', + callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void, + ): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post( + method: 'Debugger.setBreakpoint', + params?: Debugger.SetBreakpointParameterType, + callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void, + ): void; + post( + method: 'Debugger.setBreakpoint', + callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void, + ): void; + /** + * Removes JavaScript breakpoint. + */ + post( + method: 'Debugger.removeBreakpoint', + params?: Debugger.RemoveBreakpointParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void, + ): void; + post( + method: 'Debugger.getPossibleBreakpoints', + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void, + ): void; + /** + * Continues execution until specific location is reached. + */ + post( + method: 'Debugger.continueToLocation', + params?: Debugger.ContinueToLocationParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post( + method: 'Debugger.pauseOnAsyncCall', + params?: Debugger.PauseOnAsyncCallParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post( + method: 'Debugger.stepInto', + params?: Debugger.StepIntoParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post( + method: 'Debugger.getStackTrace', + params?: Debugger.GetStackTraceParameterType, + callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void, + ): void; + post( + method: 'Debugger.getStackTrace', + callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void, + ): void; + /** + * Searches for given string in script content. + */ + post( + method: 'Debugger.searchInContent', + params?: Debugger.SearchInContentParameterType, + callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void, + ): void; + post( + method: 'Debugger.searchInContent', + callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void, + ): void; + /** + * Edits JavaScript source live. + */ + post( + method: 'Debugger.setScriptSource', + params?: Debugger.SetScriptSourceParameterType, + callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void, + ): void; + post( + method: 'Debugger.setScriptSource', + callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void, + ): void; + /** + * Restarts particular call frame from the beginning. + */ + post( + method: 'Debugger.restartFrame', + params?: Debugger.RestartFrameParameterType, + callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void, + ): void; + post( + method: 'Debugger.restartFrame', + callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void, + ): void; + /** + * Returns source for the script with given id. + */ + post( + method: 'Debugger.getScriptSource', + params?: Debugger.GetScriptSourceParameterType, + callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void, + ): void; + post( + method: 'Debugger.getScriptSource', + callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void, + ): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post( + method: 'Debugger.setPauseOnExceptions', + params?: Debugger.SetPauseOnExceptionsParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post( + method: 'Debugger.evaluateOnCallFrame', + params?: Debugger.EvaluateOnCallFrameParameterType, + callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void, + ): void; + post( + method: 'Debugger.evaluateOnCallFrame', + callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void, + ): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post( + method: 'Debugger.setVariableValue', + params?: Debugger.SetVariableValueParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post( + method: 'Debugger.setReturnValue', + params?: Debugger.SetReturnValueParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post( + method: 'Debugger.setAsyncCallStackDepth', + params?: Debugger.SetAsyncCallStackDepthParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post( + method: 'Debugger.setBlackboxPatterns', + params?: Debugger.SetBlackboxPatternsParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post( + method: 'Debugger.setBlackboxedRanges', + params?: Debugger.SetBlackboxedRangesParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post( + method: 'Profiler.setSamplingInterval', + params?: Profiler.SetSamplingIntervalParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post( + method: 'Profiler.startPreciseCoverage', + params?: Profiler.StartPreciseCoverageParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post( + method: 'Profiler.takePreciseCoverage', + callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void, + ): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post( + method: 'Profiler.getBestEffortCoverage', + callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void, + ): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post( + method: 'Profiler.takeTypeProfile', + callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void, + ): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.startTrackingHeapObjects', + params?: HeapProfiler.StartTrackingHeapObjectsParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.stopTrackingHeapObjects', + params?: HeapProfiler.StopTrackingHeapObjectsParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.takeHeapSnapshot', + params?: HeapProfiler.TakeHeapSnapshotParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void, + ): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void, + ): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post( + method: 'HeapProfiler.addInspectedHeapObject', + params?: HeapProfiler.AddInspectedHeapObjectParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getHeapObjectId', + params?: HeapProfiler.GetHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void, + ): void; + post( + method: 'HeapProfiler.getHeapObjectId', + callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void, + ): void; + post( + method: 'HeapProfiler.startSampling', + params?: HeapProfiler.StartSamplingParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.stopSampling', + callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void, + ): void; + post( + method: 'HeapProfiler.getSamplingProfile', + callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void, + ): void; + /** + * Gets supported tracing categories. + */ + post( + method: 'NodeTracing.getCategories', + callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void, + ): void; + /** + * Start trace events collection. + */ + post( + method: 'NodeTracing.start', + params?: NodeTracing.StartParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post( + method: 'NodeWorker.sendMessageToWorker', + params?: NodeWorker.SendMessageToWorkerParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post( + method: 'NodeWorker.enable', + params?: NodeWorker.EnableParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post( + method: 'NodeWorker.detach', + params?: NodeWorker.DetachParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post( + method: 'NodeRuntime.notifyWhenWaitingForDisconnect', + params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, + callback?: (err: Error | null) => void, + ): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener( + event: 'Runtime.executionContextCreated', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when execution context is destroyed. + */ + addListener( + event: 'Runtime.executionContextDestroyed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener( + event: 'Runtime.exceptionThrown', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener( + event: 'Runtime.exceptionRevoked', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when console API was called. + */ + addListener( + event: 'Runtime.consoleAPICalled', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener( + event: 'Runtime.inspectRequested', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener( + event: 'Debugger.scriptParsed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener( + event: 'Debugger.scriptFailedToParse', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener( + event: 'Debugger.breakpointResolved', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener( + event: 'Debugger.paused', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener( + event: 'Console.messageAdded', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener( + event: 'Profiler.consoleProfileStarted', + listener: (message: InspectorNotification) => void, + ): this; + addListener( + event: 'Profiler.consoleProfileFinished', + listener: (message: InspectorNotification) => void, + ): this; + addListener( + event: 'HeapProfiler.addHeapSnapshotChunk', + listener: (message: InspectorNotification) => void, + ): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener( + event: 'HeapProfiler.reportHeapSnapshotProgress', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener( + event: 'HeapProfiler.lastSeenObjectId', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener( + event: 'HeapProfiler.heapStatsUpdate', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Contains an bucket of collected trace events. + */ + addListener( + event: 'NodeTracing.dataCollected', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener( + event: 'NodeWorker.attachedToWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when detached from the worker. + */ + addListener( + event: 'NodeWorker.detachedFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener( + event: 'NodeWorker.receivedMessageFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit( + event: 'Runtime.executionContextCreated', + message: InspectorNotification, + ): boolean; + emit( + event: 'Runtime.executionContextDestroyed', + message: InspectorNotification, + ): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit( + event: 'Runtime.exceptionThrown', + message: InspectorNotification, + ): boolean; + emit( + event: 'Runtime.exceptionRevoked', + message: InspectorNotification, + ): boolean; + emit( + event: 'Runtime.consoleAPICalled', + message: InspectorNotification, + ): boolean; + emit( + event: 'Runtime.inspectRequested', + message: InspectorNotification, + ): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit( + event: 'Debugger.scriptFailedToParse', + message: InspectorNotification, + ): boolean; + emit( + event: 'Debugger.breakpointResolved', + message: InspectorNotification, + ): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit( + event: 'Profiler.consoleProfileStarted', + message: InspectorNotification, + ): boolean; + emit( + event: 'Profiler.consoleProfileFinished', + message: InspectorNotification, + ): boolean; + emit( + event: 'HeapProfiler.addHeapSnapshotChunk', + message: InspectorNotification, + ): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit( + event: 'HeapProfiler.reportHeapSnapshotProgress', + message: InspectorNotification, + ): boolean; + emit( + event: 'HeapProfiler.lastSeenObjectId', + message: InspectorNotification, + ): boolean; + emit( + event: 'HeapProfiler.heapStatsUpdate', + message: InspectorNotification, + ): boolean; + emit( + event: 'NodeTracing.dataCollected', + message: InspectorNotification, + ): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit( + event: 'NodeWorker.attachedToWorker', + message: InspectorNotification, + ): boolean; + emit( + event: 'NodeWorker.detachedFromWorker', + message: InspectorNotification, + ): boolean; + emit( + event: 'NodeWorker.receivedMessageFromWorker', + message: InspectorNotification, + ): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on( + event: 'Runtime.executionContextCreated', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when execution context is destroyed. + */ + on( + event: 'Runtime.executionContextDestroyed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on( + event: 'Runtime.exceptionThrown', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when unhandled exception was revoked. + */ + on( + event: 'Runtime.exceptionRevoked', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when console API was called. + */ + on( + event: 'Runtime.consoleAPICalled', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on( + event: 'Runtime.inspectRequested', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on( + event: 'Debugger.scriptParsed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on( + event: 'Debugger.scriptFailedToParse', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on( + event: 'Debugger.breakpointResolved', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on( + event: 'Debugger.paused', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on( + event: 'Console.messageAdded', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on( + event: 'Profiler.consoleProfileStarted', + listener: (message: InspectorNotification) => void, + ): this; + on( + event: 'Profiler.consoleProfileFinished', + listener: (message: InspectorNotification) => void, + ): this; + on( + event: 'HeapProfiler.addHeapSnapshotChunk', + listener: (message: InspectorNotification) => void, + ): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on( + event: 'HeapProfiler.reportHeapSnapshotProgress', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on( + event: 'HeapProfiler.lastSeenObjectId', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on( + event: 'HeapProfiler.heapStatsUpdate', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Contains an bucket of collected trace events. + */ + on( + event: 'NodeTracing.dataCollected', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on( + event: 'NodeWorker.attachedToWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when detached from the worker. + */ + on( + event: 'NodeWorker.detachedFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on( + event: 'NodeWorker.receivedMessageFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once( + event: 'Runtime.executionContextCreated', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when execution context is destroyed. + */ + once( + event: 'Runtime.executionContextDestroyed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once( + event: 'Runtime.exceptionThrown', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when unhandled exception was revoked. + */ + once( + event: 'Runtime.exceptionRevoked', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when console API was called. + */ + once( + event: 'Runtime.consoleAPICalled', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once( + event: 'Runtime.inspectRequested', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once( + event: 'Debugger.scriptParsed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once( + event: 'Debugger.scriptFailedToParse', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once( + event: 'Debugger.breakpointResolved', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once( + event: 'Debugger.paused', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once( + event: 'Console.messageAdded', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once( + event: 'Profiler.consoleProfileStarted', + listener: (message: InspectorNotification) => void, + ): this; + once( + event: 'Profiler.consoleProfileFinished', + listener: (message: InspectorNotification) => void, + ): this; + once( + event: 'HeapProfiler.addHeapSnapshotChunk', + listener: (message: InspectorNotification) => void, + ): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once( + event: 'HeapProfiler.reportHeapSnapshotProgress', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once( + event: 'HeapProfiler.lastSeenObjectId', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once( + event: 'HeapProfiler.heapStatsUpdate', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Contains an bucket of collected trace events. + */ + once( + event: 'NodeTracing.dataCollected', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once( + event: 'NodeWorker.attachedToWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when detached from the worker. + */ + once( + event: 'NodeWorker.detachedFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once( + event: 'NodeWorker.receivedMessageFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener( + event: 'Runtime.executionContextCreated', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when execution context is destroyed. + */ + prependListener( + event: 'Runtime.executionContextDestroyed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener( + event: 'Runtime.exceptionThrown', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener( + event: 'Runtime.exceptionRevoked', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when console API was called. + */ + prependListener( + event: 'Runtime.consoleAPICalled', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener( + event: 'Runtime.inspectRequested', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener( + event: 'Debugger.scriptParsed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener( + event: 'Debugger.scriptFailedToParse', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener( + event: 'Debugger.breakpointResolved', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener( + event: 'Debugger.paused', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener( + event: 'Console.messageAdded', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener( + event: 'Profiler.consoleProfileStarted', + listener: (message: InspectorNotification) => void, + ): this; + prependListener( + event: 'Profiler.consoleProfileFinished', + listener: (message: InspectorNotification) => void, + ): this; + prependListener( + event: 'HeapProfiler.addHeapSnapshotChunk', + listener: (message: InspectorNotification) => void, + ): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener( + event: 'HeapProfiler.reportHeapSnapshotProgress', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener( + event: 'HeapProfiler.lastSeenObjectId', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener( + event: 'HeapProfiler.heapStatsUpdate', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener( + event: 'NodeTracing.dataCollected', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener( + event: 'NodeWorker.attachedToWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when detached from the worker. + */ + prependListener( + event: 'NodeWorker.detachedFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener( + event: 'NodeWorker.receivedMessageFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener( + event: 'Runtime.executionContextCreated', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener( + event: 'Runtime.executionContextDestroyed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener( + event: 'Runtime.exceptionThrown', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener( + event: 'Runtime.exceptionRevoked', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when console API was called. + */ + prependOnceListener( + event: 'Runtime.consoleAPICalled', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener( + event: 'Runtime.inspectRequested', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener( + event: 'Debugger.scriptParsed', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener( + event: 'Debugger.scriptFailedToParse', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener( + event: 'Debugger.breakpointResolved', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener( + event: 'Debugger.paused', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener( + event: 'Console.messageAdded', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener( + event: 'Profiler.consoleProfileStarted', + listener: (message: InspectorNotification) => void, + ): this; + prependOnceListener( + event: 'Profiler.consoleProfileFinished', + listener: (message: InspectorNotification) => void, + ): this; + prependOnceListener( + event: 'HeapProfiler.addHeapSnapshotChunk', + listener: (message: InspectorNotification) => void, + ): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener( + event: 'HeapProfiler.reportHeapSnapshotProgress', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener( + event: 'HeapProfiler.lastSeenObjectId', + listener: (message: InspectorNotification) => void, + ): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener( + event: 'HeapProfiler.heapStatsUpdate', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener( + event: 'NodeTracing.dataCollected', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener( + event: 'NodeWorker.attachedToWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener( + event: 'NodeWorker.detachedFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener( + event: 'NodeWorker.receivedMessageFromWorker', + listener: (message: InspectorNotification) => void, + ): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to`node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'node:inspector' { + import inspector = require('inspector'); + export = inspector; +} + +/** + * @types/node doesn't have a `node:inspector/promises` module, maybe because it's still experimental? + */ +declare module 'node:inspector/promises' { + /** + * Async Debugger session + */ + class Session { + constructor(); + + connect(): void; + + post(method: 'Debugger.pause' | 'Debugger.resume' | 'Debugger.enable' | 'Debugger.disable'): Promise; + post(method: 'Debugger.setPauseOnExceptions', params: Debugger.SetPauseOnExceptionsParameterType): Promise; + post( + method: 'Runtime.getProperties', + params: Runtime.GetPropertiesParameterType, + ): Promise; + + on( + event: 'Debugger.paused', + listener: (message: InspectorNotification) => void, + ): Session; + + on(event: 'Debugger.resumed', listener: () => void): Session; + } +} diff --git a/packages/node-experimental/src/integrations/local-variables/local-variables-async.ts b/packages/node-experimental/src/integrations/local-variables/local-variables-async.ts new file mode 100644 index 000000000000..db065466e82a --- /dev/null +++ b/packages/node-experimental/src/integrations/local-variables/local-variables-async.ts @@ -0,0 +1,267 @@ +import type { Session } from 'node:inspector/promises'; +import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core'; +import type { Event, Exception, Integration, IntegrationClass, IntegrationFn, StackParser } from '@sentry/types'; +import { LRUMap, dynamicRequire, logger } from '@sentry/utils'; +import type { Debugger, InspectorNotification, Runtime } from 'inspector'; + +import type { NodeClient } from '../../sdk/client'; +import type { NodeClientOptions } from '../../types'; +import type { + FrameVariables, + LocalVariablesIntegrationOptions, + PausedExceptionEvent, + RateLimitIncrement, + Variables, +} from './common'; +import { createRateLimiter, functionNamesMatch, hashFrames, hashFromStack } from './common'; + +async function unrollArray(session: Session, objectId: string, name: string, vars: Variables): Promise { + const properties: Runtime.GetPropertiesReturnType = await session.post('Runtime.getProperties', { + objectId, + ownProperties: true, + }); + + vars[name] = properties.result + .filter(v => v.name !== 'length' && !isNaN(parseInt(v.name, 10))) + .sort((a, b) => parseInt(a.name, 10) - parseInt(b.name, 10)) + .map(v => v.value?.value); +} + +async function unrollObject(session: Session, objectId: string, name: string, vars: Variables): Promise { + const properties: Runtime.GetPropertiesReturnType = await session.post('Runtime.getProperties', { + objectId, + ownProperties: true, + }); + + vars[name] = properties.result + .map<[string, unknown]>(v => [v.name, v.value?.value]) + .reduce((obj, [key, val]) => { + obj[key] = val; + return obj; + }, {} as Variables); +} + +function unrollOther(prop: Runtime.PropertyDescriptor, vars: Variables): void { + if (prop?.value?.value) { + vars[prop.name] = prop.value.value; + } else if (prop?.value?.description && prop?.value?.type !== 'function') { + vars[prop.name] = `<${prop.value.description}>`; + } +} + +async function getLocalVariables(session: Session, objectId: string): Promise { + const properties: Runtime.GetPropertiesReturnType = await session.post('Runtime.getProperties', { + objectId, + ownProperties: true, + }); + const variables = {}; + + for (const prop of properties.result) { + if (prop?.value?.objectId && prop?.value.className === 'Array') { + const id = prop.value.objectId; + await unrollArray(session, id, prop.name, variables); + } else if (prop?.value?.objectId && prop?.value?.className === 'Object') { + const id = prop.value.objectId; + await unrollObject(session, id, prop.name, variables); + } else if (prop?.value?.value || prop?.value?.description) { + unrollOther(prop, variables); + } + } + + return variables; +} + +const INTEGRATION_NAME = 'LocalVariablesAsync'; + +/** + * Adds local variables to exception frames + */ +const _localVariablesAsyncIntegration = ((options: LocalVariablesIntegrationOptions = {}) => { + const cachedFrames: LRUMap = new LRUMap(20); + let rateLimiter: RateLimitIncrement | undefined; + let shouldProcessEvent = false; + + async function handlePaused( + session: Session, + stackParser: StackParser, + { reason, data, callFrames }: PausedExceptionEvent, + ): Promise { + if (reason !== 'exception' && reason !== 'promiseRejection') { + return; + } + + rateLimiter?.(); + + // data.description contains the original error.stack + const exceptionHash = hashFromStack(stackParser, data?.description); + + if (exceptionHash == undefined) { + return; + } + + const frames = []; + + for (let i = 0; i < callFrames.length; i++) { + const { scopeChain, functionName, this: obj } = callFrames[i]; + + const localScope = scopeChain.find(scope => scope.type === 'local'); + + // obj.className is undefined in ESM modules + const fn = obj.className === 'global' || !obj.className ? functionName : `${obj.className}.${functionName}`; + + if (localScope?.object.objectId === undefined) { + frames[i] = { function: fn }; + } else { + const vars = await getLocalVariables(session, localScope.object.objectId); + frames[i] = { function: fn, vars }; + } + } + + cachedFrames.set(exceptionHash, frames); + } + + async function startDebugger(session: Session, clientOptions: NodeClientOptions): Promise { + session.connect(); + + let isPaused = false; + + session.on('Debugger.resumed', () => { + isPaused = false; + }); + + session.on('Debugger.paused', (event: InspectorNotification) => { + isPaused = true; + + handlePaused(session, clientOptions.stackParser, event.params as PausedExceptionEvent).then( + () => { + // After the pause work is complete, resume execution! + return isPaused ? session.post('Debugger.resume') : Promise.resolve(); + }, + _ => { + // ignore + }, + ); + }); + + await session.post('Debugger.enable'); + + const captureAll = options.captureAllExceptions !== false; + await session.post('Debugger.setPauseOnExceptions', { state: captureAll ? 'all' : 'uncaught' }); + + if (captureAll) { + const max = options.maxExceptionsPerSecond || 50; + + rateLimiter = createRateLimiter( + max, + () => { + logger.log('Local variables rate-limit lifted.'); + return session.post('Debugger.setPauseOnExceptions', { state: 'all' }); + }, + seconds => { + logger.log( + `Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${seconds} seconds.`, + ); + return session.post('Debugger.setPauseOnExceptions', { state: 'uncaught' }); + }, + ); + } + + shouldProcessEvent = true; + } + + function addLocalVariablesToException(exception: Exception): void { + const hash = hashFrames(exception.stacktrace?.frames); + + if (hash === undefined) { + return; + } + + // Check if we have local variables for an exception that matches the hash + // remove is identical to get but also removes the entry from the cache + const cachedFrame = cachedFrames.remove(hash); + + if (cachedFrame === undefined) { + return; + } + + const frameCount = exception.stacktrace?.frames?.length || 0; + + for (let i = 0; i < frameCount; i++) { + // Sentry frames are in reverse order + const frameIndex = frameCount - i - 1; + + // Drop out if we run out of frames to match up + if (!exception.stacktrace?.frames?.[frameIndex] || !cachedFrame[i]) { + break; + } + + if ( + // We need to have vars to add + cachedFrame[i].vars === undefined || + // We're not interested in frames that are not in_app because the vars are not relevant + exception.stacktrace.frames[frameIndex].in_app === false || + // The function names need to match + !functionNamesMatch(exception.stacktrace.frames[frameIndex].function, cachedFrame[i].function) + ) { + continue; + } + + exception.stacktrace.frames[frameIndex].vars = cachedFrame[i].vars; + } + } + + function addLocalVariablesToEvent(event: Event): Event { + for (const exception of event.exception?.values || []) { + addLocalVariablesToException(exception); + } + + return event; + } + + return { + name: INTEGRATION_NAME, + setup(client: NodeClient) { + const clientOptions = client.getOptions(); + + if (!clientOptions.includeLocalVariables) { + return; + } + + try { + // TODO: Use import()... + // It would be nice to use import() here, but this built-in library is not in Node <19 so webpack will pick it + // up and report it as a missing dependency + const { Session } = dynamicRequire(module, 'node:inspector/promises'); + + startDebugger(new Session(), clientOptions).catch(e => { + logger.error('Failed to start inspector session', e); + }); + } catch (e) { + logger.error('Failed to load inspector API', e); + return; + } + }, + processEvent(event: Event): Event { + if (shouldProcessEvent) { + return addLocalVariablesToEvent(event); + } + + return event; + }, + }; +}) satisfies IntegrationFn; + +export const localVariablesAsyncIntegration = defineIntegration(_localVariablesAsyncIntegration); + +/** + * Adds local variables to exception frames. + * @deprecated Use `localVariablesAsyncIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +export const LocalVariablesAsync = convertIntegrationFnToClass( + INTEGRATION_NAME, + localVariablesAsyncIntegration, +) as IntegrationClass Event; setup: (client: NodeClient) => void }>; + +// eslint-disable-next-line deprecation/deprecation +export type LocalVariablesAsync = typeof LocalVariablesAsync; diff --git a/packages/node-experimental/src/integrations/local-variables/local-variables-sync.ts b/packages/node-experimental/src/integrations/local-variables/local-variables-sync.ts new file mode 100644 index 000000000000..b014ed0adb77 --- /dev/null +++ b/packages/node-experimental/src/integrations/local-variables/local-variables-sync.ts @@ -0,0 +1,409 @@ +import { convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core'; +import type { Event, Exception, Integration, IntegrationClass, IntegrationFn, StackParser } from '@sentry/types'; +import { LRUMap, logger } from '@sentry/utils'; +import type { Debugger, InspectorNotification, Runtime, Session } from 'inspector'; + +import { NODE_MAJOR } from '../../nodeVersion'; +import type { NodeClient } from '../../sdk/client'; +import type { + FrameVariables, + LocalVariablesIntegrationOptions, + PausedExceptionEvent, + RateLimitIncrement, + Variables, +} from './common'; +import { createRateLimiter, functionNamesMatch, hashFrames, hashFromStack } from './common'; + +type OnPauseEvent = InspectorNotification; +export interface DebugSession { + /** Configures and connects to the debug session */ + configureAndConnect(onPause: (message: OnPauseEvent, complete: () => void) => void, captureAll: boolean): void; + /** Updates which kind of exceptions to capture */ + setPauseOnExceptions(captureAll: boolean): void; + /** Gets local variables for an objectId */ + getLocalVariables(objectId: string, callback: (vars: Variables) => void): void; +} + +type Next = (result: T) => void; +type Add = (fn: Next) => void; +type CallbackWrapper = { add: Add; next: Next }; + +/** Creates a container for callbacks to be called sequentially */ +export function createCallbackList(complete: Next): CallbackWrapper { + // A collection of callbacks to be executed last to first + let callbacks: Next[] = []; + + let completedCalled = false; + function checkedComplete(result: T): void { + callbacks = []; + if (completedCalled) { + return; + } + completedCalled = true; + complete(result); + } + + // complete should be called last + callbacks.push(checkedComplete); + + function add(fn: Next): void { + callbacks.push(fn); + } + + function next(result: T): void { + const popped = callbacks.pop() || checkedComplete; + + try { + popped(result); + } catch (_) { + // If there is an error, we still want to call the complete callback + checkedComplete(result); + } + } + + return { add, next }; +} + +/** + * Promise API is available as `Experimental` and in Node 19 only. + * + * Callback-based API is `Stable` since v14 and `Experimental` since v8. + * Because of that, we are creating our own `AsyncSession` class. + * + * https://nodejs.org/docs/latest-v19.x/api/inspector.html#promises-api + * https://nodejs.org/docs/latest-v14.x/api/inspector.html + */ +class AsyncSession implements DebugSession { + private readonly _session: Session; + + /** Throws if inspector API is not available */ + public constructor() { + /* + TODO: We really should get rid of this require statement below for a couple of reasons: + 1. It makes the integration unusable in the SvelteKit SDK, as it's not possible to use `require` + in SvelteKit server code (at least not by default). + 2. Throwing in a constructor is bad practice + + More context for a future attempt to fix this: + We already tried replacing it with import but didn't get it to work because of async problems. + We still called import in the constructor but assigned to a promise which we "awaited" in + `configureAndConnect`. However, this broke the Node integration tests as no local variables + were reported any more. We probably missed a place where we need to await the promise, too. + */ + + // Node can be built without inspector support so this can throw + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { Session } = require('inspector'); + this._session = new Session(); + } + + /** @inheritdoc */ + public configureAndConnect(onPause: (event: OnPauseEvent, complete: () => void) => void, captureAll: boolean): void { + this._session.connect(); + + this._session.on('Debugger.paused', event => { + onPause(event, () => { + // After the pause work is complete, resume execution or the exception context memory is leaked + this._session.post('Debugger.resume'); + }); + }); + + this._session.post('Debugger.enable'); + this._session.post('Debugger.setPauseOnExceptions', { state: captureAll ? 'all' : 'uncaught' }); + } + + public setPauseOnExceptions(captureAll: boolean): void { + this._session.post('Debugger.setPauseOnExceptions', { state: captureAll ? 'all' : 'uncaught' }); + } + + /** @inheritdoc */ + public getLocalVariables(objectId: string, complete: (vars: Variables) => void): void { + this._getProperties(objectId, props => { + const { add, next } = createCallbackList(complete); + + for (const prop of props) { + if (prop?.value?.objectId && prop?.value.className === 'Array') { + const id = prop.value.objectId; + add(vars => this._unrollArray(id, prop.name, vars, next)); + } else if (prop?.value?.objectId && prop?.value?.className === 'Object') { + const id = prop.value.objectId; + add(vars => this._unrollObject(id, prop.name, vars, next)); + } else if (prop?.value?.value || prop?.value?.description) { + add(vars => this._unrollOther(prop, vars, next)); + } + } + + next({}); + }); + } + + /** + * Gets all the PropertyDescriptors of an object + */ + private _getProperties(objectId: string, next: (result: Runtime.PropertyDescriptor[]) => void): void { + this._session.post( + 'Runtime.getProperties', + { + objectId, + ownProperties: true, + }, + (err, params) => { + if (err) { + next([]); + } else { + next(params.result); + } + }, + ); + } + + /** + * Unrolls an array property + */ + private _unrollArray(objectId: string, name: string, vars: Variables, next: (vars: Variables) => void): void { + this._getProperties(objectId, props => { + vars[name] = props + .filter(v => v.name !== 'length' && !isNaN(parseInt(v.name, 10))) + .sort((a, b) => parseInt(a.name, 10) - parseInt(b.name, 10)) + .map(v => v?.value?.value); + + next(vars); + }); + } + + /** + * Unrolls an object property + */ + private _unrollObject(objectId: string, name: string, vars: Variables, next: (obj: Variables) => void): void { + this._getProperties(objectId, props => { + vars[name] = props + .map<[string, unknown]>(v => [v.name, v?.value?.value]) + .reduce((obj, [key, val]) => { + obj[key] = val; + return obj; + }, {} as Variables); + + next(vars); + }); + } + + /** + * Unrolls other properties + */ + private _unrollOther(prop: Runtime.PropertyDescriptor, vars: Variables, next: (vars: Variables) => void): void { + if (prop?.value?.value) { + vars[prop.name] = prop.value.value; + } else if (prop?.value?.description && prop?.value?.type !== 'function') { + vars[prop.name] = `<${prop.value.description}>`; + } + + next(vars); + } +} + +/** + * When using Vercel pkg, the inspector module is not available. + * https://github.com/getsentry/sentry-javascript/issues/6769 + */ +function tryNewAsyncSession(): AsyncSession | undefined { + try { + return new AsyncSession(); + } catch (e) { + return undefined; + } +} + +const INTEGRATION_NAME = 'LocalVariables'; + +/** + * Adds local variables to exception frames + */ +const _localVariablesSyncIntegration = (( + options: LocalVariablesIntegrationOptions = {}, + session: DebugSession | undefined = tryNewAsyncSession(), +) => { + const cachedFrames: LRUMap = new LRUMap(20); + let rateLimiter: RateLimitIncrement | undefined; + let shouldProcessEvent = false; + + function handlePaused( + stackParser: StackParser, + { params: { reason, data, callFrames } }: InspectorNotification, + complete: () => void, + ): void { + if (reason !== 'exception' && reason !== 'promiseRejection') { + complete(); + return; + } + + rateLimiter?.(); + + // data.description contains the original error.stack + const exceptionHash = hashFromStack(stackParser, data?.description); + + if (exceptionHash == undefined) { + complete(); + return; + } + + const { add, next } = createCallbackList(frames => { + cachedFrames.set(exceptionHash, frames); + complete(); + }); + + // Because we're queuing up and making all these calls synchronously, we can potentially overflow the stack + // For this reason we only attempt to get local variables for the first 5 frames + for (let i = 0; i < Math.min(callFrames.length, 5); i++) { + const { scopeChain, functionName, this: obj } = callFrames[i]; + + const localScope = scopeChain.find(scope => scope.type === 'local'); + + // obj.className is undefined in ESM modules + const fn = obj.className === 'global' || !obj.className ? functionName : `${obj.className}.${functionName}`; + + if (localScope?.object.objectId === undefined) { + add(frames => { + frames[i] = { function: fn }; + next(frames); + }); + } else { + const id = localScope.object.objectId; + add(frames => + session?.getLocalVariables(id, vars => { + frames[i] = { function: fn, vars }; + next(frames); + }), + ); + } + } + + next([]); + } + + function addLocalVariablesToException(exception: Exception): void { + const hash = hashFrames(exception?.stacktrace?.frames); + + if (hash === undefined) { + return; + } + + // Check if we have local variables for an exception that matches the hash + // remove is identical to get but also removes the entry from the cache + const cachedFrame = cachedFrames.remove(hash); + + if (cachedFrame === undefined) { + return; + } + + const frameCount = exception.stacktrace?.frames?.length || 0; + + for (let i = 0; i < frameCount; i++) { + // Sentry frames are in reverse order + const frameIndex = frameCount - i - 1; + + // Drop out if we run out of frames to match up + if (!exception?.stacktrace?.frames?.[frameIndex] || !cachedFrame[i]) { + break; + } + + if ( + // We need to have vars to add + cachedFrame[i].vars === undefined || + // We're not interested in frames that are not in_app because the vars are not relevant + exception.stacktrace.frames[frameIndex].in_app === false || + // The function names need to match + !functionNamesMatch(exception.stacktrace.frames[frameIndex].function, cachedFrame[i].function) + ) { + continue; + } + + exception.stacktrace.frames[frameIndex].vars = cachedFrame[i].vars; + } + } + + function addLocalVariablesToEvent(event: Event): Event { + for (const exception of event?.exception?.values || []) { + addLocalVariablesToException(exception); + } + + return event; + } + + return { + name: INTEGRATION_NAME, + setupOnce() { + const client = getClient(); + const clientOptions = client?.getOptions(); + + if (session && clientOptions?.includeLocalVariables) { + // Only setup this integration if the Node version is >= v18 + // https://github.com/getsentry/sentry-javascript/issues/7697 + const unsupportedNodeVersion = NODE_MAJOR < 18; + + if (unsupportedNodeVersion) { + logger.log('The `LocalVariables` integration is only supported on Node >= v18.'); + return; + } + + const captureAll = options.captureAllExceptions !== false; + + session.configureAndConnect( + (ev, complete) => + handlePaused(clientOptions.stackParser, ev as InspectorNotification, complete), + captureAll, + ); + + if (captureAll) { + const max = options.maxExceptionsPerSecond || 50; + + rateLimiter = createRateLimiter( + max, + () => { + logger.log('Local variables rate-limit lifted.'); + session?.setPauseOnExceptions(true); + }, + seconds => { + logger.log( + `Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${seconds} seconds.`, + ); + session?.setPauseOnExceptions(false); + }, + ); + } + + shouldProcessEvent = true; + } + }, + processEvent(event: Event): Event { + if (shouldProcessEvent) { + return addLocalVariablesToEvent(event); + } + + return event; + }, + // These are entirely for testing + _getCachedFramesCount(): number { + return cachedFrames.size; + }, + _getFirstCachedFrame(): FrameVariables[] | undefined { + return cachedFrames.values()[0]; + }, + }; +}) satisfies IntegrationFn; + +export const localVariablesSyncIntegration = defineIntegration(_localVariablesSyncIntegration); + +/** + * Adds local variables to exception frames. + * @deprecated Use `localVariablesSyncIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +export const LocalVariablesSync = convertIntegrationFnToClass( + INTEGRATION_NAME, + localVariablesSyncIntegration, +) as IntegrationClass Event; setup: (client: NodeClient) => void }> & { + new (options?: LocalVariablesIntegrationOptions, session?: DebugSession): Integration; +}; + +// eslint-disable-next-line deprecation/deprecation +export type LocalVariablesSync = typeof LocalVariablesSync; diff --git a/packages/node-experimental/src/integrations/modules.ts b/packages/node-experimental/src/integrations/modules.ts new file mode 100644 index 000000000000..ad30bb4d7a3b --- /dev/null +++ b/packages/node-experimental/src/integrations/modules.ts @@ -0,0 +1,96 @@ +import { existsSync, readFileSync } from 'fs'; +import { dirname, join } from 'path'; +import { defineIntegration } from '@sentry/core'; +import type { IntegrationFn } from '@sentry/types'; + +let moduleCache: { [key: string]: string }; + +const INTEGRATION_NAME = 'Modules'; + +const _modulesIntegration = (() => { + return { + name: INTEGRATION_NAME, + processEvent(event) { + event.modules = { + ...event.modules, + ..._getModules(), + }; + + return event; + }, + }; +}) satisfies IntegrationFn; + +/** + * Add node modules / packages to the event. + */ +export const modulesIntegration = defineIntegration(_modulesIntegration); + +/** Extract information about paths */ +function getPaths(): string[] { + try { + return require.cache ? Object.keys(require.cache as Record) : []; + } catch (e) { + return []; + } +} + +/** Extract information about package.json modules */ +function collectModules(): { + [name: string]: string; +} { + const mainPaths = (require.main && require.main.paths) || []; + const paths = getPaths(); + const infos: { + [name: string]: string; + } = {}; + const seen: { + [path: string]: boolean; + } = {}; + + paths.forEach(path => { + let dir = path; + + /** Traverse directories upward in the search of package.json file */ + const updir = (): void | (() => void) => { + const orig = dir; + dir = dirname(orig); + + if (!dir || orig === dir || seen[orig]) { + return undefined; + } + if (mainPaths.indexOf(dir) < 0) { + return updir(); + } + + const pkgfile = join(orig, 'package.json'); + seen[orig] = true; + + if (!existsSync(pkgfile)) { + return updir(); + } + + try { + const info = JSON.parse(readFileSync(pkgfile, 'utf8')) as { + name: string; + version: string; + }; + infos[info.name] = info.version; + } catch (_oO) { + // no-empty + } + }; + + updir(); + }); + + return infos; +} + +/** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ +function _getModules(): { [key: string]: string } { + if (!moduleCache) { + moduleCache = collectModules(); + } + return moduleCache; +} diff --git a/packages/node-experimental/src/integrations/node-fetch.ts b/packages/node-experimental/src/integrations/node-fetch.ts index 94eca67c29ba..254b3f93e930 100644 --- a/packages/node-experimental/src/integrations/node-fetch.ts +++ b/packages/node-experimental/src/integrations/node-fetch.ts @@ -5,12 +5,10 @@ import { registerInstrumentations } from '@opentelemetry/instrumentation'; import { addBreadcrumb, defineIntegration } from '@sentry/core'; import { _INTERNAL, getSpanKind } from '@sentry/opentelemetry'; import type { IntegrationFn } from '@sentry/types'; -import { parseSemver } from '@sentry/utils'; +import { NODE_MAJOR } from '../nodeVersion'; import { addOriginToSpan } from '../utils/addOriginToSpan'; -const NODE_VERSION: ReturnType = parseSemver(process.versions.node); - interface NodeFetchOptions { /** * Whether breadcrumbs should be recorded for requests. @@ -31,7 +29,7 @@ const _nativeNodeFetchIntegration = ((options: NodeFetchOptions = {}) => { function getInstrumentation(): [Instrumentation] | void { // Only add NodeFetch if Node >= 16, as previous versions do not support it - if (!NODE_VERSION.major || NODE_VERSION.major < 16) { + if (NODE_MAJOR < 16) { return; } diff --git a/packages/node-experimental/src/integrations/onuncaughtexception.ts b/packages/node-experimental/src/integrations/onuncaughtexception.ts new file mode 100644 index 000000000000..84cae854ab81 --- /dev/null +++ b/packages/node-experimental/src/integrations/onuncaughtexception.ts @@ -0,0 +1,171 @@ +import { captureException, defineIntegration } from '@sentry/core'; +import { getClient } from '@sentry/core'; +import type { IntegrationFn } from '@sentry/types'; +import { logger } from '@sentry/utils'; + +import { DEBUG_BUILD } from '../debug-build'; +import type { NodeClient } from '../sdk/client'; +import { logAndExitProcess } from '../utils/errorhandling'; + +type OnFatalErrorHandler = (firstError: Error, secondError?: Error) => void; + +type TaggedListener = NodeJS.UncaughtExceptionListener & { + tag?: string; +}; + +// CAREFUL: Please think twice before updating the way _options looks because the Next.js SDK depends on it in `index.server.ts` +interface OnUncaughtExceptionOptions { + // TODO(v8): Evaluate whether we should switch the default behaviour here. + // Also, we can evaluate using https://nodejs.org/api/process.html#event-uncaughtexceptionmonitor per default, and + // falling back to current behaviour when that's not available. + /** + * Controls if the SDK should register a handler to exit the process on uncaught errors: + * - `true`: The SDK will exit the process on all uncaught errors. + * - `false`: The SDK will only exit the process when there are no other `uncaughtException` handlers attached. + * + * Default: `true` + */ + exitEvenIfOtherHandlersAreRegistered: boolean; + + /** + * This is called when an uncaught error would cause the process to exit. + * + * @param firstError Uncaught error causing the process to exit + * @param secondError Will be set if the handler was called multiple times. This can happen either because + * `onFatalError` itself threw, or because an independent error happened somewhere else while `onFatalError` + * was running. + */ + onFatalError?(this: void, firstError: Error, secondError?: Error): void; +} + +const INTEGRATION_NAME = 'OnUncaughtException'; + +const _onUncaughtExceptionIntegration = ((options: Partial = {}) => { + const _options = { + exitEvenIfOtherHandlersAreRegistered: true, + ...options, + }; + + return { + name: INTEGRATION_NAME, + setup(client: NodeClient) { + global.process.on('uncaughtException', makeErrorHandler(client, _options)); + }, + }; +}) satisfies IntegrationFn; + +/** + * Add a global exception handler. + */ +export const onUncaughtExceptionIntegration = defineIntegration(_onUncaughtExceptionIntegration); + +type ErrorHandler = { _errorHandler: boolean } & ((error: Error) => void); + +/** Exported only for tests */ +export function makeErrorHandler(client: NodeClient, options: OnUncaughtExceptionOptions): ErrorHandler { + const timeout = 2000; + let caughtFirstError: boolean = false; + let caughtSecondError: boolean = false; + let calledFatalError: boolean = false; + let firstError: Error; + + const clientOptions = client.getOptions(); + + return Object.assign( + (error: Error): void => { + let onFatalError: OnFatalErrorHandler = logAndExitProcess; + + if (options.onFatalError) { + onFatalError = options.onFatalError; + } else if (clientOptions.onFatalError) { + onFatalError = clientOptions.onFatalError as OnFatalErrorHandler; + } + + // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not + // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust + // exit behaviour of the SDK accordingly: + // - If other listeners are attached, do not exit. + // - If the only listener attached is ours, exit. + const userProvidedListenersCount = ( + global.process.listeners('uncaughtException') as TaggedListener[] + ).reduce((acc, listener) => { + if ( + // There are 3 listeners we ignore: + listener.name === 'domainUncaughtExceptionClear' || // as soon as we're using domains this listener is attached by node itself + (listener.tag && listener.tag === 'sentry_tracingErrorCallback') || // the handler we register for tracing + (listener as ErrorHandler)._errorHandler // the handler we register in this integration + ) { + return acc; + } else { + return acc + 1; + } + }, 0); + + const processWouldExit = userProvidedListenersCount === 0; + const shouldApplyFatalHandlingLogic = options.exitEvenIfOtherHandlersAreRegistered || processWouldExit; + + if (!caughtFirstError) { + // this is the first uncaught error and the ultimate reason for shutting down + // we want to do absolutely everything possible to ensure it gets captured + // also we want to make sure we don't go recursion crazy if more errors happen after this one + firstError = error; + caughtFirstError = true; + + if (getClient() === client) { + captureException(error, { + originalException: error, + captureContext: { + level: 'fatal', + }, + mechanism: { + handled: false, + type: 'onuncaughtexception', + }, + }); + } + + if (!calledFatalError && shouldApplyFatalHandlingLogic) { + calledFatalError = true; + onFatalError(error); + } + } else { + if (shouldApplyFatalHandlingLogic) { + if (calledFatalError) { + // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down + DEBUG_BUILD && + logger.warn( + 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown', + ); + logAndExitProcess(error); + } else if (!caughtSecondError) { + // two cases for how we can hit this branch: + // - capturing of first error blew up and we just caught the exception from that + // - quit trying to capture, proceed with shutdown + // - a second independent error happened while waiting for first error to capture + // - want to avoid causing premature shutdown before first error capture finishes + // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff + // so let's instead just delay a bit before we proceed with our action here + // in case 1, we just wait a bit unnecessarily but ultimately do the same thing + // in case 2, the delay hopefully made us wait long enough for the capture to finish + // two potential nonideal outcomes: + // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError + // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error + // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) + // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish + caughtSecondError = true; + setTimeout(() => { + if (!calledFatalError) { + // it was probably case 1, let's treat err as the sendErr and call onFatalError + calledFatalError = true; + onFatalError(firstError, error); + } else { + // it was probably case 2, our first error finished capturing while we waited, cool, do nothing + } + }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc + } + } + } + }, + { _errorHandler: true }, + ); +} diff --git a/packages/node-experimental/src/integrations/onunhandledrejection.ts b/packages/node-experimental/src/integrations/onunhandledrejection.ts new file mode 100644 index 000000000000..e1bc0b4145cf --- /dev/null +++ b/packages/node-experimental/src/integrations/onunhandledrejection.ts @@ -0,0 +1,95 @@ +import { captureException, defineIntegration, getClient } from '@sentry/core'; +import type { Client, IntegrationFn } from '@sentry/types'; +import { consoleSandbox } from '@sentry/utils'; +import { logAndExitProcess } from '../utils/errorhandling'; + +type UnhandledRejectionMode = 'none' | 'warn' | 'strict'; + +interface OnUnhandledRejectionOptions { + /** + * Option deciding what to do after capturing unhandledRejection, + * that mimicks behavior of node's --unhandled-rejection flag. + */ + mode: UnhandledRejectionMode; +} + +const INTEGRATION_NAME = 'OnUnhandledRejection'; + +const _onUnhandledRejectionIntegration = ((options: Partial = {}) => { + const mode = options.mode || 'warn'; + + return { + name: INTEGRATION_NAME, + setup(client) { + global.process.on('unhandledRejection', makeUnhandledPromiseHandler(client, { mode })); + }, + }; +}) satisfies IntegrationFn; + +/** + * Add a global promise rejection handler. + */ +export const onUnhandledRejectionIntegration = defineIntegration(_onUnhandledRejectionIntegration); + +/** + * Send an exception with reason + * @param reason string + * @param promise promise + * + * Exported only for tests. + */ +export function makeUnhandledPromiseHandler( + client: Client, + options: OnUnhandledRejectionOptions, +): (reason: unknown, promise: unknown) => void { + return function sendUnhandledPromise(reason: unknown, promise: unknown): void { + if (getClient() !== client) { + return; + } + + captureException(reason, { + originalException: promise, + captureContext: { + extra: { unhandledPromiseRejection: true }, + }, + mechanism: { + handled: false, + type: 'onunhandledrejection', + }, + }); + + handleRejection(reason, options); + }; +} + +/** + * Handler for `mode` option + + */ +function handleRejection( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + reason: any, + options: OnUnhandledRejectionOptions, +): void { + // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 + const rejectionWarning = + 'This error originated either by ' + + 'throwing inside of an async function without a catch block, ' + + 'or by rejecting a promise which was not handled with .catch().' + + ' The promise rejected with the reason:'; + + /* eslint-disable no-console */ + if (options.mode === 'warn') { + consoleSandbox(() => { + console.warn(rejectionWarning); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + console.error(reason && reason.stack ? reason.stack : reason); + }); + } else if (options.mode === 'strict') { + consoleSandbox(() => { + console.warn(rejectionWarning); + }); + logAndExitProcess(reason); + } + /* eslint-enable no-console */ +} diff --git a/packages/node-experimental/src/integrations/spotlight.ts b/packages/node-experimental/src/integrations/spotlight.ts new file mode 100644 index 000000000000..ebd8573c5072 --- /dev/null +++ b/packages/node-experimental/src/integrations/spotlight.ts @@ -0,0 +1,116 @@ +import * as http from 'http'; +import { URL } from 'url'; +import { defineIntegration } from '@sentry/core'; +import type { Client, Envelope, IntegrationFn } from '@sentry/types'; +import { logger, serializeEnvelope } from '@sentry/utils'; + +type SpotlightConnectionOptions = { + /** + * Set this if the Spotlight Sidecar is not running on localhost:8969 + * By default, the Url is set to http://localhost:8969/stream + */ + sidecarUrl?: string; +}; + +const INTEGRATION_NAME = 'Spotlight'; + +const _spotlightIntegration = ((options: Partial = {}) => { + const _options = { + sidecarUrl: options.sidecarUrl || 'http://localhost:8969/stream', + }; + + return { + name: INTEGRATION_NAME, + setup(client) { + if (typeof process === 'object' && process.env && process.env.NODE_ENV !== 'development') { + logger.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?"); + } + connectToSpotlight(client, _options); + }, + }; +}) satisfies IntegrationFn; + +/** + * Use this integration to send errors and transactions to Spotlight. + * + * Learn more about spotlight at https://spotlightjs.com + * + * Important: This integration only works with Node 18 or newer. + */ +export const spotlightIntegration = defineIntegration(_spotlightIntegration); + +function connectToSpotlight(client: Client, options: Required): void { + const spotlightUrl = parseSidecarUrl(options.sidecarUrl); + if (!spotlightUrl) { + return; + } + + let failedRequests = 0; + + client.on('beforeEnvelope', (envelope: Envelope) => { + if (failedRequests > 3) { + logger.warn('[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests'); + return; + } + + const serializedEnvelope = serializeEnvelope(envelope); + + const request = getNativeHttpRequest(); + const req = request( + { + method: 'POST', + path: spotlightUrl.pathname, + hostname: spotlightUrl.hostname, + port: spotlightUrl.port, + headers: { + 'Content-Type': 'application/x-sentry-envelope', + }, + }, + res => { + res.on('data', () => { + // Drain socket + }); + + res.on('end', () => { + // Drain socket + }); + res.setEncoding('utf8'); + }, + ); + + req.on('error', () => { + failedRequests++; + logger.warn('[Spotlight] Failed to send envelope to Spotlight Sidecar'); + }); + req.write(serializedEnvelope); + req.end(); + }); +} + +function parseSidecarUrl(url: string): URL | undefined { + try { + return new URL(`${url}`); + } catch { + logger.warn(`[Spotlight] Invalid sidecar URL: ${url}`); + return undefined; + } +} + +type HttpRequestImpl = typeof http.request; +type WrappedHttpRequest = HttpRequestImpl & { __sentry_original__: HttpRequestImpl }; + +/** + * We want to get an unpatched http request implementation to avoid capturing our own calls. + */ +export function getNativeHttpRequest(): HttpRequestImpl { + const { request } = http; + if (isWrapped(request)) { + return request.__sentry_original__; + } + + return request; +} + +function isWrapped(impl: HttpRequestImpl): impl is WrappedHttpRequest { + return '__sentry_original__' in impl; +} diff --git a/packages/node-experimental/src/integrations/tracing/hapi.ts b/packages/node-experimental/src/integrations/tracing/hapi.ts deleted file mode 100644 index 949726af698b..000000000000 --- a/packages/node-experimental/src/integrations/tracing/hapi.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { registerInstrumentations } from '@opentelemetry/instrumentation'; -import { HapiInstrumentation } from '@opentelemetry/instrumentation-hapi'; -import { defineIntegration } from '@sentry/core'; -import type { IntegrationFn } from '@sentry/types'; - -const _hapiIntegration = (() => { - return { - name: 'Hapi', - setupOnce() { - registerInstrumentations({ - instrumentations: [new HapiInstrumentation()], - }); - }, - }; -}) satisfies IntegrationFn; - -/** - * Hapi integration - * - * Capture tracing data for Hapi. - */ -export const hapiIntegration = defineIntegration(_hapiIntegration); diff --git a/packages/node-experimental/src/integrations/tracing/hapi/index.ts b/packages/node-experimental/src/integrations/tracing/hapi/index.ts new file mode 100644 index 000000000000..4d72af191f84 --- /dev/null +++ b/packages/node-experimental/src/integrations/tracing/hapi/index.ts @@ -0,0 +1,76 @@ +import { registerInstrumentations } from '@opentelemetry/instrumentation'; +import { HapiInstrumentation } from '@opentelemetry/instrumentation-hapi'; +import { SDK_VERSION, captureException, defineIntegration, getActiveSpan, getRootSpan } from '@sentry/core'; +import type { IntegrationFn } from '@sentry/types'; +import type { Boom, RequestEvent, ResponseObject, Server } from './types'; + +const _hapiIntegration = (() => { + return { + name: 'Hapi', + setupOnce() { + registerInstrumentations({ + instrumentations: [new HapiInstrumentation()], + }); + }, + }; +}) satisfies IntegrationFn; + +/** + * Hapi integration + * + * Capture tracing data for Hapi. + * If you also want to capture errors, you need to call `setupHapiErrorHandler(server)` after you set up your server. + */ +export const hapiIntegration = defineIntegration(_hapiIntegration); + +function isBoomObject(response: ResponseObject | Boom): response is Boom { + return response && (response as Boom).isBoom !== undefined; +} + +function isErrorEvent(event: RequestEvent): event is RequestEvent { + return event && (event as RequestEvent).error !== undefined; +} + +function sendErrorToSentry(errorData: object): void { + captureException(errorData, { + mechanism: { + type: 'hapi', + handled: false, + data: { + function: 'hapiErrorPlugin', + }, + }, + }); +} + +export const hapiErrorPlugin = { + name: 'SentryHapiErrorPlugin', + version: SDK_VERSION, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + register: async function (serverArg: Record) { + const server = serverArg as unknown as Server; + + server.events.on('request', (request, event) => { + const activeSpan = getActiveSpan(); + const rootSpan = activeSpan ? getRootSpan(activeSpan) : undefined; + + if (request.response && isBoomObject(request.response)) { + sendErrorToSentry(request.response); + } else if (isErrorEvent(event)) { + sendErrorToSentry(event.error); + } + + if (rootSpan) { + rootSpan.setStatus('internal_error'); + rootSpan.end(); + } + }); + }, +}; + +/** + * Add a Hapi plugin to capture errors to Sentry. + */ +export async function setupHapiErrorHandler(server: Server): Promise { + await server.register(hapiErrorPlugin); +} diff --git a/packages/node-experimental/src/integrations/tracing/hapi/types.ts b/packages/node-experimental/src/integrations/tracing/hapi/types.ts new file mode 100644 index 000000000000..a650667fe362 --- /dev/null +++ b/packages/node-experimental/src/integrations/tracing/hapi/types.ts @@ -0,0 +1,279 @@ +/* eslint-disable @typescript-eslint/no-misused-new */ +/* eslint-disable @typescript-eslint/naming-convention */ +/* eslint-disable @typescript-eslint/unified-signatures */ +/* eslint-disable @typescript-eslint/no-empty-interface */ +/* eslint-disable @typescript-eslint/no-namespace */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +// Vendored and simplified from: +// - @types/hapi__hapi +// v17.8.9999 +// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/c73060bd14bb74a2f1906ccfc714d385863bc07d/types/hapi/v17/index.d.ts +// +// - @types/podium +// v1.0.9999 +// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/c73060bd14bb74a2f1906ccfc714d385863bc07d/types/podium/index.d.ts +// +// - @types/boom +// v7.3.9999 +// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/c73060bd14bb74a2f1906ccfc714d385863bc07d/types/boom/v4/index.d.ts + +import type * as stream from 'stream'; +import type * as url from 'url'; + +interface Podium { + new (events?: Events[]): Podium; + new (events?: Events): Podium; + + registerEvent(events: Events[]): void; + registerEvent(events: Events): void; + + registerPodium?(podiums: Podium[]): void; + registerPodium?(podiums: Podium): void; + + emit( + criteria: string | { name: string; channel?: string | undefined; tags?: string | string[] | undefined }, + data: any, + callback?: () => void, + ): void; + + on(criteria: string | Criteria, listener: Listener): void; + addListener(criteria: string | Criteria, listener: Listener): void; + once(criteria: string | Criteria, listener: Listener): void; + removeListener(name: string, listener: Listener): Podium; + removeAllListeners(name: string): Podium; + hasListeners(name: string): boolean; +} + +export interface Boom extends Error { + isBoom: boolean; + isServer: boolean; + message: string; + output: Output; + reformat: () => string; + isMissing?: boolean | undefined; + data: Data; +} + +export interface Output { + statusCode: number; + headers: { [index: string]: string }; + payload: Payload; +} + +export interface Payload { + statusCode: number; + error: string; + message: string; + attributes?: any; +} + +export type Events = string | EventOptionsObject | Podium; + +export interface EventOptionsObject { + name: string; + channels?: string | string[] | undefined; + clone?: boolean | undefined; + spread?: boolean | undefined; + tags?: boolean | undefined; + shared?: boolean | undefined; +} + +export interface CriteriaObject { + name: string; + block?: boolean | number | undefined; + channels?: string | string[] | undefined; + clone?: boolean | undefined; + count?: number | undefined; + filter?: string | string[] | CriteriaFilterOptionsObject | undefined; + spread?: boolean | undefined; + tags?: boolean | undefined; + listener?: Listener | undefined; +} + +export interface CriteriaFilterOptionsObject { + tags?: string | string[] | undefined; + all?: boolean | undefined; +} + +export type Criteria = string | CriteriaObject; + +export interface Listener { + (data: any, tags?: Tags, callback?: () => void): void; +} + +export type Tags = { [tag: string]: boolean }; + +type Dependencies = + | string + | string[] + | { + [key: string]: string; + }; + +interface PluginNameVersion { + name: string; + version?: string | undefined; +} + +interface PluginPackage { + pkg: any; +} + +interface PluginBase { + register: (server: Server, options: T) => void | Promise; + multiple?: boolean | undefined; + dependencies?: Dependencies | undefined; + requirements?: + | { + node?: string | undefined; + hapi?: string | undefined; + } + | undefined; + + once?: boolean | undefined; +} + +type Plugin = PluginBase & (PluginNameVersion | PluginPackage); + +interface UserCredentials {} + +interface AppCredentials {} + +interface AuthCredentials { + scope?: string[] | undefined; + user?: UserCredentials | undefined; + app?: AppCredentials | undefined; +} + +interface RequestAuth { + artifacts: object; + credentials: AuthCredentials; + error: Error; + isAuthenticated: boolean; + isAuthorized: boolean; + mode: string; + strategy: string; +} + +interface RequestEvents extends Podium { + on(criteria: 'peek', listener: PeekListener): void; + on(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void; + once(criteria: 'peek', listener: PeekListener): void; + once(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void; +} + +namespace Lifecycle { + export type Method = (request: Request, h: ResponseToolkit, err?: Error) => ReturnValue; + export type ReturnValue = ReturnValueTypes | Promise; + export type ReturnValueTypes = + | (null | string | number | boolean) + | Buffer + | (Error | Boom) + | stream.Stream + | (object | object[]) + | symbol + | ResponseToolkit; + export type FailAction = 'error' | 'log' | 'ignore' | Method; +} + +namespace Util { + export interface Dictionary { + [key: string]: T; + } + + export type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; + export type HTTP_METHODS_PARTIAL = + | 'GET' + | 'POST' + | 'PUT' + | 'PATCH' + | 'DELETE' + | 'OPTIONS' + | HTTP_METHODS_PARTIAL_LOWERCASE; + export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; +} + +interface RequestRoute { + method: Util.HTTP_METHODS_PARTIAL; + path: string; + vhost?: string | string[] | undefined; + realm: any; + fingerprint: string; + + auth: { + access(request: Request): boolean; + }; +} + +interface Request extends Podium { + app: ApplicationState; + readonly auth: RequestAuth; + events: RequestEvents; + readonly headers: Util.Dictionary; + readonly path: string; + response: ResponseObject | Boom | null; + readonly route: RequestRoute; + readonly url: url.Url; +} + +interface ResponseObjectHeaderOptions { + append?: boolean | undefined; + separator?: string | undefined; + override?: boolean | undefined; + duplicate?: boolean | undefined; +} + +export interface ResponseObject extends Podium { + readonly statusCode: number; + header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject; +} + +interface ResponseToolkit { + readonly continue: symbol; +} + +interface ServerEventCriteria { + name: T; + channels?: string | string[] | undefined; + clone?: boolean | undefined; + count?: number | undefined; + filter?: string | string[] | { tags: string | string[]; all?: boolean | undefined } | undefined; + spread?: boolean | undefined; + tags?: boolean | undefined; +} + +export interface RequestEvent { + timestamp: string; + tags: string[]; + channel: 'internal' | 'app' | 'error'; + data: object; + error: object; +} + +type RequestEventHandler = (request: Request, event: RequestEvent, tags: { [key: string]: true }) => void; +interface ServerEvents { + on(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): void; +} + +type RouteRequestExtType = + | 'onPreAuth' + | 'onCredentials' + | 'onPostAuth' + | 'onPreHandler' + | 'onPostHandler' + | 'onPreResponse'; + +type ServerRequestExtType = RouteRequestExtType | 'onRequest'; + +export type Server = Record & { + events: ServerEvents; + ext(event: ServerRequestExtType, method: Lifecycle.Method, options?: Record): void; + initialize(): Promise; + register(plugins: Plugin | Array>, options?: Record): Promise; + start(): Promise; +}; + +interface ApplicationState {} + +type PeekListener = (chunk: string, encoding: string) => void; diff --git a/packages/node-experimental/src/nodeVersion.ts b/packages/node-experimental/src/nodeVersion.ts new file mode 100644 index 000000000000..792037ece168 --- /dev/null +++ b/packages/node-experimental/src/nodeVersion.ts @@ -0,0 +1,7 @@ +import { parseSemver } from '@sentry/utils'; + +export const NODE_VERSION = parseSemver(process.versions.node) as { + major: number | undefined; + minor: number | undefined; +}; +export const NODE_MAJOR = NODE_VERSION.major || 0; diff --git a/packages/node-experimental/src/sdk/init.ts b/packages/node-experimental/src/sdk/init.ts index c61a72155cda..2b41c235b234 100644 --- a/packages/node-experimental/src/sdk/init.ts +++ b/packages/node-experimental/src/sdk/init.ts @@ -1,13 +1,16 @@ import { endSession, + functionToStringIntegration, getClient, getCurrentScope, getIntegrationsToSetup, getIsolationScope, hasTracingEnabled, + inboundFiltersIntegration, + linkedErrorsIntegration, + requestDataIntegration, startSession, } from '@sentry/core'; -import { getDefaultIntegrations as getDefaultNodeIntegrations, spotlightIntegration } from '@sentry/node'; import { setOpenTelemetryContextAsyncContextStrategy } from '@sentry/opentelemetry'; import type { Client, Integration, Options } from '@sentry/types'; import { @@ -18,9 +21,17 @@ import { stackParserFromStackParserOptions, } from '@sentry/utils'; import { DEBUG_BUILD } from '../debug-build'; +import { consoleIntegration } from '../integrations/console'; +import { nodeContextIntegration } from '../integrations/context'; +import { contextLinesIntegration } from '../integrations/contextlines'; import { httpIntegration } from '../integrations/http'; +import { localVariablesIntegration } from '../integrations/local-variables'; +import { modulesIntegration } from '../integrations/modules'; import { nativeNodeFetchIntegration } from '../integrations/node-fetch'; +import { onUncaughtExceptionIntegration } from '../integrations/onuncaughtexception'; +import { onUnhandledRejectionIntegration } from '../integrations/onunhandledrejection'; +import { spotlightIntegration } from '../integrations/spotlight'; import { getAutoPerformanceIntegrations } from '../integrations/tracing'; import { makeNodeTransport } from '../transports'; import type { NodeClientOptions, NodeOptions } from '../types'; @@ -28,12 +39,27 @@ import { defaultStackParser, getSentryRelease } from './api'; import { NodeClient } from './client'; import { initOtel } from './initOtel'; -const ignoredDefaultIntegrations = ['Http', 'Undici']; - /** Get the default integrations for the Node Experimental SDK. */ export function getDefaultIntegrations(options: Options): Integration[] { + // TODO return [ - ...getDefaultNodeIntegrations(options).filter(i => !ignoredDefaultIntegrations.includes(i.name)), + // Common + inboundFiltersIntegration(), + functionToStringIntegration(), + linkedErrorsIntegration(), + requestDataIntegration(), + // Native Wrappers + consoleIntegration(), + httpIntegration(), + nativeNodeFetchIntegration(), + // Global Handlers + onUncaughtExceptionIntegration(), + onUnhandledRejectionIntegration(), + // Event Info + contextLinesIntegration(), + localVariablesIntegration(), + nodeContextIntegration(), + modulesIntegration(), httpIntegration(), nativeNodeFetchIntegration(), ...(hasTracingEnabled(options) ? getAutoPerformanceIntegrations() : []), diff --git a/packages/node-experimental/src/utils/errorhandling.ts b/packages/node-experimental/src/utils/errorhandling.ts new file mode 100644 index 000000000000..3e08ca5d2ff4 --- /dev/null +++ b/packages/node-experimental/src/utils/errorhandling.ts @@ -0,0 +1,40 @@ +import { getClient } from '@sentry/core'; +import { consoleSandbox, logger } from '@sentry/utils'; +import { DEBUG_BUILD } from '../debug-build'; +import type { NodeClient } from '../sdk/client'; + +const DEFAULT_SHUTDOWN_TIMEOUT = 2000; + +/** + * @hidden + */ +export function logAndExitProcess(error: Error): void { + consoleSandbox(() => { + // eslint-disable-next-line no-console + console.error(error); + }); + + const client = getClient(); + + if (client === undefined) { + DEBUG_BUILD && logger.warn('No NodeClient was defined, we are exiting the process now.'); + global.process.exit(1); + return; + } + + const options = client.getOptions(); + const timeout = + (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || + DEFAULT_SHUTDOWN_TIMEOUT; + client.close(timeout).then( + (result: boolean) => { + if (!result) { + DEBUG_BUILD && logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); + } + global.process.exit(1); + }, + error => { + DEBUG_BUILD && logger.error(error); + }, + ); +} diff --git a/packages/node-experimental/test/helpers/getDefaultNodePreviewClientOptions.ts b/packages/node-experimental/test/helpers/getDefaultNodeClientOptions.ts similarity index 100% rename from packages/node-experimental/test/helpers/getDefaultNodePreviewClientOptions.ts rename to packages/node-experimental/test/helpers/getDefaultNodeClientOptions.ts diff --git a/packages/node-experimental/test/integrations/context.test.ts b/packages/node-experimental/test/integrations/context.test.ts new file mode 100644 index 000000000000..519e101187ff --- /dev/null +++ b/packages/node-experimental/test/integrations/context.test.ts @@ -0,0 +1,22 @@ +import * as os from 'os'; + +import { getDeviceContext } from '../../src/integrations/context'; + +describe('Context', () => { + describe('getDeviceContext', () => { + afterAll(() => { + jest.clearAllMocks(); + }); + + it('returns boot time if os.uptime is defined and returns a valid uptime', () => { + const deviceCtx = getDeviceContext({}); + expect(deviceCtx.boot_time).toEqual(expect.any(String)); + }); + + it('returns no boot time if os.uptime() returns undefined', () => { + jest.spyOn(os, 'uptime').mockReturnValue(undefined as unknown as number); + const deviceCtx = getDeviceContext({}); + expect(deviceCtx.boot_time).toBeUndefined(); + }); + }); +}); diff --git a/packages/node-experimental/test/integrations/contextlines.test.ts b/packages/node-experimental/test/integrations/contextlines.test.ts new file mode 100644 index 000000000000..ba3fa8575e79 --- /dev/null +++ b/packages/node-experimental/test/integrations/contextlines.test.ts @@ -0,0 +1,150 @@ +import * as fs from 'fs'; +import type { StackFrame } from '@sentry/types'; +import { parseStackFrames } from '@sentry/utils'; + +import { _contextLinesIntegration, resetFileContentCache } from '../../src/integrations/contextlines'; +import { defaultStackParser } from '../../src/sdk/api'; + +jest.mock('fs', () => { + const actual = jest.requireActual('fs'); + return { + ...actual, + promises: { + ...actual.promises, + readFile: jest.fn(actual.promises), + }, + }; +}); + +describe('ContextLines', () => { + const readFileSpy = fs.promises.readFile as unknown as jest.SpyInstance; + let contextLines: ReturnType; + + async function addContext(frames: StackFrame[]): Promise { + await contextLines.processEvent({ exception: { values: [{ stacktrace: { frames } }] } }); + } + + beforeEach(() => { + contextLines = _contextLinesIntegration(); + resetFileContentCache(); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + describe('lru file cache', () => { + test('parseStack with same file', async () => { + expect.assertions(1); + + const frames = parseStackFrames(defaultStackParser, new Error('test')); + + await addContext(Array.from(frames)); + + const numCalls = readFileSpy.mock.calls.length; + await addContext(frames); + + // Calls to `readFile` shouldn't increase if there isn't a new error to + // parse whose stacktrace contains a file we haven't yet seen + expect(readFileSpy).toHaveBeenCalledTimes(numCalls); + }); + + test('parseStack with ESM module names', async () => { + expect.assertions(1); + + const framesWithFilePath: StackFrame[] = [ + { + colno: 1, + filename: 'file:///var/task/index.js', + lineno: 1, + function: 'fxn1', + }, + ]; + + await addContext(framesWithFilePath); + expect(readFileSpy).toHaveBeenCalledTimes(1); + }); + + test('parseStack with adding different file', async () => { + expect.assertions(1); + const frames = parseStackFrames(defaultStackParser, new Error('test')); + + await addContext(frames); + + const numCalls = readFileSpy.mock.calls.length; + const parsedFrames = parseStackFrames(defaultStackParser, getError()); + await addContext(parsedFrames); + + const newErrorCalls = readFileSpy.mock.calls.length; + expect(newErrorCalls).toBeGreaterThan(numCalls); + }); + + test('parseStack with duplicate files', async () => { + expect.assertions(1); + const framesWithDuplicateFiles: StackFrame[] = [ + { + colno: 1, + filename: '/var/task/index.js', + lineno: 1, + function: 'fxn1', + }, + { + colno: 2, + filename: '/var/task/index.js', + lineno: 2, + function: 'fxn2', + }, + { + colno: 3, + filename: '/var/task/index.js', + lineno: 3, + function: 'fxn3', + }, + ]; + + await addContext(framesWithDuplicateFiles); + expect(readFileSpy).toHaveBeenCalledTimes(1); + }); + + test('parseStack with no context', async () => { + contextLines = _contextLinesIntegration({ frameContextLines: 0 }); + + expect.assertions(1); + const frames = parseStackFrames(defaultStackParser, new Error('test')); + + await addContext(frames); + expect(readFileSpy).toHaveBeenCalledTimes(0); + }); + }); + + test('does not attempt to readfile multiple times if it fails', async () => { + expect.assertions(1); + + readFileSpy.mockImplementation(() => { + throw new Error("ENOENT: no such file or directory, open '/does/not/exist.js'"); + }); + + await addContext([ + { + colno: 1, + filename: '/does/not/exist.js', + lineno: 1, + function: 'fxn1', + }, + ]); + await addContext([ + { + colno: 1, + filename: '/does/not/exist.js', + lineno: 1, + function: 'fxn1', + }, + ]); + + expect(readFileSpy).toHaveBeenCalledTimes(1); + }); +}); + +function getError(): Error { + return new Error('mock error'); +} diff --git a/packages/node-experimental/test/integrations/localvariables.test.ts b/packages/node-experimental/test/integrations/localvariables.test.ts new file mode 100644 index 000000000000..db9385214d42 --- /dev/null +++ b/packages/node-experimental/test/integrations/localvariables.test.ts @@ -0,0 +1,140 @@ +import { createRateLimiter } from '../../src/integrations/local-variables/common'; +import { createCallbackList } from '../../src/integrations/local-variables/local-variables-sync'; +import { NODE_MAJOR } from '../../src/nodeVersion'; + +jest.setTimeout(20_000); + +const describeIf = (condition: boolean) => (condition ? describe : describe.skip); + +describeIf(NODE_MAJOR >= 18)('LocalVariables', () => { + describe('createCallbackList', () => { + it('Should call callbacks in reverse order', done => { + const log: number[] = []; + + const { add, next } = createCallbackList(n => { + expect(log).toEqual([5, 4, 3, 2, 1]); + expect(n).toBe(15); + done(); + }); + + add(n => { + log.push(1); + next(n + 1); + }); + + add(n => { + log.push(2); + next(n + 1); + }); + + add(n => { + log.push(3); + next(n + 1); + }); + + add(n => { + log.push(4); + next(n + 1); + }); + + add(n => { + log.push(5); + next(n + 11); + }); + + next(0); + }); + + it('only calls complete once even if multiple next', done => { + const { add, next } = createCallbackList(n => { + expect(n).toBe(1); + done(); + }); + + add(n => { + next(n + 1); + // We dont actually do this in our code... + next(n + 1); + }); + + next(0); + }); + + it('calls completed if added closure throws', done => { + const { add, next } = createCallbackList(n => { + expect(n).toBe(10); + done(); + }); + + add(n => { + throw new Error('test'); + next(n + 1); + }); + + next(10); + }); + }); + + describe('rateLimiter', () => { + it('calls disable if exceeded', done => { + const increment = createRateLimiter( + 5, + () => {}, + () => { + done(); + }, + ); + + for (let i = 0; i < 7; i++) { + increment(); + } + }); + + it('does not call disable if not exceeded', done => { + const increment = createRateLimiter( + 5, + () => { + throw new Error('Should not be called'); + }, + () => { + throw new Error('Should not be called'); + }, + ); + + let count = 0; + + const timer = setInterval(() => { + for (let i = 0; i < 4; i++) { + increment(); + } + + count += 1; + + if (count >= 5) { + clearInterval(timer); + done(); + } + }, 1_000); + }); + + it('re-enables after timeout', done => { + let called = false; + + const increment = createRateLimiter( + 5, + () => { + expect(called).toEqual(true); + done(); + }, + () => { + expect(called).toEqual(false); + called = true; + }, + ); + + for (let i = 0; i < 10; i++) { + increment(); + } + }); + }); +}); diff --git a/packages/node-experimental/test/integrations/spotlight.test.ts b/packages/node-experimental/test/integrations/spotlight.test.ts new file mode 100644 index 000000000000..6b888c22edcd --- /dev/null +++ b/packages/node-experimental/test/integrations/spotlight.test.ts @@ -0,0 +1,181 @@ +import * as http from 'http'; +import type { Envelope, EventEnvelope } from '@sentry/types'; +import { createEnvelope, logger } from '@sentry/utils'; + +import { spotlightIntegration } from '../../src/integrations/spotlight'; +import { NodeClient } from '../../src/sdk/client'; +import { getDefaultNodeClientOptions } from '../helpers/getDefaultNodeClientOptions'; + +describe('Spotlight', () => { + const loggerSpy = jest.spyOn(logger, 'warn'); + + afterEach(() => { + loggerSpy.mockClear(); + jest.clearAllMocks(); + }); + + const options = getDefaultNodeClientOptions(); + const client = new NodeClient(options); + + it('has a name', () => { + const integration = spotlightIntegration(); + expect(integration.name).toEqual('Spotlight'); + }); + + it('registers a callback on the `beforeEnvelope` hook', () => { + const clientWithSpy = { + ...client, + on: jest.fn(), + }; + const integration = spotlightIntegration(); + // @ts-expect-error - this is fine in tests + integration.setup(clientWithSpy); + expect(clientWithSpy.on).toHaveBeenCalledWith('beforeEnvelope', expect.any(Function)); + }); + + it('sends an envelope POST request to the sidecar url', () => { + const httpSpy = jest.spyOn(http, 'request').mockImplementationOnce(() => { + return { + on: jest.fn(), + write: jest.fn(), + end: jest.fn(), + } as any; + }); + + let callback: (envelope: Envelope) => void = () => {}; + const clientWithSpy = { + ...client, + on: jest.fn().mockImplementationOnce((_, cb) => (callback = cb)), + }; + + const integration = spotlightIntegration(); + // @ts-expect-error - this is fine in tests + integration.setup(clientWithSpy); + + const envelope = createEnvelope({ event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2', sent_at: '123' }, [ + [{ type: 'event' }, { event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2' }], + ]); + + callback(envelope); + + expect(httpSpy).toHaveBeenCalledWith( + { + headers: { + 'Content-Type': 'application/x-sentry-envelope', + }, + hostname: 'localhost', + method: 'POST', + path: '/stream', + port: '8969', + }, + expect.any(Function), + ); + }); + + it('sends an envelope POST request to a custom sidecar url', () => { + const httpSpy = jest.spyOn(http, 'request').mockImplementationOnce(() => { + return { + on: jest.fn(), + write: jest.fn(), + end: jest.fn(), + } as any; + }); + + let callback: (envelope: Envelope) => void = () => {}; + const clientWithSpy = { + ...client, + on: jest.fn().mockImplementationOnce((_, cb) => (callback = cb)), + }; + + const integration = spotlightIntegration({ sidecarUrl: 'http://mylocalhost:8888/abcd' }); + // @ts-expect-error - this is fine in tests + integration.setup(clientWithSpy); + + const envelope = createEnvelope({ event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2', sent_at: '123' }, [ + [{ type: 'event' }, { event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2' }], + ]); + + callback(envelope); + + expect(httpSpy).toHaveBeenCalledWith( + { + headers: { + 'Content-Type': 'application/x-sentry-envelope', + }, + hostname: 'mylocalhost', + method: 'POST', + path: '/abcd', + port: '8888', + }, + expect.any(Function), + ); + }); + + describe('no-ops if', () => { + it('an invalid URL is passed', () => { + const integration = spotlightIntegration({ sidecarUrl: 'invalid-url' }); + integration.setup!(client); + expect(loggerSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid sidecar URL: invalid-url')); + }); + }); + + it('warns if the NODE_ENV variable doesn\'t equal "development"', () => { + const oldEnvValue = process.env.NODE_ENV; + process.env.NODE_ENV = 'production'; + + const integration = spotlightIntegration({ sidecarUrl: 'http://localhost:8969' }); + integration.setup!(client); + + expect(loggerSpy).toHaveBeenCalledWith( + expect.stringContaining("It seems you're not in dev mode. Do you really want to have Spotlight enabled?"), + ); + + process.env.NODE_ENV = oldEnvValue; + }); + + it('doesn\'t warn if the NODE_ENV variable equals "development"', () => { + const oldEnvValue = process.env.NODE_ENV; + process.env.NODE_ENV = 'development'; + + const integration = spotlightIntegration({ sidecarUrl: 'http://localhost:8969' }); + integration.setup!(client); + + expect(loggerSpy).not.toHaveBeenCalledWith( + expect.stringContaining("It seems you're not in dev mode. Do you really want to have Spotlight enabled?"), + ); + + process.env.NODE_ENV = oldEnvValue; + }); + + it('handles `process` not being available', () => { + const originalProcess = process; + + // @ts-expect-error - TS complains but we explicitly wanna test this + delete global.process; + + const integration = spotlightIntegration({ sidecarUrl: 'http://localhost:8969' }); + integration.setup!(client); + + expect(loggerSpy).not.toHaveBeenCalledWith( + expect.stringContaining("It seems you're not in dev mode. Do you really want to have Spotlight enabled?"), + ); + + global.process = originalProcess; + }); + + it('handles `process.env` not being available', () => { + const originalEnv = process.env; + + // @ts-expect-error - TS complains but we explicitly wanna test this + delete process.env; + + const integration = spotlightIntegration({ sidecarUrl: 'http://localhost:8969' }); + integration.setup!(client); + + expect(loggerSpy).not.toHaveBeenCalledWith( + expect.stringContaining("It seems you're not in dev mode. Do you really want to have Spotlight enabled?"), + ); + + process.env = originalEnv; + }); +}); diff --git a/packages/node-experimental/test/sdk/client.test.ts b/packages/node-experimental/test/sdk/client.test.ts index f9e69b0b7233..de2b6c6fdf6b 100644 --- a/packages/node-experimental/test/sdk/client.test.ts +++ b/packages/node-experimental/test/sdk/client.test.ts @@ -15,7 +15,7 @@ import type { Scope } from '@sentry/types'; import { setOpenTelemetryContextAsyncContextStrategy } from '@sentry/opentelemetry'; import { NodeClient } from '../../src/sdk/client'; import { initOtel } from '../../src/sdk/initOtel'; -import { getDefaultNodeClientOptions } from '../helpers/getDefaultNodePreviewClientOptions'; +import { getDefaultNodeClientOptions } from '../helpers/getDefaultNodeClientOptions'; import { cleanupOtel } from '../helpers/mockSdkInit'; describe('NodeClient', () => { diff --git a/packages/node-experimental/test/sdk/handlers/errorHandler.test.ts b/packages/node-experimental/test/sdk/handlers/errorHandler.test.ts index 05d3f73858d7..58c0cf934316 100644 --- a/packages/node-experimental/test/sdk/handlers/errorHandler.test.ts +++ b/packages/node-experimental/test/sdk/handlers/errorHandler.test.ts @@ -3,7 +3,7 @@ import { getCurrentScope, getIsolationScope, setAsyncContextStrategy, setCurrent import type { Scope } from '@sentry/types'; import { NodeClient } from '../../../src/sdk/client'; import { errorHandler } from '../../../src/sdk/handlers/errorHandler'; -import { getDefaultNodeClientOptions } from '../../helpers/getDefaultNodePreviewClientOptions'; +import { getDefaultNodeClientOptions } from '../../helpers/getDefaultNodeClientOptions'; describe('errorHandler()', () => { beforeEach(() => { diff --git a/packages/node-experimental/tsconfig.json b/packages/node-experimental/tsconfig.json index bf45a09f2d71..5fc0658105eb 100644 --- a/packages/node-experimental/tsconfig.json +++ b/packages/node-experimental/tsconfig.json @@ -4,6 +4,6 @@ "include": ["src/**/*"], "compilerOptions": { - // package-specific options + "lib": ["es6"] } } From 62d5cfadb4a94134e21913605fc7ff207f2ac866 Mon Sep 17 00:00:00 2001 From: Francesco Novy Date: Tue, 20 Feb 2024 17:09:16 +0100 Subject: [PATCH 2/2] fix e2e test --- .../e2e-tests/test-applications/node-hapi-app/src/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-packages/e2e-tests/test-applications/node-hapi-app/src/app.js b/dev-packages/e2e-tests/test-applications/node-hapi-app/src/app.js index 896479d3d338..5a7712dd4495 100644 --- a/dev-packages/e2e-tests/test-applications/node-hapi-app/src/app.js +++ b/dev-packages/e2e-tests/test-applications/node-hapi-app/src/app.js @@ -10,7 +10,7 @@ Sentry.init({ environment: 'qa', // dynamic sampling bias to keep transactions dsn: process.env.E2E_TEST_DSN, includeLocalVariables: true, - integrations: [new Sentry.hapiIntegration({ server })], + integrations: [Sentry.hapiIntegration({ server })], debug: true, tunnel: `http://localhost:3031/`, // proxy server tracesSampleRate: 1,