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

ref(browser): Remove getGlobalObject() usage from @sentry/browser #5884

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
17 changes: 7 additions & 10 deletions packages/browser/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,16 @@ import {
createClientReportEnvelope,
dsnToString,
getEventDescription,
getGlobalObject,
logger,
serializeEnvelope,
WINDOW,
} from '@sentry/utils';

import { eventFromException, eventFromMessage } from './eventbuilder';
import { Breadcrumbs } from './integrations';
import { BREADCRUMB_INTEGRATION_ID } from './integrations/breadcrumbs';
import { BrowserTransportOptions } from './transports/types';

const globalObject = getGlobalObject<Window>();

export interface BaseBrowserOptions {
/**
* A pattern for error URLs which should exclusively be sent to Sentry.
Expand Down Expand Up @@ -71,9 +69,9 @@ export class BrowserClient extends BaseClient<BrowserClientOptions> {

super(options);

if (options.sendClientReports && globalObject.document) {
globalObject.document.addEventListener('visibilitychange', () => {
if (globalObject.document.visibilityState === 'hidden') {
if (options.sendClientReports && WINDOW.document) {
WINDOW.document.addEventListener('visibilitychange', () => {
if (WINDOW.document.visibilityState === 'hidden') {
this._flushOutcomes();
}
});
Expand Down Expand Up @@ -164,13 +162,12 @@ export class BrowserClient extends BaseClient<BrowserClientOptions> {
const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));

try {
const global = getGlobalObject<Window>();
const isRealNavigator = Object.prototype.toString.call(global && global.navigator) === '[object Navigator]';
const hasSendBeacon = isRealNavigator && typeof global.navigator.sendBeacon === 'function';
const isRealNavigator = Object.prototype.toString.call(WINDOW && WINDOW.navigator) === '[object Navigator]';
const hasSendBeacon = isRealNavigator && typeof WINDOW.navigator.sendBeacon === 'function';
// Make sure beacon is not used if user configures custom transport options
if (hasSendBeacon && !this._options.transportOptions) {
// Prevent illegal invocations - https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch
const sendBeacon = global.navigator.sendBeacon.bind(global.navigator);
const sendBeacon = WINDOW.navigator.sendBeacon.bind(WINDOW.navigator);
sendBeacon(url, serializeEnvelope(envelope));
} else {
// If beacon is not supported or if they are using the tunnel option
Expand Down
7 changes: 3 additions & 4 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
export * from './exports';

import { Integrations as CoreIntegrations } from '@sentry/core';
import { getGlobalObject } from '@sentry/utils';
import { WINDOW } from '@sentry/utils';

import * as BrowserIntegrations from './integrations';

let windowIntegrations = {};

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

const INTEGRATIONS = {
Expand Down
5 changes: 2 additions & 3 deletions packages/browser/src/integrations/breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { getCurrentHub } from '@sentry/core';
import { Integration } from '@sentry/types';
import {
addInstrumentationHandler,
getGlobalObject,
htmlTreeAsString,
parseUrl,
safeJoin,
severityLevelFromString,
WINDOW,
} from '@sentry/utils';

/** JSDoc */
Expand Down Expand Up @@ -245,10 +245,9 @@ function _fetchBreadcrumb(handlerData: { [key: string]: any }): void {
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function _historyBreadcrumb(handlerData: { [key: string]: any }): void {
const global = getGlobalObject<Window>();
let from = handlerData.from;
let to = handlerData.to;
const parsedLoc = parseUrl(global.location.href);
const parsedLoc = parseUrl(WINDOW.location.href);
let parsedFrom = parseUrl(from);
const parsedTo = parseUrl(to);

Expand Down
12 changes: 5 additions & 7 deletions packages/browser/src/integrations/httpcontext.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';
import { Event, Integration } from '@sentry/types';
import { getGlobalObject } from '@sentry/utils';

const global = getGlobalObject<Window>();
import { WINDOW } from '@sentry/utils';

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

// grab as much info as exists and add it to the event
const url = (event.request && event.request.url) || (global.location && global.location.href);
const { referrer } = global.document || {};
const { userAgent } = global.navigator || {};
const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);
const { referrer } = WINDOW.document || {};
const { userAgent } = WINDOW.navigator || {};

const headers = {
...(event.request && event.request.headers),
Expand Down
14 changes: 6 additions & 8 deletions packages/browser/src/integrations/trycatch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Integration, WrappedFunction } from '@sentry/types';
import { fill, getFunctionName, getGlobalObject, getOriginalFunction } from '@sentry/utils';
import { fill, getFunctionName, getOriginalFunction, WINDOW } from '@sentry/utils';

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

Expand Down Expand Up @@ -80,21 +80,19 @@ export class TryCatch implements Integration {
* and provide better metadata.
*/
public setupOnce(): void {
const global = getGlobalObject();

if (this._options.setTimeout) {
fill(global, 'setTimeout', _wrapTimeFunction);
fill(WINDOW, 'setTimeout', _wrapTimeFunction);
}

if (this._options.setInterval) {
fill(global, 'setInterval', _wrapTimeFunction);
fill(WINDOW, 'setInterval', _wrapTimeFunction);
}

if (this._options.requestAnimationFrame) {
fill(global, 'requestAnimationFrame', _wrapRAF);
fill(WINDOW, 'requestAnimationFrame', _wrapRAF);
}

if (this._options.XMLHttpRequest && 'XMLHttpRequest' in global) {
if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {
fill(XMLHttpRequest.prototype, 'send', _wrapXHR);
}

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

Expand Down
19 changes: 7 additions & 12 deletions packages/browser/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import {
} from '@sentry/core';
import {
addInstrumentationHandler,
getGlobalObject,
logger,
resolvedSyncPromise,
stackParserFromStackParserOptions,
supportsFetch,
WINDOW,
} from '@sentry/utils';

import { BrowserClient, BrowserClientOptions, BrowserOptions } from './client';
Expand Down Expand Up @@ -94,10 +94,9 @@ export function init(options: BrowserOptions = {}): void {
options.defaultIntegrations = defaultIntegrations;
}
if (options.release === undefined) {
const window = getGlobalObject<Window>();
// This supports the variable that sentry-webpack-plugin injects
if (window.SENTRY_RELEASE && window.SENTRY_RELEASE.id) {
options.release = window.SENTRY_RELEASE.id;
if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {
options.release = WINDOW.SENTRY_RELEASE.id;
}
}
if (options.autoSessionTracking === undefined) {
Expand Down Expand Up @@ -128,8 +127,7 @@ export function init(options: BrowserOptions = {}): void {
*/
export function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = getCurrentHub()): void {
// doesn't work without a document (React Native)
const global = getGlobalObject<Window>();
if (!global.document) {
if (!WINDOW.document) {
__DEBUG_BUILD__ && logger.error('Global document not defined in showReportDialog call');
return;
}
Expand All @@ -152,7 +150,7 @@ export function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = g
options.eventId = hub.lastEventId();
}

const script = global.document.createElement('script');
const script = WINDOW.document.createElement('script');
script.async = true;
script.src = getReportDialogEndpoint(dsn, options);

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

const injectionPoint = global.document.head || global.document.body;
const injectionPoint = WINDOW.document.head || WINDOW.document.body;
if (injectionPoint) {
injectionPoint.appendChild(script);
} else {
Expand Down Expand Up @@ -249,10 +247,7 @@ function startSessionOnHub(hub: Hub): void {
* Enable automatic Session Tracking for the initial page load.
*/
function startSessionTracking(): void {
const window = getGlobalObject<Window>();
const document = window.document;

if (typeof document === 'undefined') {
if (typeof WINDOW.document === 'undefined') {
__DEBUG_BUILD__ &&
logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
return;
Expand Down
13 changes: 6 additions & 7 deletions packages/browser/src/transports/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { getGlobalObject, isNativeFetch, logger } from '@sentry/utils';
import { isNativeFetch, logger, WINDOW } from '@sentry/utils';

const global = getGlobalObject<Window>();
let cachedFetchImpl: FetchImpl;

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

// Fast path to avoid DOM I/O
if (isNativeFetch(global.fetch)) {
return (cachedFetchImpl = global.fetch.bind(global));
if (isNativeFetch(WINDOW.fetch)) {
return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));
}

const document = global.document;
let fetchImpl = global.fetch;
const document = WINDOW.document;
let fetchImpl = WINDOW.fetch;
// eslint-disable-next-line deprecation/deprecation
if (document && typeof document.createElement === 'function') {
try {
Expand All @@ -74,6 +73,6 @@ export function getNativeFetchImplementation(): FetchImpl {
}
}

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