Skip to content

Commit 334b097

Browse files
author
Luca Forstner
authored
ref(build): Add debug constants in each package individually (#4842)
1 parent b5756ee commit 334b097

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

71 files changed

+506
-240
lines changed

CONTRIBUTING.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,19 @@ If you run into trouble writing tests and need to debug one of them, you can do
6060

6161
Pro tip: If any of your breakpoints are in code run by multiple tests, and you run the whole test file, you'll land on those breakpoints over and over again, in the middle of tests you don't care about. To avoid this, replace the test's initial `it` or `test` with `it.only` or `test.only`. That way, when you hit a breakpoint, you'll know you got there are part of the buggy test.
6262

63+
## Debug Build Flags
64+
65+
Throughout the codebase, you will find debug flags like `IS_DEBUG_BUILD` guarding various code sections.
66+
These flags serve two purposes:
67+
68+
1. They enable us to remove debug code for our production browser bundles.
69+
2. Enable users to tree-shake Sentry debug code for their production builds.
70+
71+
These debug flags need to be declared in each package individually and must not be imported across package boundaries, because some build tools have trouble tree-shaking imported guards.
72+
As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder.
73+
The `flags.ts` file will contain "magic strings" like `__SENTRY_DEBUG__` that may get replaced with actual values during our, or the user's build process.
74+
Take care when introducing new flags - they must not throw if they are not replaced.
75+
6376
## Linting
6477

6578
Similar to building and testing, linting can be done in the project root or in individual packages by calling `yarn lint`.

packages/angular/src/flags.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/*
2+
* This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking
3+
* for users.
4+
*
5+
* Debug flags need to be declared in each package individually and must not be imported across package boundaries,
6+
* because some build tools have trouble tree-shaking imported guards.
7+
*
8+
* As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder.
9+
*
10+
* Debug flag files will contain "magic strings" like `__SENTRY_DEBUG__` that may get replaced with actual values during
11+
* our, or the user's build process. Take care when introducing new flags - they must not throw if they are not
12+
* replaced.
13+
*/
14+
15+
declare const __SENTRY_DEBUG__: boolean;
16+
17+
/** Flag that is true for debug builds, false otherwise. */
18+
export const IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__;

packages/angular/src/tracing.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@ import { AfterViewInit, Directive, Injectable, Input, NgModule, OnDestroy, OnIni
22
import { Event, NavigationEnd, NavigationStart, Router } from '@angular/router';
33
import { getCurrentHub } from '@sentry/browser';
44
import { Span, Transaction, TransactionContext } from '@sentry/types';
5-
import { getGlobalObject, isDebugBuild, logger, stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils';
5+
import { getGlobalObject, logger, stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils';
66
import { Observable, Subscription } from 'rxjs';
77
import { filter, tap } from 'rxjs/operators';
88

99
import { ANGULAR_INIT_OP, ANGULAR_OP, ANGULAR_ROUTING_OP } from './constants';
10+
import { IS_DEBUG_BUILD } from './flags';
1011
import { runOutsideAngular } from './zone';
1112

1213
let instrumentationInitialized: boolean;
@@ -63,7 +64,7 @@ export class TraceService implements OnDestroy {
6364
filter(event => event instanceof NavigationStart),
6465
tap(event => {
6566
if (!instrumentationInitialized) {
66-
isDebugBuild() &&
67+
IS_DEBUG_BUILD &&
6768
logger.error('Angular integration has tracing enabled, but Tracing integration is not configured');
6869
return;
6970
}

packages/browser/src/client.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { BaseClient, Scope, SDK_VERSION } from '@sentry/core';
22
import { Event, EventHint } from '@sentry/types';
3-
import { getGlobalObject, isDebugBuild, logger } from '@sentry/utils';
3+
import { getGlobalObject, logger } from '@sentry/utils';
44

55
import { BrowserBackend, BrowserOptions } from './backend';
6+
import { IS_DEBUG_BUILD } from './flags';
67
import { injectReportDialog, ReportDialogOptions } from './helpers';
78
import { Breadcrumbs } from './integrations';
89

@@ -47,7 +48,7 @@ export class BrowserClient extends BaseClient<BrowserBackend, BrowserOptions> {
4748
}
4849

4950
if (!this._isEnabled()) {
50-
isDebugBuild() && logger.error('Trying to call showReportDialog with Sentry Client disabled');
51+
IS_DEBUG_BUILD && logger.error('Trying to call showReportDialog with Sentry Client disabled');
5152
return;
5253
}
5354

packages/browser/src/flags.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/*
2+
* This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking
3+
* for users.
4+
*
5+
* Debug flags need to be declared in each package individually and must not be imported across package boundaries,
6+
* because some build tools have trouble tree-shaking imported guards.
7+
*
8+
* As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder.
9+
*
10+
* Debug flag files will contain "magic strings" like `__SENTRY_DEBUG__` that may get replaced with actual values during
11+
* our, or the user's build process. Take care when introducing new flags - they must not throw if they are not
12+
* replaced.
13+
*/
14+
15+
declare const __SENTRY_DEBUG__: boolean;
16+
17+
/** Flag that is true for debug builds, false otherwise. */
18+
export const IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__;

packages/browser/src/helpers.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@ import {
66
addNonEnumerableProperty,
77
getGlobalObject,
88
getOriginalFunction,
9-
isDebugBuild,
109
logger,
1110
markFunctionWrapped,
1211
} from '@sentry/utils';
1312

13+
import { IS_DEBUG_BUILD } from './flags';
14+
1415
const global = getGlobalObject<Window>();
1516
let ignoreOnError: number = 0;
1617

@@ -192,12 +193,12 @@ export function injectReportDialog(options: ReportDialogOptions = {}): void {
192193
}
193194

194195
if (!options.eventId) {
195-
isDebugBuild() && logger.error('Missing eventId option in showReportDialog call');
196+
IS_DEBUG_BUILD && logger.error('Missing eventId option in showReportDialog call');
196197
return;
197198
}
198199

199200
if (!options.dsn) {
200-
isDebugBuild() && logger.error('Missing dsn option in showReportDialog call');
201+
IS_DEBUG_BUILD && logger.error('Missing dsn option in showReportDialog call');
201202
return;
202203
}
203204

packages/browser/src/integrations/dedupe.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';
2-
import { isDebugBuild, logger } from '@sentry/utils';
2+
import { logger } from '@sentry/utils';
3+
4+
import { IS_DEBUG_BUILD } from '../flags';
35

46
/** Deduplication filter */
57
export class Dedupe implements Integration {
@@ -28,7 +30,7 @@ export class Dedupe implements Integration {
2830
// Juuust in case something goes wrong
2931
try {
3032
if (_shouldDropEvent(currentEvent, self._previousEvent)) {
31-
isDebugBuild() && logger.warn('Event dropped due to being a duplicate of previously captured event.');
33+
IS_DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');
3234
return null;
3335
}
3436
} catch (_oO) {

packages/browser/src/integrations/globalhandlers.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ import {
55
addExceptionMechanism,
66
addInstrumentationHandler,
77
getLocationHref,
8-
isDebugBuild,
98
isErrorEvent,
109
isPrimitive,
1110
isString,
1211
logger,
1312
} from '@sentry/utils';
1413

1514
import { eventFromUnknownInput } from '../eventbuilder';
15+
import { IS_DEBUG_BUILD } from '../flags';
1616
import { shouldIgnoreOnError } from '../helpers';
1717

1818
type GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';
@@ -237,7 +237,7 @@ function _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column
237237
}
238238

239239
function globalHandlerLog(type: string): void {
240-
isDebugBuild() && logger.log(`Global Handler attached: ${type}`);
240+
IS_DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);
241241
}
242242

243243
function addMechanismAndCapture(hub: Hub, error: EventHint['originalException'], event: Event, type: string): void {

packages/browser/src/sdk.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { getCurrentHub, initAndBind, Integrations as CoreIntegrations } from '@sentry/core';
22
import { Hub } from '@sentry/types';
3-
import { addInstrumentationHandler, getGlobalObject, isDebugBuild, logger, resolvedSyncPromise } from '@sentry/utils';
3+
import { addInstrumentationHandler, getGlobalObject, logger, resolvedSyncPromise } from '@sentry/utils';
44

55
import { BrowserOptions } from './backend';
66
import { BrowserClient } from './client';
7+
import { IS_DEBUG_BUILD } from './flags';
78
import { ReportDialogOptions, wrap as internalWrap } from './helpers';
89
import { Breadcrumbs, Dedupe, GlobalHandlers, LinkedErrors, TryCatch, UserAgent } from './integrations';
910

@@ -162,7 +163,7 @@ export function flush(timeout?: number): PromiseLike<boolean> {
162163
if (client) {
163164
return client.flush(timeout);
164165
}
165-
isDebugBuild() && logger.warn('Cannot flush events. No client defined.');
166+
IS_DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');
166167
return resolvedSyncPromise(false);
167168
}
168169

@@ -179,7 +180,7 @@ export function close(timeout?: number): PromiseLike<boolean> {
179180
if (client) {
180181
return client.close(timeout);
181182
}
182-
isDebugBuild() && logger.warn('Cannot flush events and disable SDK. No client defined.');
183+
IS_DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');
183184
return resolvedSyncPromise(false);
184185
}
185186

@@ -208,7 +209,7 @@ function startSessionTracking(): void {
208209
const document = window.document;
209210

210211
if (typeof document === 'undefined') {
211-
isDebugBuild() && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
212+
IS_DEBUG_BUILD && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
212213
return;
213214
}
214215

packages/browser/src/transports/base.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import {
2323
dsnToString,
2424
eventStatusFromHttpCode,
2525
getGlobalObject,
26-
isDebugBuild,
2726
isRateLimited,
2827
logger,
2928
makePromiseBuffer,
@@ -33,6 +32,7 @@ import {
3332
updateRateLimits,
3433
} from '@sentry/utils';
3534

35+
import { IS_DEBUG_BUILD } from '../flags';
3636
import { sendReport } from './utils';
3737

3838
function requestTypeToCategory(ty: SentryRequestType): string {
@@ -108,7 +108,7 @@ export abstract class BaseTransport implements Transport {
108108
// A correct type for map-based implementation if we want to go that route
109109
// would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>`
110110
const key = `${requestTypeToCategory(category)}:${reason}`;
111-
isDebugBuild() && logger.log(`Adding outcome: ${key}`);
111+
IS_DEBUG_BUILD && logger.log(`Adding outcome: ${key}`);
112112
this._outcomes[key] = (this._outcomes[key] ?? 0) + 1;
113113
}
114114

@@ -125,11 +125,11 @@ export abstract class BaseTransport implements Transport {
125125

126126
// Nothing to send
127127
if (!Object.keys(outcomes).length) {
128-
isDebugBuild() && logger.log('No outcomes to flush');
128+
IS_DEBUG_BUILD && logger.log('No outcomes to flush');
129129
return;
130130
}
131131

132-
isDebugBuild() && logger.log(`Flushing outcomes:\n${JSON.stringify(outcomes, null, 2)}`);
132+
IS_DEBUG_BUILD && logger.log(`Flushing outcomes:\n${JSON.stringify(outcomes, null, 2)}`);
133133

134134
const url = getEnvelopeEndpointWithUrlEncodedAuth(this._api.dsn, this._api.tunnel);
135135

@@ -147,7 +147,7 @@ export abstract class BaseTransport implements Transport {
147147
try {
148148
sendReport(url, serializeEnvelope(envelope));
149149
} catch (e) {
150-
isDebugBuild() && logger.error(e);
150+
IS_DEBUG_BUILD && logger.error(e);
151151
}
152152
}
153153

@@ -172,7 +172,7 @@ export abstract class BaseTransport implements Transport {
172172
this._rateLimits = updateRateLimits(this._rateLimits, headers);
173173
// eslint-disable-next-line deprecation/deprecation
174174
if (this._isRateLimited(requestType)) {
175-
isDebugBuild() &&
175+
IS_DEBUG_BUILD &&
176176
// eslint-disable-next-line deprecation/deprecation
177177
logger.warn(`Too many ${requestType} requests, backing off until: ${this._disabledUntil(requestType)}`);
178178
}

packages/browser/src/transports/utils.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
import { forget, getGlobalObject, isDebugBuild, isNativeFetch, logger, supportsFetch } from '@sentry/utils';
1+
import { forget, getGlobalObject, isNativeFetch, logger, supportsFetch } from '@sentry/utils';
2+
3+
import { IS_DEBUG_BUILD } from '../flags';
24

35
const global = getGlobalObject<Window>();
46
let cachedFetchImpl: FetchImpl;
@@ -69,7 +71,7 @@ export function getNativeFetchImplementation(): FetchImpl {
6971
}
7072
document.head.removeChild(sandbox);
7173
} catch (e) {
72-
isDebugBuild() &&
74+
IS_DEBUG_BUILD &&
7375
logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);
7476
}
7577
}

packages/core/src/basebackend.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { Event, EventHint, Options, Session, Severity, Transport } from '@sentry/types';
2-
import { isDebugBuild, logger, SentryError } from '@sentry/utils';
2+
import { logger, SentryError } from '@sentry/utils';
33

44
import { initAPIDetails } from './api';
5+
import { IS_DEBUG_BUILD } from './flags';
56
import { createEventEnvelope, createSessionEnvelope } from './request';
67
import { NewTransport } from './transports/base';
78
import { NoopTransport } from './transports/noop';
@@ -73,7 +74,7 @@ export abstract class BaseBackend<O extends Options> implements Backend {
7374
public constructor(options: O) {
7475
this._options = options;
7576
if (!this._options.dsn) {
76-
isDebugBuild() && logger.warn('No DSN provided, backend will not do anything.');
77+
IS_DEBUG_BUILD && logger.warn('No DSN provided, backend will not do anything.');
7778
}
7879
this._transport = this._setupTransport();
7980
}
@@ -107,11 +108,11 @@ export abstract class BaseBackend<O extends Options> implements Backend {
107108
const api = initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel);
108109
const env = createEventEnvelope(event, api);
109110
void this._newTransport.send(env).then(null, reason => {
110-
isDebugBuild() && logger.error('Error while sending event:', reason);
111+
IS_DEBUG_BUILD && logger.error('Error while sending event:', reason);
111112
});
112113
} else {
113114
void this._transport.sendEvent(event).then(null, reason => {
114-
isDebugBuild() && logger.error('Error while sending event:', reason);
115+
IS_DEBUG_BUILD && logger.error('Error while sending event:', reason);
115116
});
116117
}
117118
}
@@ -121,7 +122,7 @@ export abstract class BaseBackend<O extends Options> implements Backend {
121122
*/
122123
public sendSession(session: Session): void {
123124
if (!this._transport.sendSession) {
124-
isDebugBuild() && logger.warn("Dropping session because custom transport doesn't implement sendSession");
125+
IS_DEBUG_BUILD && logger.warn("Dropping session because custom transport doesn't implement sendSession");
125126
return;
126127
}
127128

@@ -135,11 +136,11 @@ export abstract class BaseBackend<O extends Options> implements Backend {
135136
const api = initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel);
136137
const [env] = createSessionEnvelope(session, api);
137138
void this._newTransport.send(env).then(null, reason => {
138-
isDebugBuild() && logger.error('Error while sending session:', reason);
139+
IS_DEBUG_BUILD && logger.error('Error while sending session:', reason);
139140
});
140141
} else {
141142
void this._transport.sendSession(session).then(null, reason => {
142-
isDebugBuild() && logger.error('Error while sending session:', reason);
143+
IS_DEBUG_BUILD && logger.error('Error while sending session:', reason);
143144
});
144145
}
145146
}

0 commit comments

Comments
 (0)