Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Update to v7.92.0 of JavaScript SDKs #810

Merged
merged 7 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,19 @@
"e2e": "cross-env TS_NODE_PROJECT=tsconfig.test.json xvfb-maybe mocha --require ts-node/register/transpile-only --retries 3 ./test/e2e/*.ts"
},
"dependencies": {
"@sentry/browser": "7.90.0",
"@sentry/core": "7.90.0",
"@sentry/node": "7.90.0",
"@sentry/types": "7.90.0",
"@sentry/utils": "7.90.0",
"@sentry/browser": "7.92.0",
"@sentry/core": "7.92.0",
"@sentry/node": "7.92.0",
"@sentry/types": "7.92.0",
"@sentry/utils": "7.92.0",
"deepmerge": "4.3.0",
"tslib": "^2.5.0"
},
"devDependencies": {
"@rollup/plugin-node-resolve": "^15.2.1",
"@rollup/plugin-typescript": "^11.1.4",
"@sentry-internal/eslint-config-sdk": "7.90.0",
"@sentry-internal/typescript": "7.90.0",
"@sentry-internal/eslint-config-sdk": "7.92.0",
"@sentry-internal/typescript": "7.92.0",
"@types/busboy": "^0.2.3",
"@types/chai": "^4.2.10",
"@types/chai-as-promised": "^7.1.5",
Expand Down
43 changes: 8 additions & 35 deletions src/common/normalize.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,5 @@
import { Envelope, Event, Profile, ReplayEvent } from '@sentry/types';
import { addItemToEnvelope, createEnvelope, forEachEnvelopeItem } from '@sentry/utils';

/**
* Normalizes URLs in exceptions and stacktraces so Sentry can fingerprint
* across platforms.
*
* @param url The URL to be normalized.
* @param basePath The application base path.
* @returns The normalized URL.
*/
export function normalizeUrl(url: string, basePath: string): string {
const escapedBase = basePath
// Backslash to forward
.replace(/\\/g, '/')
// Escape RegExp special characters
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');

let newUrl = url;
try {
newUrl = decodeURI(url);
} catch (_Oo) {
// Sometime this breaks
}
return newUrl
.replace(/\\/g, '/')
.replace(/webpack:\/?/g, '') // Remove intermediate base path
.replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///');
}
import { addItemToEnvelope, createEnvelope, forEachEnvelopeItem, normalizeUrlToBase } from '@sentry/utils';

/**
* Normalizes all URLs in an event. See {@link normalizeUrl} for more
Expand All @@ -40,25 +13,25 @@ export function normalizeEvent(event: Event, basePath: string): Event {
for (const exception of event.exception?.values || []) {
for (const frame of exception.stacktrace?.frames || []) {
if (frame.filename) {
frame.filename = normalizeUrl(frame.filename, basePath);
frame.filename = normalizeUrlToBase(frame.filename, basePath);
}
}
}

// We need to normalize debug ID images the same way as the stack frames for symbolicator to match them correctly
for (const debugImage of event.debug_meta?.images || []) {
if (debugImage.type === 'sourcemap') {
debugImage.code_file = normalizeUrl(debugImage.code_file, basePath);
debugImage.code_file = normalizeUrlToBase(debugImage.code_file, basePath);
}
}

if (event.transaction) {
event.transaction = normalizeUrl(event.transaction, basePath);
event.transaction = normalizeUrlToBase(event.transaction, basePath);
}

const { request = {} } = event;
if (request.url) {
request.url = normalizeUrl(request.url, basePath);
request.url = normalizeUrlToBase(request.url, basePath);
}

event.contexts = {
Expand Down Expand Up @@ -96,11 +69,11 @@ export function normalizeUrlsInReplayEnvelope(envelope: Envelope, basePath: stri
const [headers, event] = item as [{ type: 'replay_event' }, ReplayEvent];

if (Array.isArray(event.urls)) {
event.urls = event.urls.map((url) => normalizeUrl(url, basePath));
event.urls = event.urls.map((url) => normalizeUrlToBase(url, basePath));
}

if (event?.request?.url) {
event.request.url = normalizeUrl(event.request.url, basePath);
event.request.url = normalizeUrlToBase(event.request.url, basePath);
}

modifiedEnvelope = addItemToEnvelope(modifiedEnvelope, [headers, event]);
Expand All @@ -118,7 +91,7 @@ export function normalizeUrlsInReplayEnvelope(envelope: Envelope, basePath: stri
export function normaliseProfile(profile: Profile, basePath: string): void {
for (const frame of profile.profile.frames) {
if (frame.abs_path) {
frame.abs_path = normalizeUrl(frame.abs_path, basePath);
frame.abs_path = normalizeUrlToBase(frame.abs_path, basePath);
}
}
}
27 changes: 11 additions & 16 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ export {
getCurrentHub,
getClient,
getCurrentScope,
getGlobalScope,
getIsolationScope,
Hub,
// eslint-disable-next-line deprecation/deprecation
lastEventId,
makeMain,
runWithAsyncContext,
Expand All @@ -57,6 +60,7 @@ export {
setTags,
setUser,
spanStatusfromHttpCode,
// eslint-disable-next-line deprecation/deprecation
trace,
withScope,
captureCheckIn,
Expand Down Expand Up @@ -88,6 +92,7 @@ interface ProcessEntryPoint {
init: (options: Partial<ElectronOptions>) => void;
close?: (timeout?: number) => Promise<boolean>;
flush?: (timeout?: number) => Promise<boolean>;
// eslint-disable-next-line deprecation/deprecation
enableMainProcessAnrDetection?(options: Parameters<typeof enableNodeAnrDetection>[0]): Promise<void>;
}

Expand Down Expand Up @@ -194,28 +199,18 @@ export async function flush(timeout?: number): Promise<boolean> {
}

/**
* **Note** This feature is still in beta so there may be breaking changes in future releases.
*
* Starts a child process that detects Application Not Responding (ANR) errors.
*
* It's important to await on the returned promise before your app code to ensure this code does not run in the ANR
* child process.
* @deprecated Use `Anr` integration instead.
*
* ```js
* import { init, enableMainProcessAnrDetection } from '@sentry/electron';
*
* init({ dsn: "__DSN__" });
* import { init, Integrations } from '@sentry/electron';
*
* // with ESM + Electron v28+
* await enableMainProcessAnrDetection({ captureStackTrace: true });
* runApp();
*
* // with CJS
* enableMainProcessAnrDetection({ captureStackTrace: true }).then(() => {
* runApp();
* init({
* dsn: "__DSN__",
* integrations: [new Integrations.Anr({ captureStackTrace: true })],
* });
* ```
*/
// eslint-disable-next-line deprecation/deprecation
export function enableMainProcessAnrDetection(options: Parameters<typeof enableNodeAnrDetection>[0]): Promise<void> {
const entryPoint = getEntryPoint();

Expand Down
119 changes: 71 additions & 48 deletions src/main/anr.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import {
captureEvent,
enableAnrDetection as enableNodeAnrDetection,
getCurrentHub,
getModuleFromFilename,
StackFrame,
} from '@sentry/node';
import { captureEvent, getClient, getCurrentHub, getModuleFromFilename, NodeClient, StackFrame } from '@sentry/node';
import { Event } from '@sentry/types';
import { createDebugPauseMessageHandler, logger, watchdogTimer } from '@sentry/utils';
import { app, WebContents } from 'electron';
import { callFrameToStackFrame, logger, stripSentryFramesAndReverse, watchdogTimer } from '@sentry/utils';
import { WebContents } from 'electron';

import { RendererStatus } from '../common';
import { ELECTRON_MAJOR_VERSION } from './electron-normalize';
import { Anr } from './integrations/anr';
import { ElectronMainOptions } from './sdk';
import { sessionAnr } from './sessions';

Expand Down Expand Up @@ -47,17 +41,60 @@ function sendRendererAnrEvent(contents: WebContents, blockedMs: number, frames?:
captureEvent(event);
}

interface ScriptParsedEventDataType {
scriptId: string;
url: string;
}

interface Location {
scriptId: string;
lineNumber: number;
columnNumber?: number;
}

interface CallFrame {
functionName: string;
location: Location;
url: string;
}

interface PausedEventDataType {
callFrames: CallFrame[];
reason: string;
}

function rendererDebugger(contents: WebContents, pausedStack: (frames: StackFrame[]) => void): () => void {
contents.debugger.attach('1.3');

const messageHandler = createDebugPauseMessageHandler(
(cmd) => contents.debugger.sendCommand(cmd),
getModuleFromFilename,
pausedStack,
);
// Collect scriptId -> url map so we can look up the filenames later
const scripts = new Map<string, string>();

contents.debugger.on('message', (_, method, params) => {
messageHandler({ method, params } as Parameters<typeof messageHandler>[0]);
if (method === 'Debugger.scriptParsed') {
const param = params as ScriptParsedEventDataType;
scripts.set(param.scriptId, param.url);
} else if (method === 'Debugger.paused') {
const param = params as PausedEventDataType;

if (param.reason !== 'other') {
return;
}

// copy the frames
const callFrames = [...param.callFrames];

contents.debugger.sendCommand('Debugger.resume').then(null, () => {
// ignore
});

const stackFrames = stripSentryFramesAndReverse(
callFrames.map((frame) =>
callFrameToStackFrame(frame, scripts.get(frame.location.scriptId), getModuleFromFilename),
),
);

pausedStack(stackFrames);
}
});

// In node, we enable just before pausing but for Chrome, the debugger must be enabled before he ANR event occurs
Expand Down Expand Up @@ -86,11 +123,6 @@ function createHrTimer(): { getTimeMs: () => number; reset: () => void } {
};
}

/** Are we currently running in the ANR child process */
export function isAnrChildProcess(): boolean {
return !!process.env.SENTRY_ANR_CHILD_PROCESS;
}

/** Creates a renderer ANR status hook */
export function createRendererAnrStatusHandler(): (status: RendererStatus, contents: WebContents) => void {
function log(message: string, ...args: unknown[]): void {
Expand Down Expand Up @@ -141,38 +173,29 @@ export function createRendererAnrStatusHandler(): (status: RendererStatus, conte
};
}

interface LegacyOptions {
entryScript: string;
pollInterval: number;
anrThreshold: number;
captureStackTrace: boolean;
debug: boolean;
}

/**
* **Note** This feature is still in beta so there may be breaking changes in future releases.
*
* Starts a child process that detects Application Not Responding (ANR) errors.
*
* It's important to await on the returned promise before your app code to ensure this code does not run in the ANR
* child process.
* @deprecated Use `Anr` integration instead.
*
* ```js
* import { init, enableMainProcessAnrDetection } from '@sentry/electron';
* import { init, Integrations } from '@sentry/electron';
*
* init({ dsn: "__DSN__" });
*
* // with ESM + Electron v28+
* await enableMainProcessAnrDetection({ captureStackTrace: true });
* runApp();
*
* // with CJS
* enableMainProcessAnrDetection({ captureStackTrace: true }).then(() => {
* runApp();
* init({
* dsn: "__DSN__",
* integrations: [new Integrations.Anr({ captureStackTrace: true })],
* });
* ```
*/
export function enableMainProcessAnrDetection(options: Parameters<typeof enableNodeAnrDetection>[0]): Promise<void> {
if (ELECTRON_MAJOR_VERSION < 4) {
throw new Error('Main process ANR detection is only supported on Electron v4+');
}

const mainOptions = {
entryScript: app.getAppPath(),
...options,
};

return enableNodeAnrDetection(mainOptions);
export function enableMainProcessAnrDetection(options: Partial<LegacyOptions> = {}): Promise<void> {
const integration = new Anr(options);
const client = getClient() as NodeClient;
integration.setup?.(client);
return Promise.resolve();
}
1 change: 0 additions & 1 deletion src/main/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,6 @@ export function getDefaultEnvironment(): string {
*/
async function _getEventDefaults(release?: string, environment?: string): Promise<Event> {
return {
sdk: getSdkInfo(),
contexts: await getContexts(),
environment: environment || getDefaultEnvironment(),
release: release || getDefaultReleaseName(),
Expand Down
7 changes: 6 additions & 1 deletion src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ export {
getCurrentHub,
getClient,
getCurrentScope,
getGlobalScope,
getIsolationScope,
Hub,
makeMain,
runWithAsyncContext,
Expand All @@ -57,6 +59,7 @@ export {
setTags,
setUser,
spanStatusfromHttpCode,
// eslint-disable-next-line deprecation/deprecation
trace,
withScope,
captureCheckIn,
Expand All @@ -74,13 +77,15 @@ export {
export type { SpanStatusType } from '@sentry/core';

export type { NodeOptions } from '@sentry/node';
// eslint-disable-next-line deprecation/deprecation
export { flush, close, NodeClient, lastEventId } from '@sentry/node';

export { makeElectronTransport } from './transports/electron-net';
export { makeElectronOfflineTransport } from './transports/electron-offline-net';
export const Integrations = { ...ElectronMainIntegrations, ...NodeIntegrations };
export const Integrations = { ...NodeIntegrations, ...ElectronMainIntegrations };

export type { ElectronMainOptions } from './sdk';
export { init, defaultIntegrations } from './sdk';
export { IPCMode } from '../common';
// eslint-disable-next-line deprecation/deprecation
export { enableMainProcessAnrDetection } from './anr';
Loading
Loading