normalize.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { isNaN, isVueViewModel, isSyntheticEvent } from './is.js';
  2. import { memoBuilder } from './memo.js';
  3. import { convertToPlainObject } from './object.js';
  4. import { getFunctionName } from './stacktrace.js';
  5. /**
  6. * Recursively normalizes the given object.
  7. *
  8. * - Creates a copy to prevent original input mutation
  9. * - Skips non-enumerable properties
  10. * - When stringifying, calls `toJSON` if implemented
  11. * - Removes circular references
  12. * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format
  13. * - Translates known global objects/classes to a string representations
  14. * - Takes care of `Error` object serialization
  15. * - Optionally limits depth of final output
  16. * - Optionally limits number of properties/elements included in any single object/array
  17. *
  18. * @param input The object to be normalized.
  19. * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)
  20. * @param maxProperties The max number of elements or properties to be included in any single array or
  21. * object in the normallized output.
  22. * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization.
  23. */
  24. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  25. function normalize(input, depth = 100, maxProperties = +Infinity) {
  26. try {
  27. // since we're at the outermost level, we don't provide a key
  28. return visit('', input, depth, maxProperties);
  29. } catch (err) {
  30. return { ERROR: `**non-serializable** (${err})` };
  31. }
  32. }
  33. /** JSDoc */
  34. function normalizeToSize(
  35. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  36. object,
  37. // Default Node.js REPL depth
  38. depth = 3,
  39. // 100kB, as 200kB is max payload size, so half sounds reasonable
  40. maxSize = 100 * 1024,
  41. ) {
  42. const normalized = normalize(object, depth);
  43. if (jsonSize(normalized) > maxSize) {
  44. return normalizeToSize(object, depth - 1, maxSize);
  45. }
  46. return normalized ;
  47. }
  48. /**
  49. * Visits a node to perform normalization on it
  50. *
  51. * @param key The key corresponding to the given node
  52. * @param value The node to be visited
  53. * @param depth Optional number indicating the maximum recursion depth
  54. * @param maxProperties Optional maximum number of properties/elements included in any single object/array
  55. * @param memo Optional Memo class handling decycling
  56. */
  57. function visit(
  58. key,
  59. value,
  60. depth = +Infinity,
  61. maxProperties = +Infinity,
  62. memo = memoBuilder(),
  63. ) {
  64. const [memoize, unmemoize] = memo;
  65. // Get the simple cases out of the way first
  66. if (
  67. value == null || // this matches null and undefined -> eqeq not eqeqeq
  68. (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))
  69. ) {
  70. return value ;
  71. }
  72. const stringified = stringifyValue(key, value);
  73. // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`.
  74. // Everything else will have already been serialized, so if we don't see that pattern, we're done.
  75. if (!stringified.startsWith('[object ')) {
  76. return stringified;
  77. }
  78. // From here on, we can assert that `value` is either an object or an array.
  79. // Do not normalize objects that we know have already been normalized. As a general rule, the
  80. // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that
  81. // have already been normalized.
  82. if ((value )['__sentry_skip_normalization__']) {
  83. return value ;
  84. }
  85. // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there
  86. // We keep a certain amount of depth.
  87. // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.
  88. const remainingDepth =
  89. typeof (value )['__sentry_override_normalization_depth__'] === 'number'
  90. ? ((value )['__sentry_override_normalization_depth__'] )
  91. : depth;
  92. // We're also done if we've reached the max depth
  93. if (remainingDepth === 0) {
  94. // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`.
  95. return stringified.replace('object ', '');
  96. }
  97. // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.
  98. if (memoize(value)) {
  99. return '[Circular ~]';
  100. }
  101. // If the value has a `toJSON` method, we call it to extract more information
  102. const valueWithToJSON = value ;
  103. if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {
  104. try {
  105. const jsonValue = valueWithToJSON.toJSON();
  106. // We need to normalize the return value of `.toJSON()` in case it has circular references
  107. return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);
  108. } catch (err) {
  109. // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)
  110. }
  111. }
  112. // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse
  113. // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each
  114. // property/entry, and keep track of the number of items we add to it.
  115. const normalized = (Array.isArray(value) ? [] : {}) ;
  116. let numAdded = 0;
  117. // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant
  118. // properties are non-enumerable and otherwise would get missed.
  119. const visitable = convertToPlainObject(value );
  120. for (const visitKey in visitable) {
  121. // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.
  122. if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
  123. continue;
  124. }
  125. if (numAdded >= maxProperties) {
  126. normalized[visitKey] = '[MaxProperties ~]';
  127. break;
  128. }
  129. // Recursively visit all the child nodes
  130. const visitValue = visitable[visitKey];
  131. normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);
  132. numAdded++;
  133. }
  134. // Once we've visited all the branches, remove the parent from memo storage
  135. unmemoize(value);
  136. // Return accumulated values
  137. return normalized;
  138. }
  139. /* eslint-disable complexity */
  140. /**
  141. * Stringify the given value. Handles various known special values and types.
  142. *
  143. * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn
  144. * the number 1231 into "[Object Number]", nor on `null`, as it will throw.
  145. *
  146. * @param value The value to stringify
  147. * @returns A stringified representation of the given value
  148. */
  149. function stringifyValue(
  150. key,
  151. // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for
  152. // our internal use, it'll do
  153. value,
  154. ) {
  155. try {
  156. if (key === 'domain' && value && typeof value === 'object' && (value )._events) {
  157. return '[Domain]';
  158. }
  159. if (key === 'domainEmitter') {
  160. return '[DomainEmitter]';
  161. }
  162. // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first
  163. // which won't throw if they are not present.
  164. if (typeof global !== 'undefined' && value === global) {
  165. return '[Global]';
  166. }
  167. // eslint-disable-next-line no-restricted-globals
  168. if (typeof window !== 'undefined' && value === window) {
  169. return '[Window]';
  170. }
  171. // eslint-disable-next-line no-restricted-globals
  172. if (typeof document !== 'undefined' && value === document) {
  173. return '[Document]';
  174. }
  175. if (isVueViewModel(value)) {
  176. return '[VueViewModel]';
  177. }
  178. // React's SyntheticEvent thingy
  179. if (isSyntheticEvent(value)) {
  180. return '[SyntheticEvent]';
  181. }
  182. if (typeof value === 'number' && value !== value) {
  183. return '[NaN]';
  184. }
  185. if (typeof value === 'function') {
  186. return `[Function: ${getFunctionName(value)}]`;
  187. }
  188. if (typeof value === 'symbol') {
  189. return `[${String(value)}]`;
  190. }
  191. // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion
  192. if (typeof value === 'bigint') {
  193. return `[BigInt: ${String(value)}]`;
  194. }
  195. // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting
  196. // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as
  197. // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class),
  198. // we can make sure that only plain objects come out that way.
  199. const objName = getConstructorName(value);
  200. // Handle HTML Elements
  201. if (/^HTML(\w*)Element$/.test(objName)) {
  202. return `[HTMLElement: ${objName}]`;
  203. }
  204. return `[object ${objName}]`;
  205. } catch (err) {
  206. return `**non-serializable** (${err})`;
  207. }
  208. }
  209. /* eslint-enable complexity */
  210. function getConstructorName(value) {
  211. const prototype = Object.getPrototypeOf(value);
  212. return prototype ? prototype.constructor.name : 'null prototype';
  213. }
  214. /** Calculates bytes size of input string */
  215. function utf8Length(value) {
  216. // eslint-disable-next-line no-bitwise
  217. return ~-encodeURI(value).split(/%..|./).length;
  218. }
  219. /** Calculates bytes size of input object */
  220. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  221. function jsonSize(value) {
  222. return utf8Length(JSON.stringify(value));
  223. }
  224. /**
  225. * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint
  226. * across platforms and working directory.
  227. *
  228. * @param url The URL to be normalized.
  229. * @param basePath The application base path.
  230. * @returns The normalized URL.
  231. */
  232. function normalizeUrlToBase(url, basePath) {
  233. const escapedBase = basePath
  234. // Backslash to forward
  235. .replace(/\\/g, '/')
  236. // Escape RegExp special characters
  237. .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
  238. let newUrl = url;
  239. try {
  240. newUrl = decodeURI(url);
  241. } catch (_Oo) {
  242. // Sometime this breaks
  243. }
  244. return (
  245. newUrl
  246. .replace(/\\/g, '/')
  247. .replace(/webpack:\/?/g, '') // Remove intermediate base path
  248. // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor
  249. .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')
  250. );
  251. }
  252. export { normalize, normalizeToSize, normalizeUrlToBase, visit as walk };
  253. //# sourceMappingURL=normalize.js.map