UNPKG

@sentry/browser

Version:
260 lines (229 loc) 7.96 kB
import { inboundFiltersIntegration, functionToStringIntegration, dedupeIntegration, consoleSandbox, supportsFetch, logger, getIntegrationsToSetup, stackParserFromStackParserOptions, initAndBind, getCurrentScope, lastEventId, getReportDialogEndpoint, getLocationHref } from '@sentry/core'; import { BrowserClient } from './client.js'; import { DEBUG_BUILD } from './debug-build.js'; import { WINDOW } from './helpers.js'; import { breadcrumbsIntegration } from './integrations/breadcrumbs.js'; import { browserApiErrorsIntegration } from './integrations/browserapierrors.js'; import { browserSessionIntegration } from './integrations/browsersession.js'; import { globalHandlersIntegration } from './integrations/globalhandlers.js'; import { httpContextIntegration } from './integrations/httpcontext.js'; import { linkedErrorsIntegration } from './integrations/linkederrors.js'; import { defaultStackParser } from './stack-parsers.js'; import { makeFetchTransport } from './transports/fetch.js'; /** Get the default integrations for the browser SDK. */ function getDefaultIntegrations(_options) { /** * Note: Please make sure this stays in sync with Angular SDK, which re-exports * `getDefaultIntegrations` but with an adjusted set of integrations. */ return [ // TODO(v10): Replace with `eventFiltersIntegration` once we remove the deprecated `inboundFiltersIntegration` // eslint-disable-next-line deprecation/deprecation inboundFiltersIntegration(), functionToStringIntegration(), browserApiErrorsIntegration(), breadcrumbsIntegration(), globalHandlersIntegration(), linkedErrorsIntegration(), dedupeIntegration(), httpContextIntegration(), browserSessionIntegration(), ]; } /** Exported only for tests. */ function applyDefaultOptions(optionsArg = {}) { const defaultOptions = { defaultIntegrations: getDefaultIntegrations(), release: typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value ? __SENTRY_RELEASE__ : WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects sendClientReports: true, }; return { ...defaultOptions, ...dropTopLevelUndefinedKeys(optionsArg), }; } /** * In contrast to the regular `dropUndefinedKeys` method, * this one does not deep-drop keys, but only on the top level. */ function dropTopLevelUndefinedKeys(obj) { const mutatetedObj = {}; for (const k of Object.getOwnPropertyNames(obj)) { const key = k ; if (obj[key] !== undefined) { mutatetedObj[key] = obj[key]; } } return mutatetedObj; } function shouldShowBrowserExtensionError() { const windowWithMaybeExtension = typeof WINDOW.window !== 'undefined' && (WINDOW ); if (!windowWithMaybeExtension) { // No need to show the error if we're not in a browser window environment (e.g. service workers) return false; } const extensionKey = windowWithMaybeExtension.chrome ? 'chrome' : 'browser'; const extensionObject = windowWithMaybeExtension[extensionKey]; const runtimeId = extensionObject?.runtime?.id; const href = getLocationHref() || ''; const extensionProtocols = ['chrome-extension:', 'moz-extension:', 'ms-browser-extension:', 'safari-web-extension:']; // Running the SDK in a dedicated extension page and calling Sentry.init is fine; no risk of data leakage const isDedicatedExtensionPage = !!runtimeId && WINDOW === WINDOW.top && extensionProtocols.some(protocol => href.startsWith(`${protocol}//`)); // Running the SDK in NW.js, which appears like a browser extension but isn't, is also fine // see: https://github.com/getsentry/sentry-javascript/issues/12668 const isNWjs = typeof windowWithMaybeExtension.nw !== 'undefined'; return !!runtimeId && !isDedicatedExtensionPage && !isNWjs; } /** * A magic string that build tooling can leverage in order to inject a release value into the SDK. */ /** * The Sentry Browser SDK Client. * * To use this SDK, call the {@link init} function as early as possible when * loading the web page. To set context information or send manual events, use * the provided methods. * * @example * * ``` * * import { init } from '@sentry/browser'; * * init({ * dsn: '__DSN__', * // ... * }); * ``` * * @example * ``` * * import { addBreadcrumb } from '@sentry/browser'; * addBreadcrumb({ * message: 'My Breadcrumb', * // ... * }); * ``` * * @example * * ``` * * import * as Sentry from '@sentry/browser'; * Sentry.captureMessage('Hello, world!'); * Sentry.captureException(new Error('Good bye')); * Sentry.captureEvent({ * message: 'Manual', * stacktrace: [ * // ... * ], * }); * ``` * * @see {@link BrowserOptions} for documentation on configuration options. */ function init(browserOptions = {}) { const options = applyDefaultOptions(browserOptions); if (!options.skipBrowserExtensionCheck && shouldShowBrowserExtensionError()) { if (DEBUG_BUILD) { consoleSandbox(() => { // eslint-disable-next-line no-console console.error( '[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/', ); }); } return; } if (DEBUG_BUILD && !supportsFetch()) { logger.warn( 'No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill.', ); } const clientOptions = { ...options, stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser), integrations: getIntegrationsToSetup(options), transport: options.transport || makeFetchTransport, }; return initAndBind(BrowserClient, clientOptions); } /** * Present the user with a report dialog. * * @param options Everything is optional, we try to fetch all info need from the global scope. */ function showReportDialog(options = {}) { // doesn't work without a document (React Native) if (!WINDOW.document) { DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call'); return; } const scope = getCurrentScope(); const client = scope.getClient(); const dsn = client?.getDsn(); if (!dsn) { DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call'); return; } if (scope) { options.user = { ...scope.getUser(), ...options.user, }; } if (!options.eventId) { const eventId = lastEventId(); if (eventId) { options.eventId = eventId; } } const script = WINDOW.document.createElement('script'); script.async = true; script.crossOrigin = 'anonymous'; script.src = getReportDialogEndpoint(dsn, options); if (options.onLoad) { script.onload = options.onLoad; } const { onClose } = options; if (onClose) { const reportDialogClosedMessageHandler = (event) => { if (event.data === '__sentry_reportdialog_closed__') { try { onClose(); } finally { WINDOW.removeEventListener('message', reportDialogClosedMessageHandler); } } }; WINDOW.addEventListener('message', reportDialogClosedMessageHandler); } const injectionPoint = WINDOW.document.head || WINDOW.document.body; if (injectionPoint) { injectionPoint.appendChild(script); } else { DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML'); } } /** * This function is here to be API compatible with the loader. * @hidden */ function forceLoad() { // Noop } /** * This function is here to be API compatible with the loader. * @hidden */ function onLoad(callback) { callback(); } export { applyDefaultOptions, forceLoad, getDefaultIntegrations, init, onLoad, showReportDialog }; //# sourceMappingURL=sdk.js.map