* Gets the time origin and the mode used to determine it. * * Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or * performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin * data as re
()
| 87 | * TODO: move to `@sentry/browser-utils` package. |
| 88 | */ |
| 89 | function getBrowserTimeOrigin(): number | undefined { |
| 90 | const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window; |
| 91 | if (!performance?.now) { |
| 92 | return undefined; |
| 93 | } |
| 94 | |
| 95 | const threshold = 300_000; // 5 minutes in milliseconds |
| 96 | const performanceNow = withRandomSafeContext(() => performance.now()); |
| 97 | const dateNow = safeDateNow(); |
| 98 | |
| 99 | const timeOrigin = performance.timeOrigin; |
| 100 | if (typeof timeOrigin === 'number') { |
| 101 | const timeOriginDelta = Math.abs(timeOrigin + performanceNow - dateNow); |
| 102 | if (timeOriginDelta < threshold) { |
| 103 | return timeOrigin; |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // TODO: Remove all code related to `performance.timing.navigationStart` once we drop support for Safari 14. |
| 108 | // `performance.timeSince` is available in Safari 15. |
| 109 | // see: https://caniuse.com/mdn-api_performance_timeorigin |
| 110 | |
| 111 | // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin |
| 112 | // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. |
| 113 | // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always |
| 114 | // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the |
| 115 | // Date API. |
| 116 | // eslint-disable-next-line typescript/no-deprecated |
| 117 | const navigationStart = performance.timing?.navigationStart; |
| 118 | if (typeof navigationStart === 'number') { |
| 119 | const navigationStartDelta = Math.abs(navigationStart + performanceNow - dateNow); |
| 120 | if (navigationStartDelta < threshold) { |
| 121 | return navigationStart; |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to subtracting |
| 126 | // `performance.now()` from `Date.now()`. |
| 127 | return dateNow - performanceNow; |
| 128 | } |
| 129 | |
| 130 | /** |
| 131 | * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the |
no test coverage detected