UNPKG

@sentry/core

Version:
199 lines (198 loc) • 7.1 kB
import { DEBUG_BUILD } from "../debug-build.js"; import { debug } from "./debug-logger.js"; import { isError, isEvent, isObjectLike, isPrimitive } from "./is.js"; // src/utils/object.ts /** * 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; const original = source[name]; if (typeof original !== "function") return; const wrapped = replacementFactory(original); if (typeof wrapped === "function") markFunctionWrapped(wrapped, original); try { source[name] = wrapped; } catch { DEBUG_BUILD && debug.log(`Failed to replace method "${String(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, { value, writable: true, configurable: true }); } catch { DEBUG_BUILD && debug.log(`Failed to add non-enumerable property "${String(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 { wrapped.prototype = original.prototype = original.prototype || {}; addNonEnumerableProperty(wrapped, "__sentry_original__", original); } catch {} } /** * Wrap a method on an object by name, only if it is not already wrapped. * * Note: to set the wrapped method as a non-enumerable property, pass * false as the `enumerable` argument. This could be detected, but only * by either walking up the prototype chain, or iterating over all fields * in a `for(in)` loop. Neither are an acceptable performance impact for * the rare case where we might patch a non-enumerable method. */ function wrapMethod(obj, field, wrapped, enumerable = true) { const original = obj[field]; if (typeof original !== "function") throw new Error(`Cannot wrap method: ${field} is not a function`); if (getOriginalFunction(original)) throw new Error(`Attempting to wrap method ${field} multiple times`); markFunctionWrapped(wrapped, original); Object.defineProperty(obj, field, { writable: true, configurable: true, enumerable, value: wrapped }); } /** * 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. */ 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) }; if (isEvent(value)) { const { type, target, currentTarget, detail } = value; return { type, target, currentTarget, ...detail ? { detail } : {}, ...getOwnProperties(value) }; } return value; } /** Filters out all but an object's own properties */ function getOwnProperties(obj) { if (isObjectLike(obj)) return Object.fromEntries(Object.entries(obj)); 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) { const keys = Object.keys(convertToPlainObject(exception)); keys.sort(); return !keys[0] ? "[object has no keys]" : keys.join(", "); } /** * Given any object, return a new object having removed all fields whose value was `undefined`. * Works recursively on objects and arrays. * * Attention: This function keeps circular references in the returned object. * * @deprecated This function is no longer used by the SDK and will be removed in a future major version. */ function dropUndefinedKeys(inputValue) { return _dropUndefinedKeys(inputValue, /* @__PURE__ */ new Map()); } function _dropUndefinedKeys(inputValue, memoizationMap) { if (inputValue === null || typeof inputValue !== "object") return inputValue; const memoVal = memoizationMap.get(inputValue); if (memoVal !== void 0) return memoVal; if (Array.isArray(inputValue)) { const returnValue = []; memoizationMap.set(inputValue, returnValue); inputValue.forEach((value) => { returnValue.push(_dropUndefinedKeys(value, memoizationMap)); }); return returnValue; } if (isPojo(inputValue)) { const returnValue = {}; memoizationMap.set(inputValue, returnValue); Object.keys(inputValue).forEach((key) => { const val = inputValue[key]; if (val !== void 0) returnValue[key] = _dropUndefinedKeys(val, memoizationMap); }); return returnValue; } return inputValue; } function isPojo(input) { const constructor = input.constructor; return constructor === Object || constructor === void 0; } /** * Ensure that something is an object. * * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. * * @param wat The subject of the objectification * @returns A version of `wat` which can safely be used with `Object` class methods */ function objectify(wat) { let objectified; switch (true) { case wat == void 0: objectified = new String(wat); break; case typeof wat === "symbol" || typeof wat === "bigint": objectified = Object(wat); break; case isPrimitive(wat): objectified = new wat.constructor(wat); break; default: objectified = wat; } return objectified; } export { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify, wrapMethod }; //# sourceMappingURL=object.js.map