UNPKG

@alloyidentity/web-sdk

Version:

Alloy Web Document SDK

1,770 lines (1,500 loc) 327 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var queryString$1 = {}; var strictUriEncode = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); var token = '%[a-f0-9]{2}'; var singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi'); var multiMatcher = new RegExp('(' + token + ')+', 'gi'); function decodeComponents(components, split) { try { // Try to decode the entire string first return [decodeURIComponent(components.join(''))]; } catch (err) { // Do nothing } if (components.length === 1) { return components; } split = split || 1; // Split the array in 2 parts var left = components.slice(0, split); var right = components.slice(split); return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); } function decode(input) { try { return decodeURIComponent(input); } catch (err) { var tokens = input.match(singleMatcher) || []; for (var i = 1; i < tokens.length; i++) { input = decodeComponents(tokens, i).join(''); tokens = input.match(singleMatcher) || []; } return input; } } function customDecodeURIComponent(input) { // Keep track of all the replacements and prefill the map with the `BOM` var replaceMap = { '%FE%FF': '\uFFFD\uFFFD', '%FF%FE': '\uFFFD\uFFFD' }; var match = multiMatcher.exec(input); while (match) { try { // Decode as big chunks as possible replaceMap[match[0]] = decodeURIComponent(match[0]); } catch (err) { var result = decode(match[0]); if (result !== match[0]) { replaceMap[match[0]] = result; } } match = multiMatcher.exec(input); } // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else replaceMap['%C2'] = '\uFFFD'; var entries = Object.keys(replaceMap); for (var i = 0; i < entries.length; i++) { // Replace all decoded components var key = entries[i]; input = input.replace(new RegExp(key, 'g'), replaceMap[key]); } return input; } var decodeUriComponent = function (encodedURI) { if (typeof encodedURI !== 'string') { throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); } try { encodedURI = encodedURI.replace(/\+/g, ' '); // Try the built in decoder first return decodeURIComponent(encodedURI); } catch (err) { // Fallback to a more advanced decoder return customDecodeURIComponent(encodedURI); } }; var splitOnFirst = (string, separator) => { if (!(typeof string === 'string' && typeof separator === 'string')) { throw new TypeError('Expected the arguments to be of type `string`'); } if (separator === '') { return [string]; } const separatorIndex = string.indexOf(separator); if (separatorIndex === -1) { return [string]; } return [ string.slice(0, separatorIndex), string.slice(separatorIndex + separator.length) ]; }; var filterObj = function (obj, predicate) { var ret = {}; var keys = Object.keys(obj); var isArr = Array.isArray(predicate); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var val = obj[key]; if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) { ret[key] = val; } } return ret; }; (function (exports) { const strictUriEncode$1 = strictUriEncode; const decodeComponent = decodeUriComponent; const splitOnFirst$1 = splitOnFirst; const filterObject = filterObj; const isNullOrUndefined = value => value === null || value === undefined; function encoderForArrayFormat(options) { switch (options.arrayFormat) { case 'index': return key => (result, value) => { const index = result.length; if ( value === undefined || (options.skipNull && value === null) || (options.skipEmptyString && value === '') ) { return result; } if (value === null) { return [...result, [encode(key, options), '[', index, ']'].join('')]; } return [ ...result, [encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('') ]; }; case 'bracket': return key => (result, value) => { if ( value === undefined || (options.skipNull && value === null) || (options.skipEmptyString && value === '') ) { return result; } if (value === null) { return [...result, [encode(key, options), '[]'].join('')]; } return [...result, [encode(key, options), '[]=', encode(value, options)].join('')]; }; case 'comma': case 'separator': return key => (result, value) => { if (value === null || value === undefined || value.length === 0) { return result; } if (result.length === 0) { return [[encode(key, options), '=', encode(value, options)].join('')]; } return [[result, encode(value, options)].join(options.arrayFormatSeparator)]; }; default: return key => (result, value) => { if ( value === undefined || (options.skipNull && value === null) || (options.skipEmptyString && value === '') ) { return result; } if (value === null) { return [...result, encode(key, options)]; } return [...result, [encode(key, options), '=', encode(value, options)].join('')]; }; } } function parserForArrayFormat(options) { let result; switch (options.arrayFormat) { case 'index': return (key, value, accumulator) => { result = /\[(\d*)\]$/.exec(key); key = key.replace(/\[\d*\]$/, ''); if (!result) { accumulator[key] = value; return; } if (accumulator[key] === undefined) { accumulator[key] = {}; } accumulator[key][result[1]] = value; }; case 'bracket': return (key, value, accumulator) => { result = /(\[\])$/.exec(key); key = key.replace(/\[\]$/, ''); if (!result) { accumulator[key] = value; return; } if (accumulator[key] === undefined) { accumulator[key] = [value]; return; } accumulator[key] = [].concat(accumulator[key], value); }; case 'comma': case 'separator': return (key, value, accumulator) => { const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator); const isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator)); value = isEncodedArray ? decode(value, options) : value; const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : value === null ? value : decode(value, options); accumulator[key] = newValue; }; default: return (key, value, accumulator) => { if (accumulator[key] === undefined) { accumulator[key] = value; return; } accumulator[key] = [].concat(accumulator[key], value); }; } } function validateArrayFormatSeparator(value) { if (typeof value !== 'string' || value.length !== 1) { throw new TypeError('arrayFormatSeparator must be single character string'); } } function encode(value, options) { if (options.encode) { return options.strict ? strictUriEncode$1(value) : encodeURIComponent(value); } return value; } function decode(value, options) { if (options.decode) { return decodeComponent(value); } return value; } function keysSorter(input) { if (Array.isArray(input)) { return input.sort(); } if (typeof input === 'object') { return keysSorter(Object.keys(input)) .sort((a, b) => Number(a) - Number(b)) .map(key => input[key]); } return input; } function removeHash(input) { const hashStart = input.indexOf('#'); if (hashStart !== -1) { input = input.slice(0, hashStart); } return input; } function getHash(url) { let hash = ''; const hashStart = url.indexOf('#'); if (hashStart !== -1) { hash = url.slice(hashStart); } return hash; } function extract(input) { input = removeHash(input); const queryStart = input.indexOf('?'); if (queryStart === -1) { return ''; } return input.slice(queryStart + 1); } function parseValue(value, options) { if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) { value = Number(value); } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) { value = value.toLowerCase() === 'true'; } return value; } function parse(query, options) { options = Object.assign({ decode: true, sort: true, arrayFormat: 'none', arrayFormatSeparator: ',', parseNumbers: false, parseBooleans: false }, options); validateArrayFormatSeparator(options.arrayFormatSeparator); const formatter = parserForArrayFormat(options); // Create an object with no prototype const ret = Object.create(null); if (typeof query !== 'string') { return ret; } query = query.trim().replace(/^[?#&]/, ''); if (!query) { return ret; } for (const param of query.split('&')) { if (param === '') { continue; } let [key, value] = splitOnFirst$1(options.decode ? param.replace(/\+/g, ' ') : param, '='); // Missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters value = value === undefined ? null : ['comma', 'separator'].includes(options.arrayFormat) ? value : decode(value, options); formatter(decode(key, options), value, ret); } for (const key of Object.keys(ret)) { const value = ret[key]; if (typeof value === 'object' && value !== null) { for (const k of Object.keys(value)) { value[k] = parseValue(value[k], options); } } else { ret[key] = parseValue(value, options); } } if (options.sort === false) { return ret; } return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => { const value = ret[key]; if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) { // Sort object keys, not values result[key] = keysSorter(value); } else { result[key] = value; } return result; }, Object.create(null)); } exports.extract = extract; exports.parse = parse; exports.stringify = (object, options) => { if (!object) { return ''; } options = Object.assign({ encode: true, strict: true, arrayFormat: 'none', arrayFormatSeparator: ',' }, options); validateArrayFormatSeparator(options.arrayFormatSeparator); const shouldFilter = key => ( (options.skipNull && isNullOrUndefined(object[key])) || (options.skipEmptyString && object[key] === '') ); const formatter = encoderForArrayFormat(options); const objectCopy = {}; for (const key of Object.keys(object)) { if (!shouldFilter(key)) { objectCopy[key] = object[key]; } } const keys = Object.keys(objectCopy); if (options.sort !== false) { keys.sort(options.sort); } return keys.map(key => { const value = object[key]; if (value === undefined) { return ''; } if (value === null) { return encode(key, options); } if (Array.isArray(value)) { return value .reduce(formatter(key), []) .join('&'); } return encode(key, options) + '=' + encode(value, options); }).filter(x => x.length > 0).join('&'); }; exports.parseUrl = (url, options) => { options = Object.assign({ decode: true }, options); const [url_, hash] = splitOnFirst$1(url, '#'); return Object.assign( { url: url_.split('?')[0] || '', query: parse(extract(url), options) }, options && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {} ); }; exports.stringifyUrl = (object, options) => { options = Object.assign({ encode: true, strict: true }, options); const url = removeHash(object.url).split('?')[0] || ''; const queryFromUrl = exports.extract(object.url); const parsedQueryFromUrl = exports.parse(queryFromUrl, {sort: false}); const query = Object.assign(parsedQueryFromUrl, object.query); let queryString = exports.stringify(query, options); if (queryString) { queryString = `?${queryString}`; } let hash = getHash(object.url); if (object.fragmentIdentifier) { hash = `#${encode(object.fragmentIdentifier, options)}`; } return `${url}${queryString}${hash}`; }; exports.pick = (input, filter, options) => { options = Object.assign({ parseFragmentIdentifier: true }, options); const {url, query, fragmentIdentifier} = exports.parseUrl(input, options); return exports.stringifyUrl({ url, query: filterObject(query, filter), fragmentIdentifier }, options); }; exports.exclude = (input, filter, options) => { const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value); return exports.pick(input, exclusionFilter, options); }; } (queryString$1)); var queryString = /*@__PURE__*/getDefaultExportFromCjs(queryString$1); /** * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */ const DEBUG_BUILD$3 = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__); /** Internal global with common properties and Sentry extensions */ /** Get's the global object for the current JavaScript runtime */ const GLOBAL_OBJ = globalThis ; /** * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */ const DEBUG_BUILD$2 = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__); // This is a magic string replaced by rollup const SDK_VERSION = "9.14.0" ; /** * An object that contains globally accessible properties and maintains a scope stack. * @hidden */ /** * Returns the global shim registry. * * FIXME: This function is problematic, because despite always returning a valid Carrier, * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. **/ function getMainCarrier() { // This ensures a Sentry carrier exists getSentryCarrier(GLOBAL_OBJ); return GLOBAL_OBJ; } /** Will either get the existing sentry carrier, or create a new one. */ function getSentryCarrier(carrier) { const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {}); // For now: First SDK that sets the .version property wins __SENTRY__.version = __SENTRY__.version || SDK_VERSION; // Intentionally populating and returning the version of "this" SDK instance // rather than what's set in .version so that "this" SDK always gets its carrier return (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {}); } /** * Returns a global singleton contained in the global `__SENTRY__[]` object. * * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory * function and added to the `__SENTRY__` object. * * @param name name of the global singleton on __SENTRY__ * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value * @returns the singleton */ function getGlobalSingleton( name, creator, obj = GLOBAL_OBJ, ) { const __SENTRY__ = (obj.__SENTRY__ = obj.__SENTRY__ || {}); const carrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {}); // Note: We do not want to set `carrier.version` here, as this may be called before any `init` is called, e.g. for the default scopes return carrier[name] || (carrier[name] = creator()); } /** Prefix for logging strings */ const PREFIX = 'Sentry Logger '; const CONSOLE_LEVELS = [ 'debug', 'info', 'warn', 'error', 'log', 'assert', 'trace', ] ; /** This may be mutated by the console instrumentation. */ const originalConsoleMethods = {}; /** A Sentry Logger instance. */ /** * Temporarily disable sentry console instrumentations. * * @param callback The function to run against the original `console` messages * @returns The results of the callback */ function consoleSandbox(callback) { if (!('console' in GLOBAL_OBJ)) { return callback(); } const console = GLOBAL_OBJ.console ; const wrappedFuncs = {}; const wrappedLevels = Object.keys(originalConsoleMethods) ; // Restore all wrapped console methods wrappedLevels.forEach(level => { const originalConsoleMethod = originalConsoleMethods[level] ; wrappedFuncs[level] = console[level] ; console[level] = originalConsoleMethod; }); try { return callback(); } finally { // Revert restoration to wrapped state wrappedLevels.forEach(level => { console[level] = wrappedFuncs[level] ; }); } } function makeLogger() { let enabled = false; const logger = { enable: () => { enabled = true; }, disable: () => { enabled = false; }, isEnabled: () => enabled, }; if (DEBUG_BUILD$2) { CONSOLE_LEVELS.forEach(name => { logger[name] = (...args) => { if (enabled) { consoleSandbox(() => { GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); }); } }; }); } else { CONSOLE_LEVELS.forEach(name => { logger[name] = () => undefined; }); } return logger ; } /** * This is a logger singleton which either logs things or no-ops if logging is not enabled. * The logger is a singleton on the carrier, to ensure that a consistent logger is used throughout the SDK. */ const logger = getGlobalSingleton('logger', makeLogger); const STACKTRACE_FRAME_LIMIT = 50; const UNKNOWN_FUNCTION = '?'; // Used to sanitize webpack (error: *) wrapped stack errors const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/; const STRIP_FRAME_REGEXP = /captureMessage|captureException/; /** * Creates a stack parser with the supplied line parsers * * StackFrames are returned in the correct order for Sentry Exception * frames and with Sentry SDK internal frames removed from the top and bottom * */ function createStackParser(...parsers) { const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); return (stack, skipFirstLines = 0, framesToPop = 0) => { const frames = []; const lines = stack.split('\n'); for (let i = skipFirstLines; i < lines.length; i++) { const line = lines[i] ; // Ignore lines over 1kb as they are unlikely to be stack frames. // Many of the regular expressions use backtracking which results in run time that increases exponentially with // input size. Huge strings can result in hangs/Denial of Service: // https://github.com/getsentry/sentry-javascript/issues/2286 if (line.length > 1024) { continue; } // https://github.com/getsentry/sentry-javascript/issues/5459 // Remove webpack (error: *) wrappers const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line; // https://github.com/getsentry/sentry-javascript/issues/7813 // Skip Error: lines if (cleanedLine.match(/\S*Error: /)) { continue; } for (const parser of sortedParsers) { const frame = parser(cleanedLine); if (frame) { frames.push(frame); break; } } if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) { break; } } return stripSentryFramesAndReverse(frames.slice(framesToPop)); }; } /** * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames. * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the * function that caused the crash is the last frame in the array. * @hidden */ function stripSentryFramesAndReverse(stack) { if (!stack.length) { return []; } const localStack = Array.from(stack); // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) if (/sentryWrapped/.test(getLastStackFrame(localStack).function || '')) { localStack.pop(); } // Reversing in the middle of the procedure allows us to just pop the values off the stack localStack.reverse(); // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) { localStack.pop(); // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')` // is produced within the scope itself, making it: // // Sentry.captureException() // scope.captureException() // // instead of just the top `Sentry` call itself. // This forces us to possibly strip an additional frame in the exact same was as above. if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) { localStack.pop(); } } return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({ ...frame, filename: frame.filename || getLastStackFrame(localStack).filename, function: frame.function || UNKNOWN_FUNCTION, })); } function getLastStackFrame(arr) { return arr[arr.length - 1] || {}; } const defaultFunctionName = '<anonymous>'; /** * Safely extract function name from itself */ function getFunctionName(fn) { try { if (!fn || typeof fn !== 'function') { return defaultFunctionName; } return fn.name || defaultFunctionName; } catch (e) { // Just accessing custom props in some Selenium environments // can cause a "Permission denied" exception (see raven-js#495). return defaultFunctionName; } } /** * Get's stack frames from an event without needing to check for undefined properties. */ function getFramesFromEvent(event) { const exception = event.exception; if (exception) { const frames = []; try { // @ts-expect-error Object could be undefined exception.values.forEach(value => { // @ts-expect-error Value could be undefined if (value.stacktrace.frames) { // @ts-expect-error Value could be undefined frames.push(...value.stacktrace.frames); } }); return frames; } catch (_oO) { return undefined; } } return undefined; } // We keep the handlers globally const handlers = {}; const instrumented = {}; /** Add a handler function. */ function addHandler(type, handler) { handlers[type] = handlers[type] || []; (handlers[type] ).push(handler); } /** Maybe run an instrumentation function, unless it was already called. */ function maybeInstrument(type, instrumentFn) { if (!instrumented[type]) { instrumented[type] = true; try { instrumentFn(); } catch (e) { DEBUG_BUILD$2 && logger.error(`Error while instrumenting ${type}`, e); } } } /** Trigger handlers for a given instrumentation type. */ function triggerHandlers(type, data) { const typeHandlers = type && handlers[type]; if (!typeHandlers) { return; } for (const handler of typeHandlers) { try { handler(data); } catch (e) { DEBUG_BUILD$2 && logger.error( `Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler)}\nError:`, e, ); } } } let _oldOnErrorHandler = null; /** * Add an instrumentation handler for when an error is captured by the global error handler. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addGlobalErrorInstrumentationHandler(handler) { const type = 'error'; addHandler(type, handler); maybeInstrument(type, instrumentError); } function instrumentError() { _oldOnErrorHandler = GLOBAL_OBJ.onerror; // Note: The reason we are doing window.onerror instead of window.addEventListener('error') // is that we are using this handler in the Loader Script, to handle buffered errors consistently GLOBAL_OBJ.onerror = function ( msg, url, line, column, error, ) { const handlerData = { column, error, line, msg, url, }; triggerHandlers('error', handlerData); if (_oldOnErrorHandler) { // eslint-disable-next-line prefer-rest-params return _oldOnErrorHandler.apply(this, arguments); } return false; }; GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true; } let _oldOnUnhandledRejectionHandler = null; /** * Add an instrumentation handler for when an unhandled promise rejection is captured. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addGlobalUnhandledRejectionInstrumentationHandler( handler, ) { const type = 'unhandledrejection'; addHandler(type, handler); maybeInstrument(type, instrumentUnhandledRejection); } function instrumentUnhandledRejection() { _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection; // Note: The reason we are doing window.onunhandledrejection instead of window.addEventListener('unhandledrejection') // is that we are using this handler in the Loader Script, to handle buffered rejections consistently GLOBAL_OBJ.onunhandledrejection = function (e) { const handlerData = e; triggerHandlers('unhandledrejection', handlerData); if (_oldOnUnhandledRejectionHandler) { // eslint-disable-next-line prefer-rest-params return _oldOnUnhandledRejectionHandler.apply(this, arguments); } return true; }; GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true; } // eslint-disable-next-line @typescript-eslint/unbound-method const objectToString = Object.prototype.toString; /** * Checks whether given value's type is one of a few Error or Error-like * {@link isError}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isError(wat) { switch (objectToString.call(wat)) { case '[object Error]': case '[object Exception]': case '[object DOMException]': case '[object WebAssembly.Exception]': return true; default: return isInstanceOf(wat, Error); } } /** * Checks whether given value is an instance of the given built-in class. * * @param wat The value to be checked * @param className * @returns A boolean representing the result. */ function isBuiltin(wat, className) { return objectToString.call(wat) === `[object ${className}]`; } /** * Checks whether given value's type is ErrorEvent * {@link isErrorEvent}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isErrorEvent$1(wat) { return isBuiltin(wat, 'ErrorEvent'); } /** * Checks whether given value's type is DOMError * {@link isDOMError}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isDOMError(wat) { return isBuiltin(wat, 'DOMError'); } /** * Checks whether given value's type is DOMException * {@link isDOMException}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isDOMException(wat) { return isBuiltin(wat, 'DOMException'); } /** * Checks whether given value's type is a string * {@link isString}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isString(wat) { return isBuiltin(wat, 'String'); } /** * Checks whether given string is parameterized * {@link isParameterizedString}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isParameterizedString(wat) { return ( typeof wat === 'object' && wat !== null && '__sentry_template_string__' in wat && '__sentry_template_values__' in wat ); } /** * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) * {@link isPrimitive}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isPrimitive(wat) { return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function'); } /** * Checks whether given value's type is an object literal, or a class instance. * {@link isPlainObject}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isPlainObject(wat) { return isBuiltin(wat, 'Object'); } /** * Checks whether given value's type is an Event instance * {@link isEvent}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isEvent(wat) { return typeof Event !== 'undefined' && isInstanceOf(wat, Event); } /** * Checks whether given value's type is an Element instance * {@link isElement}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isElement(wat) { return typeof Element !== 'undefined' && isInstanceOf(wat, Element); } /** * Checks whether given value's type is an regexp * {@link isRegExp}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isRegExp(wat) { return isBuiltin(wat, 'RegExp'); } /** * Checks whether given value has a then function. * @param wat A value to be checked. */ function isThenable(wat) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access return Boolean(wat?.then && typeof wat.then === 'function'); } /** * Checks whether given value's type is a SyntheticEvent * {@link isSyntheticEvent}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isSyntheticEvent(wat) { return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; } /** * Checks whether given value's type is an instance of provided constructor. * {@link isInstanceOf}. * * @param wat A value to be checked. * @param base A constructor to be used in a check. * @returns A boolean representing the result. */ function isInstanceOf(wat, base) { try { return wat instanceof base; } catch (_e) { return false; } } /** * Checks whether given value's type is a Vue ViewModel. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isVueViewModel(wat) { // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property. return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue)); } /** * Checks whether the given parameter is a Standard Web API Request instance. * * Returns false if Request is not available in the current runtime. */ function isRequest(request) { return typeof Request !== 'undefined' && isInstanceOf(request, Request); } const WINDOW$3 = GLOBAL_OBJ ; const DEFAULT_MAX_STRING_LENGTH = 80; /** * Given a child DOM element, returns a query-selector statement describing that * and its ancestors * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] * @returns generated DOM path */ function htmlTreeAsString( elem, options = {}, ) { if (!elem) { return '<unknown>'; } // try/catch both: // - accessing event.target (see getsentry/raven-js#838, #768) // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly // - can throw an exception in some circumstances. try { let currentElem = elem ; const MAX_TRAVERSE_HEIGHT = 5; const out = []; let height = 0; let len = 0; const separator = ' > '; const sepLength = separator.length; let nextStr; const keyAttrs = Array.isArray(options) ? options : options.keyAttrs; const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH; while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { nextStr = _htmlElementAsString(currentElem, keyAttrs); // bail out if // - nextStr is the 'html' element // - the length of the string that would be created exceeds maxStringLength // (ignore this limit if we are on the first iteration) if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) { break; } out.push(nextStr); len += nextStr.length; currentElem = currentElem.parentNode; } return out.reverse().join(separator); } catch (_oO) { return '<unknown>'; } } /** * Returns a simple, query-selector representation of a DOM element * e.g. [HTMLElement] => input#foo.btn[name=baz] * @returns generated DOM path */ function _htmlElementAsString(el, keyAttrs) { const elem = el ; const out = []; if (!elem?.tagName) { return ''; } // @ts-expect-error WINDOW has HTMLElement if (WINDOW$3.HTMLElement) { // If using the component name annotation plugin, this value may be available on the DOM node if (elem instanceof HTMLElement && elem.dataset) { if (elem.dataset['sentryComponent']) { return elem.dataset['sentryComponent']; } if (elem.dataset['sentryElement']) { return elem.dataset['sentryElement']; } } } out.push(elem.tagName.toLowerCase()); // Pairs of attribute keys defined in `serializeAttribute` and their values on element. const keyAttrPairs = keyAttrs?.length ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) : null; if (keyAttrPairs?.length) { keyAttrPairs.forEach(keyAttrPair => { out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); }); } else { if (elem.id) { out.push(`#${elem.id}`); } const className = elem.className; if (className && isString(className)) { const classes = className.split(/\s+/); for (const c of classes) { out.push(`.${c}`); } } } const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt']; for (const k of allowedAttrs) { const attr = elem.getAttribute(k); if (attr) { out.push(`[${k}="${attr}"]`); } } return out.join(''); } /** * A safe form of location.href */ function getLocationHref() { try { return WINDOW$3.document.location.href; } catch (oO) { return ''; } } /** * Given a DOM element, traverses up the tree until it finds the first ancestor node * that has the `data-sentry-component` or `data-sentry-element` attribute with `data-sentry-component` taking * precedence. This attribute is added at build-time by projects that have the component name annotation plugin installed. * * @returns a string representation of the component for the provided DOM element, or `null` if not found */ function getComponentName(elem) { // @ts-expect-error WINDOW has HTMLElement if (!WINDOW$3.HTMLElement) { return null; } let currentElem = elem ; const MAX_TRAVERSE_HEIGHT = 5; for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) { if (!currentElem) { return null; } if (currentElem instanceof HTMLElement) { if (currentElem.dataset['sentryComponent']) { return currentElem.dataset['sentryComponent']; } if (currentElem.dataset['sentryElement']) { return currentElem.dataset['sentryElement']; } } currentElem = currentElem.parentNode; } return null; } /** * Truncates given string to the maximum characters count * * @param str An object that contains serializable values * @param max Maximum number of characters in truncated string (0 = unlimited) * @returns string Encoded */ function truncate(str, max = 0) { if (typeof str !== 'string' || max === 0) { return str; } return str.length <= max ? str : `${str.slice(0, max)}...`; } /** * Join values in array * @param input array of values to be joined together * @param delimiter string to be placed in-between values * @returns Joined values */ function safeJoin(input, delimiter) { if (!Array.isArray(input)) { return ''; } const output = []; // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < input.length; i++) { const value = input[i]; try { // This is a hack to fix a Vue3-specific bug that causes an infinite loop of // console warnings. This happens when a Vue template is rendered with // an undeclared variable, which we try to stringify, ultimately causing // Vue to issue another warning which repeats indefinitely. // see: https://github.com/getsentry/sentry-javascript/pull/8981 if (isVueViewModel(value)) { output.push('[VueViewModel]'); } else { output.push(String(value)); } } catch (e) { output.push('[value cannot be serialized]'); } } return output.join(delimiter); } /** * Checks if the given value matches a regex or string * * @param value The string to test * @param pattern Either a regex or a string against which `value` will be matched * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match * `pattern` if it contains `pattern`. Only applies to string-type patterns. */ function isMatchingPattern( value, pattern, requireExactStringMatch = false, ) { if (!isString(value)) { return false; } if (isRegExp(pattern)) { return pattern.test(value); } if (isString(pattern)) { return requireExactStringMatch ? value === pattern : value.includes(pattern); } return false; } /** * Test the given string against an array of strings and regexes. By default, string matching is done on a * substring-inclusion basis rather than a strict equality basis * * @param testString The string to test * @param patterns The patterns against which to test the string * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to * count. If false, `testString` will match a string pattern if it contains that pattern. * @returns */ function stringMatchesSomePattern( testString, patterns = [], requireExactStringMatch = false, ) { return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch)); } /** * Replace a method in an object with a wrapped version of itself. * * If the method on the passed object is not a function, the wrapper will not be applied. * * @param source An object that contains a method to be wrapped. * @param name The name of the method to be wrapped. * @param replacementFactory A higher-order function that takes the original version of the given method and returns a * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`. * @returns void */ function fill(source, name, replacementFactory) { if (!(name in source)) { return; } // explicitly casting to unknown because we don't know the type of the method initially at all const original = source[name] ; if (typeof original !== 'function') { return; } const wrapped = replacementFactory(original) ; // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" if (typeof wrapped === 'function') { markFunctionWrapped(wrapped, original); } try { source[name] = wrapped; } catch { DEBUG_BUILD$2 && logger.log(`Failed to replace method "${name}" in object`, source); } } /** * Defines a non-enumerable property on the given object. * * @param obj The object on which to set the property * @param name The name of the property to be set * @param value The value to which to set the property */ function addNonEnumerableProperty(obj, name, value) { try { Object.defineProperty(obj, name, { // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it value: value, writable: true, configurable: true, }); } catch (o_O) { DEBUG_BUILD$2 && logger.log(`Failed to add non-enumerable property "${name}" to object`, obj); } } /** * Remembers the original function on the wrapped function and * patches up the prototype. * * @param wrapped the wrapper function * @param original the original function that gets wrapped */ function markFunctionWrapped(wrapped, original) { try { const proto = original.prototype || {}; wrapped.prototype = original.prototype = proto; addNonEnumerableProperty(wrapped, '__sentry_original__', original); } catch (o_O) {} // eslint-disable-line no-empty } /** * This extracts the original function if available. See * `markFunctionWrapped` for more information. * * @param func the function to unwrap * @returns the unwrapped version of the function if available. */ // eslint-disable-next-line @typescript-eslint/ban-types function getOriginalFunction(func) { return func.__sentry_original__; } /** * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their * non-enumerable properties attached. * * @param value Initial source that we have to transform in order for it to be usable by the serializer * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor * an Error. */ function convertToPlainObject(value) { if (isError(value)) { return { message: value.message, name: value.name, stack: value.stack, ...getOwnProperties(value), }; } else if (isEvent(value)) { const newObj = { type: value.type, target: serializeEventTarget(value.target), currentTarget: serializeEventTarget(value.currentTarget), ...getOwnProperties(value), }; if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) { newObj.detail = value.detail; } return newObj; } else { return value; } } /** Creates a string representation of the target of an `Event` object */ function serializeEventTarget(target) { try { return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target); } catch (_oO) { return '<unknown>'; } } /** Filters out all but an object's own properties */ function getOwnProperties(obj) { if (typeof obj === 'object' && obj !== null) { const extractedProps = {}; for (const property in obj) { if (Object.prototype.hasOwnProperty.call(obj, property)) { extractedProps[property] = (obj )[property]; } } return extractedProps; } else { return {}; } } /** * Given any captured exception, extract its keys and create a sorted * and truncated list that will be used inside the event message. * eg. `Non-error exception captured with keys: foo, bar, baz` */ function extractExceptionKeysForMessage(exception, maxLength = 40) { const keys = Object.keys(convertToPlainObject(exception)); keys.sort(); const firstKey = keys[0]; if (!firstKey) { return '[object has no keys]'; } if (firstKey.length >= maxLength) { return truncate(firstKey, maxLength); } for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { const serialized = keys.slice(0, includedKeys).join(', '); if (serialized.length > maxLength) { continue; } if (includedKeys === keys.length) { return serialized; } return truncate(serialized, maxLength); } return ''; } function getCrypto() { const gbl = GLOBAL_OBJ ; return gbl.crypto || gbl.msCrypto; } /** * UUID4 generator * @param crypto Object that provides the crypto API. * @returns string Generated UUID4. */ function uuid4(crypto = getCrypto()) { let getRandomByte = () => Math.random() * 16; try { if (crypto?.randomUUID) { return crypto.randomUUID().replace(/-/g, ''); } if (crypto?.getRandomValues) { getRandomByte = () => { // crypto.getRandomValues might return undefined instead of the typed array // in old Chromium versions (e.g. 23.0.1235.0 (151422)) // However, `typedArray` is still filled in-place. // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray const typedArray = new Uint8Array(1); crypto.getRandomValues(typedArray); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return typedArray[0]; }; } } catch (_) { // some runtimes can crash invoking crypto // https://github.com/getsentry/sentry-javascript/issues/8935 } // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 // Concatenating the following numbers as strings results in '10000000100040008000100000000000' return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c => // eslint-disable-next-line no-bitwise ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16), ); } function getFirstException(event) { return event.exception?.values?.[0]; } /** * Extracts either message or type+value from an event that can be used for user-facing logs * @returns event's description */ function getEventDescription(event) { const { message, event_id: eventId } = event; if (message) { return message; } const firstException = getFirstException(event); if (firstException) { if (firstException.type && firstException.value) { return `${firstException.type}: ${firstException.value}`; } return firstException.type || firstException.value || eventId || '<unknown>'; } return eventId || '<unknown>'; } /** * Adds exception values, type and value to an synthetic Exception. * @param event The event to modify. * @param value Value of the exception. * @param type Type of the exception. * @hidden */ function addExceptionTypeValue(event, value, type) { const exception = (event.exception = event.exception || {}); const values = (exception.values = exception.values || []); const firstException = (values[0] = values[0] || {}); if (!firstException.value) { firstException.value = value || ''; } if (!firstException.type) { firstException.type = type || 'Error'; } } /** * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. * * @param event The event to modify. * @param newMechanism Mechanism data to add to the event. * @hidden */ function addExceptionMechanism(event, newMechanism) { const firstException = getFirstException(event); if (!firstException) { return; } const defaultMechanism = { type: 'generic', handled: true }; const currentMechanism = firstException.mechanism; firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; if (newMechanism && 'data' in newMechanism) { const mergedData = { ...currentMechanism?.data, ...newMechanism.data }; firstException.mechanism.data = mergedData; } } /** * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object * in question), and marks it captured if not. * * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we * see it. * * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent * object wrapper forms so that this check will always work. However, because we need to flag the exact object which * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification * must be done before the exception captured. * * @param A thrown exception to check or flag as having been seen * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) */ function checkOrSetAlreadyCaught(exception) { if (isAlreadyCaptured(exception)) { return true; } try { // set it this w