misc.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import { addNonEnumerableProperty } from './object.js';
  2. import { snipLine } from './string.js';
  3. import { GLOBAL_OBJ } from './worldwide.js';
  4. /**
  5. * UUID4 generator
  6. *
  7. * @returns string Generated UUID4.
  8. */
  9. function uuid4() {
  10. const gbl = GLOBAL_OBJ ;
  11. const crypto = gbl.crypto || gbl.msCrypto;
  12. let getRandomByte = () => Math.random() * 16;
  13. try {
  14. if (crypto && crypto.randomUUID) {
  15. return crypto.randomUUID().replace(/-/g, '');
  16. }
  17. if (crypto && crypto.getRandomValues) {
  18. getRandomByte = () => {
  19. // crypto.getRandomValues might return undefined instead of the typed array
  20. // in old Chromium versions (e.g. 23.0.1235.0 (151422))
  21. // However, `typedArray` is still filled in-place.
  22. // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray
  23. const typedArray = new Uint8Array(1);
  24. crypto.getRandomValues(typedArray);
  25. return typedArray[0];
  26. };
  27. }
  28. } catch (_) {
  29. // some runtimes can crash invoking crypto
  30. // https://github.com/getsentry/sentry-javascript/issues/8935
  31. }
  32. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
  33. // Concatenating the following numbers as strings results in '10000000100040008000100000000000'
  34. return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>
  35. // eslint-disable-next-line no-bitwise
  36. ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),
  37. );
  38. }
  39. function getFirstException(event) {
  40. return event.exception && event.exception.values ? event.exception.values[0] : undefined;
  41. }
  42. /**
  43. * Extracts either message or type+value from an event that can be used for user-facing logs
  44. * @returns event's description
  45. */
  46. function getEventDescription(event) {
  47. const { message, event_id: eventId } = event;
  48. if (message) {
  49. return message;
  50. }
  51. const firstException = getFirstException(event);
  52. if (firstException) {
  53. if (firstException.type && firstException.value) {
  54. return `${firstException.type}: ${firstException.value}`;
  55. }
  56. return firstException.type || firstException.value || eventId || '<unknown>';
  57. }
  58. return eventId || '<unknown>';
  59. }
  60. /**
  61. * Adds exception values, type and value to an synthetic Exception.
  62. * @param event The event to modify.
  63. * @param value Value of the exception.
  64. * @param type Type of the exception.
  65. * @hidden
  66. */
  67. function addExceptionTypeValue(event, value, type) {
  68. const exception = (event.exception = event.exception || {});
  69. const values = (exception.values = exception.values || []);
  70. const firstException = (values[0] = values[0] || {});
  71. if (!firstException.value) {
  72. firstException.value = value || '';
  73. }
  74. if (!firstException.type) {
  75. firstException.type = type || 'Error';
  76. }
  77. }
  78. /**
  79. * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.
  80. *
  81. * @param event The event to modify.
  82. * @param newMechanism Mechanism data to add to the event.
  83. * @hidden
  84. */
  85. function addExceptionMechanism(event, newMechanism) {
  86. const firstException = getFirstException(event);
  87. if (!firstException) {
  88. return;
  89. }
  90. const defaultMechanism = { type: 'generic', handled: true };
  91. const currentMechanism = firstException.mechanism;
  92. firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
  93. if (newMechanism && 'data' in newMechanism) {
  94. const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };
  95. firstException.mechanism.data = mergedData;
  96. }
  97. }
  98. // https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
  99. const SEMVER_REGEXP =
  100. /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
  101. /**
  102. * Represents Semantic Versioning object
  103. */
  104. /**
  105. * Parses input into a SemVer interface
  106. * @param input string representation of a semver version
  107. */
  108. function parseSemver(input) {
  109. const match = input.match(SEMVER_REGEXP) || [];
  110. const major = parseInt(match[1], 10);
  111. const minor = parseInt(match[2], 10);
  112. const patch = parseInt(match[3], 10);
  113. return {
  114. buildmetadata: match[5],
  115. major: isNaN(major) ? undefined : major,
  116. minor: isNaN(minor) ? undefined : minor,
  117. patch: isNaN(patch) ? undefined : patch,
  118. prerelease: match[4],
  119. };
  120. }
  121. /**
  122. * This function adds context (pre/post/line) lines to the provided frame
  123. *
  124. * @param lines string[] containing all lines
  125. * @param frame StackFrame that will be mutated
  126. * @param linesOfContext number of context lines we want to add pre/post
  127. */
  128. function addContextToFrame(lines, frame, linesOfContext = 5) {
  129. // When there is no line number in the frame, attaching context is nonsensical and will even break grouping
  130. if (frame.lineno === undefined) {
  131. return;
  132. }
  133. const maxLines = lines.length;
  134. const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);
  135. frame.pre_context = lines
  136. .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)
  137. .map((line) => snipLine(line, 0));
  138. frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);
  139. frame.post_context = lines
  140. .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)
  141. .map((line) => snipLine(line, 0));
  142. }
  143. /**
  144. * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object
  145. * in question), and marks it captured if not.
  146. *
  147. * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and
  148. * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so
  149. * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because
  150. * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not
  151. * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This
  152. * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we
  153. * see it.
  154. *
  155. * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on
  156. * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent
  157. * object wrapper forms so that this check will always work. However, because we need to flag the exact object which
  158. * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification
  159. * must be done before the exception captured.
  160. *
  161. * @param A thrown exception to check or flag as having been seen
  162. * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)
  163. */
  164. function checkOrSetAlreadyCaught(exception) {
  165. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  166. if (exception && (exception ).__sentry_captured__) {
  167. return true;
  168. }
  169. try {
  170. // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the
  171. // `ExtraErrorData` integration
  172. addNonEnumerableProperty(exception , '__sentry_captured__', true);
  173. } catch (err) {
  174. // `exception` is a primitive, so we can't mark it seen
  175. }
  176. return false;
  177. }
  178. /**
  179. * Checks whether the given input is already an array, and if it isn't, wraps it in one.
  180. *
  181. * @param maybeArray Input to turn into an array, if necessary
  182. * @returns The input, if already an array, or an array with the input as the only element, if not
  183. */
  184. function arrayify(maybeArray) {
  185. return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
  186. }
  187. export { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, arrayify, checkOrSetAlreadyCaught, getEventDescription, parseSemver, uuid4 };
  188. //# sourceMappingURL=misc.js.map