Skip to content

Commit 1d15d6e

Browse files
committed
Use GLOBAL_OBJ and WINDOW rather than getGlobalObject
1 parent a5bfa80 commit 1d15d6e

Some content is hidden

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

50 files changed

+275
-342
lines changed

Diff for: packages/angular/src/tracing.ts

+3-5
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { AfterViewInit, Directive, Injectable, Input, NgModule, OnDestroy, OnIni
33
import { ActivatedRouteSnapshot, Event, NavigationEnd, NavigationStart, ResolveEnd, Router } from '@angular/router';
44
import { getCurrentHub } from '@sentry/browser';
55
import { Span, Transaction, TransactionContext } from '@sentry/types';
6-
import { getGlobalObject, logger, stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils';
6+
import { logger, stripUrlQueryAndFragment, timestampWithMs, WINDOW } from '@sentry/utils';
77
import { Observable, Subscription } from 'rxjs';
88
import { filter, tap } from 'rxjs/operators';
99

@@ -15,8 +15,6 @@ let instrumentationInitialized: boolean;
1515
let stashedStartTransaction: (context: TransactionContext) => Transaction | undefined;
1616
let stashedStartTransactionOnLocationChange: boolean;
1717

18-
const global = getGlobalObject<Window>();
19-
2018
/**
2119
* Creates routing instrumentation for Angular Router.
2220
*/
@@ -29,9 +27,9 @@ export function routingInstrumentation(
2927
stashedStartTransaction = customStartTransaction;
3028
stashedStartTransactionOnLocationChange = startTransactionOnLocationChange;
3129

32-
if (startTransactionOnPageLoad && global && global.location) {
30+
if (startTransactionOnPageLoad && WINDOW && WINDOW.location) {
3331
customStartTransaction({
34-
name: global.location.pathname,
32+
name: WINDOW.location.pathname,
3533
op: 'pageload',
3634
metadata: { source: 'url' },
3735
});

Diff for: packages/browser/src/client.ts

+7-10
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,16 @@ import {
44
createClientReportEnvelope,
55
dsnToString,
66
getEventDescription,
7-
getGlobalObject,
87
logger,
98
serializeEnvelope,
9+
WINDOW,
1010
} from '@sentry/utils';
1111

1212
import { eventFromException, eventFromMessage } from './eventbuilder';
1313
import { Breadcrumbs } from './integrations';
1414
import { BREADCRUMB_INTEGRATION_ID } from './integrations/breadcrumbs';
1515
import { BrowserTransportOptions } from './transports/types';
1616

17-
const globalObject = getGlobalObject<Window>();
18-
1917
export interface BaseBrowserOptions {
2018
/**
2119
* A pattern for error URLs which should exclusively be sent to Sentry.
@@ -71,9 +69,9 @@ export class BrowserClient extends BaseClient<BrowserClientOptions> {
7169

7270
super(options);
7371

74-
if (options.sendClientReports && globalObject.document) {
75-
globalObject.document.addEventListener('visibilitychange', () => {
76-
if (globalObject.document.visibilityState === 'hidden') {
72+
if (options.sendClientReports && WINDOW.document) {
73+
WINDOW.document.addEventListener('visibilitychange', () => {
74+
if (WINDOW.document.visibilityState === 'hidden') {
7775
this._flushOutcomes();
7876
}
7977
});
@@ -164,13 +162,12 @@ export class BrowserClient extends BaseClient<BrowserClientOptions> {
164162
const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));
165163

166164
try {
167-
const global = getGlobalObject<Window>();
168-
const isRealNavigator = Object.prototype.toString.call(global && global.navigator) === '[object Navigator]';
169-
const hasSendBeacon = isRealNavigator && typeof global.navigator.sendBeacon === 'function';
165+
const isRealNavigator = Object.prototype.toString.call(WINDOW && WINDOW.navigator) === '[object Navigator]';
166+
const hasSendBeacon = isRealNavigator && typeof WINDOW.navigator.sendBeacon === 'function';
170167
// Make sure beacon is not used if user configures custom transport options
171168
if (hasSendBeacon && !this._options.transportOptions) {
172169
// Prevent illegal invocations - https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch
173-
const sendBeacon = global.navigator.sendBeacon.bind(global.navigator);
170+
const sendBeacon = WINDOW.navigator.sendBeacon.bind(WINDOW.navigator);
174171
sendBeacon(url, serializeEnvelope(envelope));
175172
} else {
176173
// If beacon is not supported or if they are using the tunnel option

Diff for: packages/browser/src/index.ts

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
export * from './exports';
22

33
import { Integrations as CoreIntegrations } from '@sentry/core';
4-
import { getGlobalObject } from '@sentry/utils';
4+
import { WINDOW } from '@sentry/utils';
55

66
import * as BrowserIntegrations from './integrations';
77

88
let windowIntegrations = {};
99

1010
// This block is needed to add compatibility with the integrations packages when used with a CDN
11-
const _window = getGlobalObject<Window>();
12-
if (_window.Sentry && _window.Sentry.Integrations) {
13-
windowIntegrations = _window.Sentry.Integrations;
11+
if (WINDOW.Sentry && WINDOW.Sentry.Integrations) {
12+
windowIntegrations = WINDOW.Sentry.Integrations;
1413
}
1514

1615
const INTEGRATIONS = {

Diff for: packages/browser/src/integrations/breadcrumbs.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ import { getCurrentHub } from '@sentry/core';
44
import { Integration } from '@sentry/types';
55
import {
66
addInstrumentationHandler,
7-
getGlobalObject,
87
htmlTreeAsString,
98
parseUrl,
109
safeJoin,
1110
severityLevelFromString,
11+
WINDOW,
1212
} from '@sentry/utils';
1313

1414
/** JSDoc */
@@ -245,10 +245,9 @@ function _fetchBreadcrumb(handlerData: { [key: string]: any }): void {
245245
*/
246246
// eslint-disable-next-line @typescript-eslint/no-explicit-any
247247
function _historyBreadcrumb(handlerData: { [key: string]: any }): void {
248-
const global = getGlobalObject<Window>();
249248
let from = handlerData.from;
250249
let to = handlerData.to;
251-
const parsedLoc = parseUrl(global.location.href);
250+
const parsedLoc = parseUrl(WINDOW.location.href);
252251
let parsedFrom = parseUrl(from);
253252
const parsedTo = parseUrl(to);
254253

Diff for: packages/browser/src/integrations/httpcontext.ts

+5-7
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';
22
import { Event, Integration } from '@sentry/types';
3-
import { getGlobalObject } from '@sentry/utils';
4-
5-
const global = getGlobalObject<Window>();
3+
import { WINDOW } from '@sentry/utils';
64

75
/** HttpContext integration collects information about HTTP request headers */
86
export class HttpContext implements Integration {
@@ -23,14 +21,14 @@ export class HttpContext implements Integration {
2321
addGlobalEventProcessor((event: Event) => {
2422
if (getCurrentHub().getIntegration(HttpContext)) {
2523
// if none of the information we want exists, don't bother
26-
if (!global.navigator && !global.location && !global.document) {
24+
if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {
2725
return event;
2826
}
2927

3028
// grab as much info as exists and add it to the event
31-
const url = (event.request && event.request.url) || (global.location && global.location.href);
32-
const { referrer } = global.document || {};
33-
const { userAgent } = global.navigator || {};
29+
const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);
30+
const { referrer } = WINDOW.document || {};
31+
const { userAgent } = WINDOW.navigator || {};
3432

3533
const headers = {
3634
...(event.request && event.request.headers),

Diff for: packages/browser/src/integrations/trycatch.ts

+6-8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Integration, WrappedFunction } from '@sentry/types';
2-
import { fill, getFunctionName, getGlobalObject, getOriginalFunction } from '@sentry/utils';
2+
import { fill, getFunctionName, getOriginalFunction, WINDOW } from '@sentry/utils';
33

44
import { wrap } from '../helpers';
55

@@ -80,21 +80,19 @@ export class TryCatch implements Integration {
8080
* and provide better metadata.
8181
*/
8282
public setupOnce(): void {
83-
const global = getGlobalObject();
84-
8583
if (this._options.setTimeout) {
86-
fill(global, 'setTimeout', _wrapTimeFunction);
84+
fill(WINDOW, 'setTimeout', _wrapTimeFunction);
8785
}
8886

8987
if (this._options.setInterval) {
90-
fill(global, 'setInterval', _wrapTimeFunction);
88+
fill(WINDOW, 'setInterval', _wrapTimeFunction);
9189
}
9290

9391
if (this._options.requestAnimationFrame) {
94-
fill(global, 'requestAnimationFrame', _wrapRAF);
92+
fill(WINDOW, 'requestAnimationFrame', _wrapRAF);
9593
}
9694

97-
if (this._options.XMLHttpRequest && 'XMLHttpRequest' in global) {
95+
if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {
9896
fill(XMLHttpRequest.prototype, 'send', _wrapXHR);
9997
}
10098

@@ -185,7 +183,7 @@ function _wrapXHR(originalSend: () => void): () => void {
185183
/** JSDoc */
186184
function _wrapEventTarget(target: string): void {
187185
// eslint-disable-next-line @typescript-eslint/no-explicit-any
188-
const global = getGlobalObject() as { [key: string]: any };
186+
const global = WINDOW as { [key: string]: any };
189187
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
190188
const proto = global[target] && global[target].prototype;
191189

Diff for: packages/browser/src/sdk.ts

+7-12
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ import {
88
} from '@sentry/core';
99
import {
1010
addInstrumentationHandler,
11-
getGlobalObject,
1211
logger,
1312
resolvedSyncPromise,
1413
stackParserFromStackParserOptions,
1514
supportsFetch,
15+
WINDOW,
1616
} from '@sentry/utils';
1717

1818
import { BrowserClient, BrowserClientOptions, BrowserOptions } from './client';
@@ -94,10 +94,9 @@ export function init(options: BrowserOptions = {}): void {
9494
options.defaultIntegrations = defaultIntegrations;
9595
}
9696
if (options.release === undefined) {
97-
const window = getGlobalObject<Window>();
9897
// This supports the variable that sentry-webpack-plugin injects
99-
if (window.SENTRY_RELEASE && window.SENTRY_RELEASE.id) {
100-
options.release = window.SENTRY_RELEASE.id;
98+
if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {
99+
options.release = WINDOW.SENTRY_RELEASE.id;
101100
}
102101
}
103102
if (options.autoSessionTracking === undefined) {
@@ -128,8 +127,7 @@ export function init(options: BrowserOptions = {}): void {
128127
*/
129128
export function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = getCurrentHub()): void {
130129
// doesn't work without a document (React Native)
131-
const global = getGlobalObject<Window>();
132-
if (!global.document) {
130+
if (!WINDOW.document) {
133131
__DEBUG_BUILD__ && logger.error('Global document not defined in showReportDialog call');
134132
return;
135133
}
@@ -152,7 +150,7 @@ export function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = g
152150
options.eventId = hub.lastEventId();
153151
}
154152

155-
const script = global.document.createElement('script');
153+
const script = WINDOW.document.createElement('script');
156154
script.async = true;
157155
script.src = getReportDialogEndpoint(dsn, options);
158156

@@ -161,7 +159,7 @@ export function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = g
161159
script.onload = options.onLoad;
162160
}
163161

164-
const injectionPoint = global.document.head || global.document.body;
162+
const injectionPoint = WINDOW.document.head || WINDOW.document.body;
165163
if (injectionPoint) {
166164
injectionPoint.appendChild(script);
167165
} else {
@@ -249,10 +247,7 @@ function startSessionOnHub(hub: Hub): void {
249247
* Enable automatic Session Tracking for the initial page load.
250248
*/
251249
function startSessionTracking(): void {
252-
const window = getGlobalObject<Window>();
253-
const document = window.document;
254-
255-
if (typeof document === 'undefined') {
250+
if (typeof WINDOW.document === 'undefined') {
256251
__DEBUG_BUILD__ &&
257252
logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
258253
return;

Diff for: packages/browser/src/transports/utils.ts

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

3-
const global = getGlobalObject<Window>();
43
let cachedFetchImpl: FetchImpl;
54

65
export type FetchImpl = typeof fetch;
@@ -51,12 +50,12 @@ export function getNativeFetchImplementation(): FetchImpl {
5150
/* eslint-disable @typescript-eslint/unbound-method */
5251

5352
// Fast path to avoid DOM I/O
54-
if (isNativeFetch(global.fetch)) {
55-
return (cachedFetchImpl = global.fetch.bind(global));
53+
if (isNativeFetch(WINDOW.fetch)) {
54+
return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));
5655
}
5756

58-
const document = global.document;
59-
let fetchImpl = global.fetch;
57+
const document = WINDOW.document;
58+
let fetchImpl = WINDOW.fetch;
6059
// eslint-disable-next-line deprecation/deprecation
6160
if (document && typeof document.createElement === 'function') {
6261
try {
@@ -74,6 +73,6 @@ export function getNativeFetchImplementation(): FetchImpl {
7473
}
7574
}
7675

77-
return (cachedFetchImpl = fetchImpl.bind(global));
76+
return (cachedFetchImpl = fetchImpl.bind(WINDOW));
7877
/* eslint-enable @typescript-eslint/unbound-method */
7978
}

Diff for: packages/core/test/lib/base.test.ts

+11-13
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,18 @@ jest.mock('@sentry/utils', () => {
2222
uuid4(): string {
2323
return '42';
2424
},
25-
getGlobalObject(): any {
26-
return {
27-
console: {
28-
log(): void {
29-
// no-empty
30-
},
31-
warn(): void {
32-
// no-empty
33-
},
34-
error(): void {
35-
// no-empty
36-
},
25+
GLOBAL_OBJ: {
26+
console: {
27+
log(): void {
28+
// no-empty
3729
},
38-
};
30+
warn(): void {
31+
// no-empty
32+
},
33+
error(): void {
34+
// no-empty
35+
},
36+
},
3937
},
4038
consoleSandbox(cb: () => any): any {
4139
return cb();

Diff for: packages/core/test/lib/hint.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { captureEvent, configureScope } from '@sentry/hub';
2-
import { getGlobalObject } from '@sentry/utils';
2+
import { GLOBAL_OBJ } from '@sentry/utils';
33

44
import { initAndBind } from '../../src/sdk';
55
import { getDefaultTestClientOptions, TestClient } from '../mocks/client';
@@ -16,7 +16,7 @@ describe('Hint', () => {
1616

1717
afterEach(() => {
1818
jest.clearAllMocks();
19-
delete getGlobalObject().__SENTRY__;
19+
delete GLOBAL_OBJ.__SENTRY__;
2020
});
2121

2222
describe('attachments', () => {

Diff for: packages/ember/addon/index.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,11 @@ import { macroCondition, isDevelopingApp, getOwnConfig } from '@embroider/macros
44
import { next } from '@ember/runloop';
55
import { assert, warn } from '@ember/debug';
66
import Ember from 'ember';
7-
import { timestampWithMs } from '@sentry/utils';
7+
import { timestampWithMs, GLOBAL_OBJ } from '@sentry/utils';
88
import { GlobalConfig, OwnConfig } from './types';
9-
import { getGlobalObject } from '@sentry/utils';
109

1110
function _getSentryInitConfig() {
12-
const _global = getGlobalObject<GlobalConfig>();
11+
const _global = GLOBAL_OBJ as typeof GLOBAL_OBJ & GlobalConfig;
1312
_global.__sentryEmberConfig = _global.__sentryEmberConfig ?? {};
1413
return _global.__sentryEmberConfig;
1514
}

Diff for: packages/ember/addon/instance-initializers/sentry-performance.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@ import { ExtendedBackburner } from '@sentry/ember/runloop';
66
import { Span, Transaction, Integration } from '@sentry/types';
77
import { EmberRunQueues } from '@ember/runloop/-private/types';
88
import { getActiveTransaction } from '..';
9-
import { browserPerformanceTimeOrigin, getGlobalObject, timestampWithMs } from '@sentry/utils';
9+
import { browserPerformanceTimeOrigin, GLOBAL_OBJ, timestampWithMs } from '@sentry/utils';
1010
import { macroCondition, isTesting, getOwnConfig } from '@embroider/macros';
1111
import { EmberSentryConfig, GlobalConfig, OwnConfig } from '../types';
1212

1313
function getSentryConfig() {
14-
const _global = getGlobalObject<GlobalConfig>();
14+
const _global = GLOBAL_OBJ as typeof GLOBAL_OBJ & GlobalConfig;
1515
_global.__sentryEmberConfig = _global.__sentryEmberConfig ?? {};
1616
const environmentConfig = getOwnConfig<OwnConfig>().sentryConfig;
1717
if (!environmentConfig.sentry) {

0 commit comments

Comments
 (0)