Skip to content

Commit 971ed96

Browse files
authored
ref(tracing): Remove getGlobalObject() usage from @sentry/tracing (#5885)
1 parent 49cdb28 commit 971ed96

File tree

10 files changed

+34
-44
lines changed

10 files changed

+34
-44
lines changed

packages/tracing/src/browser/backgroundtab.ts

+4-6
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
1-
import { getGlobalObject, logger } from '@sentry/utils';
1+
import { logger, WINDOW } from '@sentry/utils';
22

33
import { IdleTransaction } from '../idletransaction';
44
import { SpanStatusType } from '../span';
55
import { getActiveTransaction } from '../utils';
66

7-
const global = getGlobalObject<Window>();
8-
97
/**
108
* Add a listener that cancels and finishes a transaction when the global
119
* document is hidden.
1210
*/
1311
export function registerBackgroundTabDetection(): void {
14-
if (global && global.document) {
15-
global.document.addEventListener('visibilitychange', () => {
12+
if (WINDOW && WINDOW.document) {
13+
WINDOW.document.addEventListener('visibilitychange', () => {
1614
const activeTransaction = getActiveTransaction() as IdleTransaction;
17-
if (global.document.hidden && activeTransaction) {
15+
if (WINDOW.document.hidden && activeTransaction) {
1816
const statusType: SpanStatusType = 'cancelled';
1917

2018
__DEBUG_BUILD__ &&

packages/tracing/src/browser/browsertracing.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* eslint-disable max-lines */
22
import { Hub } from '@sentry/core';
33
import { EventProcessor, Integration, Transaction, TransactionContext } from '@sentry/types';
4-
import { baggageHeaderToDynamicSamplingContext, getDomElement, getGlobalObject, logger } from '@sentry/utils';
4+
import { baggageHeaderToDynamicSamplingContext, getDomElement, logger, WINDOW } from '@sentry/utils';
55

66
import { startIdleTransaction } from '../hubextensions';
77
import { DEFAULT_FINAL_TIMEOUT, DEFAULT_HEARTBEAT_INTERVAL, DEFAULT_IDLE_TIMEOUT } from '../idletransaction';
@@ -265,7 +265,7 @@ export class BrowserTracing implements Integration {
265265
__DEBUG_BUILD__ && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);
266266

267267
const hub = this._getCurrentHub();
268-
const { location } = getGlobalObject() as WindowOrWorkerGlobalScope & { location: Location };
268+
const { location } = WINDOW;
269269

270270
const idleTransaction = startIdleTransaction(
271271
hub,

packages/tracing/src/browser/metrics/index.ts

+6-8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* eslint-disable max-lines */
22
import { Measurements } from '@sentry/types';
3-
import { browserPerformanceTimeOrigin, getGlobalObject, htmlTreeAsString, logger } from '@sentry/utils';
3+
import { browserPerformanceTimeOrigin, htmlTreeAsString, logger, WINDOW } from '@sentry/utils';
44

55
import { IdleTransaction } from '../../idletransaction';
66
import { Transaction } from '../../transaction';
@@ -13,10 +13,8 @@ import { observe, PerformanceEntryHandler } from '../web-vitals/lib/observe';
1313
import { NavigatorDeviceMemory, NavigatorNetworkInformation } from '../web-vitals/types';
1414
import { _startChild, isMeasurementValue } from './utils';
1515

16-
const global = getGlobalObject<Window>();
17-
1816
function getBrowserPerformanceAPI(): Performance | undefined {
19-
return global && global.addEventListener && global.performance;
17+
return WINDOW && WINDOW.addEventListener && WINDOW.performance;
2018
}
2119

2220
let _performanceCursor: number = 0;
@@ -32,7 +30,7 @@ export function startTrackingWebVitals(reportAllChanges: boolean = false): void
3230
const performance = getBrowserPerformanceAPI();
3331
if (performance && browserPerformanceTimeOrigin) {
3432
if (performance.mark) {
35-
global.performance.mark('sentry-tracing-init');
33+
WINDOW.performance.mark('sentry-tracing-init');
3634
}
3735
_trackCLS();
3836
_trackLCP(reportAllChanges);
@@ -112,7 +110,7 @@ function _trackFID(): void {
112110
/** Add performance related spans to a transaction */
113111
export function addPerformanceEntries(transaction: Transaction): void {
114112
const performance = getBrowserPerformanceAPI();
115-
if (!performance || !global.performance.getEntries || !browserPerformanceTimeOrigin) {
113+
if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {
116114
// Gatekeeper if performance API not available
117115
return;
118116
}
@@ -162,7 +160,7 @@ export function addPerformanceEntries(transaction: Transaction): void {
162160
break;
163161
}
164162
case 'resource': {
165-
const resourceName = (entry.name as string).replace(global.location.origin, '');
163+
const resourceName = (entry.name as string).replace(WINDOW.location.origin, '');
166164
_addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);
167165
break;
168166
}
@@ -376,7 +374,7 @@ export function _addResourceSpans(
376374
* Capture the information of the user agent.
377375
*/
378376
function _trackNavigator(transaction: Transaction): void {
379-
const navigator = global.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);
377+
const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);
380378
if (!navigator) {
381379
return;
382380
}

packages/tracing/src/browser/router.ts

+5-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import { Transaction, TransactionContext } from '@sentry/types';
2-
import { addInstrumentationHandler, getGlobalObject, logger } from '@sentry/utils';
3-
4-
const global = getGlobalObject<Window>();
2+
import { addInstrumentationHandler, logger, WINDOW } from '@sentry/utils';
53

64
/**
75
* Default function implementing pageload and navigation transactions
@@ -11,17 +9,17 @@ export function instrumentRoutingWithDefaults<T extends Transaction>(
119
startTransactionOnPageLoad: boolean = true,
1210
startTransactionOnLocationChange: boolean = true,
1311
): void {
14-
if (!global || !global.location) {
12+
if (!WINDOW || !WINDOW.location) {
1513
__DEBUG_BUILD__ && logger.warn('Could not initialize routing instrumentation due to invalid location');
1614
return;
1715
}
1816

19-
let startingUrl: string | undefined = global.location.href;
17+
let startingUrl: string | undefined = WINDOW.location.href;
2018

2119
let activeTransaction: T | undefined;
2220
if (startTransactionOnPageLoad) {
2321
activeTransaction = customStartTransaction({
24-
name: global.location.pathname,
22+
name: WINDOW.location.pathname,
2523
op: 'pageload',
2624
metadata: { source: 'url' },
2725
});
@@ -51,7 +49,7 @@ export function instrumentRoutingWithDefaults<T extends Transaction>(
5149
activeTransaction.finish();
5250
}
5351
activeTransaction = customStartTransaction({
54-
name: global.location.pathname,
52+
name: WINDOW.location.pathname,
5553
op: 'navigation',
5654
metadata: { source: 'url' },
5755
});

packages/tracing/src/browser/web-vitals/lib/getVisibilityWatcher.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@
1414
* limitations under the License.
1515
*/
1616

17-
import { getGlobalObject } from '@sentry/utils';
17+
import { WINDOW } from '@sentry/utils';
1818

1919
import { onHidden } from './onHidden';
2020

2121
let firstHiddenTime = -1;
2222

2323
const initHiddenTime = (): number => {
24-
return getGlobalObject<Window>().document.visibilityState === 'hidden' ? 0 : Infinity;
24+
return WINDOW.document.visibilityState === 'hidden' ? 0 : Infinity;
2525
};
2626

2727
const trackChanges = (): void => {

packages/tracing/src/browser/web-vitals/lib/onHidden.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,15 @@
1414
* limitations under the License.
1515
*/
1616

17-
import { getGlobalObject } from '@sentry/utils';
17+
import { WINDOW } from '@sentry/utils';
1818

1919
export interface OnHiddenCallback {
2020
(event: Event): void;
2121
}
2222

2323
export const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {
2424
const onHiddenOrPageHide = (event: Event): void => {
25-
if (event.type === 'pagehide' || getGlobalObject<Window>().document.visibilityState === 'hidden') {
25+
if (event.type === 'pagehide' || WINDOW.document.visibilityState === 'hidden') {
2626
cb(event);
2727
if (once) {
2828
removeEventListener('visibilitychange', onHiddenOrPageHide, true);

packages/tracing/src/index.bundle.ts

+3-4
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export {
5353
export { SDK_VERSION } from '@sentry/browser';
5454

5555
import { Integrations as BrowserIntegrations } from '@sentry/browser';
56-
import { getGlobalObject } from '@sentry/utils';
56+
import { GLOBAL_OBJ } from '@sentry/utils';
5757

5858
import { BrowserTracing } from './browser';
5959
import { addExtensionMethods } from './hubextensions';
@@ -63,9 +63,8 @@ export { Span } from './span';
6363
let windowIntegrations = {};
6464

6565
// This block is needed to add compatibility with the integrations packages when used with a CDN
66-
const _window = getGlobalObject<Window>();
67-
if (_window.Sentry && _window.Sentry.Integrations) {
68-
windowIntegrations = _window.Sentry.Integrations;
66+
if (GLOBAL_OBJ.Sentry && GLOBAL_OBJ.Sentry.Integrations) {
67+
windowIntegrations = GLOBAL_OBJ.Sentry.Integrations;
6968
}
7069

7170
const INTEGRATIONS = {

packages/tracing/test/browser/browsertracing.test.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { BrowserClient } from '@sentry/browser';
22
import { Hub, makeMain } from '@sentry/core';
33
import type { BaseTransportOptions, ClientOptions, DsnComponents } from '@sentry/types';
4-
import { getGlobalObject, InstrumentHandlerCallback, InstrumentHandlerType } from '@sentry/utils';
4+
import { InstrumentHandlerCallback, InstrumentHandlerType, WINDOW } from '@sentry/utils';
55
import { JSDOM } from 'jsdom';
66

77
import { BrowserTracing, BrowserTracingOptions, getMetaContent } from '../../src/browser/browsertracing';
@@ -40,11 +40,11 @@ const warnSpy = jest.spyOn(logger, 'warn');
4040
beforeAll(() => {
4141
const dom = new JSDOM();
4242
// @ts-ignore need to override global document
43-
global.document = dom.window.document;
43+
WINDOW.document = dom.window.document;
4444
// @ts-ignore need to override global document
45-
global.window = dom.window;
45+
WINDOW.window = dom.window;
4646
// @ts-ignore need to override global document
47-
global.location = dom.window.location;
47+
WINDOW.location = dom.window.location;
4848
});
4949

5050
describe('BrowserTracing', () => {
@@ -508,7 +508,7 @@ describe('BrowserTracing', () => {
508508
};
509509

510510
it('extracts window.location/self.location for sampling context in pageload transactions', () => {
511-
getGlobalObject<Window>().location = dogParkLocation as any;
511+
WINDOW.location = dogParkLocation as any;
512512

513513
const tracesSampler = jest.fn();
514514
const options = getDefaultBrowserClientOptions({ tracesSampler });
@@ -525,7 +525,7 @@ describe('BrowserTracing', () => {
525525
});
526526

527527
it('extracts window.location/self.location for sampling context in navigation transactions', () => {
528-
getGlobalObject<Window>().location = dogParkLocation as any;
528+
WINDOW.location = dogParkLocation as any;
529529

530530
const tracesSampler = jest.fn();
531531
const options = getDefaultBrowserClientOptions({ tracesSampler });

packages/tracing/test/hub.test.ts

-2
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@ jest.spyOn(logger, 'warn');
2323
jest.spyOn(logger, 'log');
2424
jest.spyOn(utilsModule, 'isNodeEnv');
2525

26-
// we have to add things into the real global object (rather than mocking the return value of getGlobalObject) because
27-
// there are modules which call getGlobalObject as they load, which is seemingly too early for jest to intervene
2826
addDOMPropertiesToGlobal(['XMLHttpRequest', 'Event', 'location', 'document']);
2927

3028
describe('Hub', () => {

packages/tracing/test/testutils.ts

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { createTransport } from '@sentry/browser';
22
import { ClientOptions } from '@sentry/types';
3-
import { getGlobalObject, resolvedSyncPromise } from '@sentry/utils';
3+
import { GLOBAL_OBJ, resolvedSyncPromise } from '@sentry/utils';
44
import { JSDOM } from 'jsdom';
55

66
/**
@@ -13,14 +13,13 @@ import { JSDOM } from 'jsdom';
1313
* @param properties The names of the properties to add
1414
*/
1515
export function addDOMPropertiesToGlobal(properties: string[]): void {
16-
// we have to add things into the real global object (rather than mocking the return value of getGlobalObject)
17-
// because there are modules which call getGlobalObject as they load, which is too early for jest to intervene
16+
// we have to add things into the real global object
17+
// because there are modules which call GLOBAL_OBJ as they load, which is too early for jest to intervene
1818
const { window } = new JSDOM('', { url: 'http://dogs.are.great/' });
19-
const global = getGlobalObject<NodeJS.Global & Window>();
2019

2120
properties.forEach(prop => {
2221
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
23-
(global as any)[prop] = window[prop];
22+
(GLOBAL_OBJ as any)[prop] = window[prop];
2423
});
2524
}
2625

0 commit comments

Comments
 (0)