router.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { logger, browserPerformanceTimeOrigin, addHistoryInstrumentationHandler } from '@sentry/utils';
  2. import { DEBUG_BUILD } from '../common/debug-build.js';
  3. import { WINDOW } from './types.js';
  4. /**
  5. * Default function implementing pageload and navigation transactions
  6. */
  7. function instrumentRoutingWithDefaults(
  8. customStartTransaction,
  9. startTransactionOnPageLoad = true,
  10. startTransactionOnLocationChange = true,
  11. ) {
  12. if (!WINDOW || !WINDOW.location) {
  13. DEBUG_BUILD && logger.warn('Could not initialize routing instrumentation due to invalid location');
  14. return;
  15. }
  16. let startingUrl = WINDOW.location.href;
  17. let activeTransaction;
  18. if (startTransactionOnPageLoad) {
  19. activeTransaction = customStartTransaction({
  20. name: WINDOW.location.pathname,
  21. // pageload should always start at timeOrigin (and needs to be in s, not ms)
  22. startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,
  23. op: 'pageload',
  24. origin: 'auto.pageload.browser',
  25. metadata: { source: 'url' },
  26. });
  27. }
  28. if (startTransactionOnLocationChange) {
  29. addHistoryInstrumentationHandler(({ to, from }) => {
  30. /**
  31. * This early return is there to account for some cases where a navigation transaction starts right after
  32. * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't
  33. * create an uneccessary navigation transaction.
  34. *
  35. * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also
  36. * only be caused in certain development environments where the usage of a hot module reloader is causing
  37. * errors.
  38. */
  39. if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {
  40. startingUrl = undefined;
  41. return;
  42. }
  43. if (from !== to) {
  44. startingUrl = undefined;
  45. if (activeTransaction) {
  46. DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);
  47. // If there's an open transaction on the scope, we need to finish it before creating an new one.
  48. activeTransaction.end();
  49. }
  50. activeTransaction = customStartTransaction({
  51. name: WINDOW.location.pathname,
  52. op: 'navigation',
  53. origin: 'auto.navigation.browser',
  54. metadata: { source: 'url' },
  55. });
  56. }
  57. });
  58. }
  59. }
  60. export { instrumentRoutingWithDefaults };
  61. //# sourceMappingURL=router.js.map