@sentry/browser 10.21.0-alpha.1 → 10.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/build/npm/cjs/index.js +0 -3
  2. package/build/npm/cjs/index.js.map +1 -1
  3. package/build/npm/cjs/integrations/httpcontext.js +0 -2
  4. package/build/npm/cjs/integrations/httpcontext.js.map +1 -1
  5. package/build/npm/cjs/profiling/integration.js +108 -46
  6. package/build/npm/cjs/profiling/integration.js.map +1 -1
  7. package/build/npm/cjs/profiling/lifecycleMode/traceLifecycleProfiler.js +343 -0
  8. package/build/npm/cjs/profiling/lifecycleMode/traceLifecycleProfiler.js.map +1 -0
  9. package/build/npm/cjs/profiling/startProfileForSpan.js +16 -0
  10. package/build/npm/cjs/profiling/startProfileForSpan.js.map +1 -1
  11. package/build/npm/cjs/profiling/utils.js +251 -14
  12. package/build/npm/cjs/profiling/utils.js.map +1 -1
  13. package/build/npm/cjs/tracing/request.js +0 -1
  14. package/build/npm/cjs/tracing/request.js.map +1 -1
  15. package/build/npm/esm/index.js +1 -2
  16. package/build/npm/esm/index.js.map +1 -1
  17. package/build/npm/esm/integrations/httpcontext.js +0 -2
  18. package/build/npm/esm/integrations/httpcontext.js.map +1 -1
  19. package/build/npm/esm/package.json +1 -1
  20. package/build/npm/esm/profiling/integration.js +110 -48
  21. package/build/npm/esm/profiling/integration.js.map +1 -1
  22. package/build/npm/esm/profiling/lifecycleMode/traceLifecycleProfiler.js +341 -0
  23. package/build/npm/esm/profiling/lifecycleMode/traceLifecycleProfiler.js.map +1 -0
  24. package/build/npm/esm/profiling/startProfileForSpan.js +16 -0
  25. package/build/npm/esm/profiling/startProfileForSpan.js.map +1 -1
  26. package/build/npm/esm/profiling/utils.js +245 -15
  27. package/build/npm/esm/profiling/utils.js.map +1 -1
  28. package/build/npm/esm/tracing/request.js +0 -1
  29. package/build/npm/esm/tracing/request.js.map +1 -1
  30. package/build/npm/types/feedbackAsync.d.ts +3 -9
  31. package/build/npm/types/feedbackAsync.d.ts.map +1 -1
  32. package/build/npm/types/feedbackSync.d.ts +3 -9
  33. package/build/npm/types/feedbackSync.d.ts.map +1 -1
  34. package/build/npm/types/helpers.d.ts +2 -29
  35. package/build/npm/types/helpers.d.ts.map +1 -1
  36. package/build/npm/types/index.d.ts +1 -2
  37. package/build/npm/types/index.d.ts.map +1 -1
  38. package/build/npm/types/integrations/featureFlags/growthbook/integration.d.ts.map +1 -1
  39. package/build/npm/types/integrations/httpcontext.d.ts.map +1 -1
  40. package/build/npm/types/integrations/webWorker.d.ts.map +1 -1
  41. package/build/npm/types/profiling/integration.d.ts.map +1 -1
  42. package/build/npm/types/profiling/lifecycleMode/traceLifecycleProfiler.d.ts +70 -0
  43. package/build/npm/types/profiling/lifecycleMode/traceLifecycleProfiler.d.ts.map +1 -0
  44. package/build/npm/types/profiling/startProfileForSpan.d.ts.map +1 -1
  45. package/build/npm/types/profiling/utils.d.ts +32 -2
  46. package/build/npm/types/profiling/utils.d.ts.map +1 -1
  47. package/build/npm/types/tracing/browserTracingIntegration.d.ts.map +1 -1
  48. package/build/npm/types/tracing/request.d.ts.map +1 -1
  49. package/build/npm/types-ts3.8/feedbackAsync.d.ts +3 -9
  50. package/build/npm/types-ts3.8/feedbackSync.d.ts +3 -9
  51. package/build/npm/types-ts3.8/helpers.d.ts +2 -29
  52. package/build/npm/types-ts3.8/index.d.ts +1 -2
  53. package/build/npm/types-ts3.8/profiling/lifecycleMode/traceLifecycleProfiler.d.ts +70 -0
  54. package/build/npm/types-ts3.8/profiling/utils.d.ts +32 -2
  55. package/package.json +7 -7
  56. package/build/npm/cjs/integrations/spanstreaming.js +0 -252
  57. package/build/npm/cjs/integrations/spanstreaming.js.map +0 -1
  58. package/build/npm/esm/integrations/spanstreaming.js +0 -250
  59. package/build/npm/esm/integrations/spanstreaming.js.map +0 -1
  60. package/build/npm/types/integrations/spanstreaming.d.ts +0 -5
  61. package/build/npm/types/integrations/spanstreaming.d.ts.map +0 -1
  62. package/build/npm/types-ts3.8/integrations/spanstreaming.d.ts +0 -5
@@ -39,7 +39,6 @@ const integration$4 = require('./integrations/featureFlags/growthbook/integratio
39
39
  const integration$5 = require('./integrations/featureFlags/statsig/integration.js');
40
40
  const diagnoseSdk = require('./diagnose-sdk.js');
41
41
  const webWorker = require('./integrations/webWorker.js');
42
- const spanstreaming = require('./integrations/spanstreaming.js');
43
42
 
44
43
 
45
44
 
@@ -121,7 +120,6 @@ exports.updateSpanName = core.updateSpanName;
121
120
  exports.withActiveSpan = core.withActiveSpan;
122
121
  exports.withIsolationScope = core.withIsolationScope;
123
122
  exports.withScope = core.withScope;
124
- exports.withStreamSpan = core.withStreamSpan;
125
123
  exports.zodErrorsIntegration = core.zodErrorsIntegration;
126
124
  exports.WINDOW = helpers.WINDOW;
127
125
  exports.BrowserClient = client.BrowserClient;
@@ -178,5 +176,4 @@ exports.statsigIntegration = integration$5.statsigIntegration;
178
176
  exports.diagnoseSdkConnectivity = diagnoseSdk.diagnoseSdkConnectivity;
179
177
  exports.registerWebWorker = webWorker.registerWebWorker;
180
178
  exports.webWorkerIntegration = webWorker.webWorkerIntegration;
181
- exports.spanStreamingIntegration = spanstreaming.spanStreamingIntegration;
182
179
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -10,8 +10,6 @@ const helpers = require('../helpers.js');
10
10
  const httpContextIntegration = core.defineIntegration(() => {
11
11
  return {
12
12
  name: 'HttpContext',
13
- // TODO (span-streaming): probably fine to omit this in favour of us globally
14
- // already adding request context data but should double-check this
15
13
  preprocessEvent(event) {
16
14
  // if none of the information we want exists, don't bother
17
15
  if (!helpers.WINDOW.navigator && !helpers.WINDOW.location && !helpers.WINDOW.document) {
@@ -1 +1 @@
1
- {"version":3,"file":"httpcontext.js","sources":["../../../../src/integrations/httpcontext.ts"],"sourcesContent":["import { defineIntegration } from '@sentry/core';\nimport { getHttpRequestData, WINDOW } from '../helpers';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nexport const httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext',\n // TODO (span-streaming): probably fine to omit this in favour of us globally\n // already adding request context data but should double-check this\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const reqData = getHttpRequestData();\n const headers = {\n ...reqData.headers,\n ...event.request?.headers,\n };\n\n event.request = {\n ...reqData,\n ...event.request,\n headers,\n };\n },\n };\n});\n"],"names":["defineIntegration","WINDOW","getHttpRequestData"],"mappings":";;;;;AAGA;AACA;AACA;AACA;MACa,sBAAA,GAAyBA,sBAAiB,CAAC,MAAM;AAC9D,EAAE,OAAO;AACT,IAAI,IAAI,EAAE,aAAa;AACvB;AACA;AACA,IAAI,eAAe,CAAC,KAAK,EAAE;AAC3B;AACA,MAAM,IAAI,CAACC,cAAM,CAAC,aAAa,CAACA,cAAM,CAAC,YAAY,CAACA,cAAM,CAAC,QAAQ,EAAE;AACrE,QAAQ;AACR;;AAEA,MAAM,MAAM,OAAA,GAAUC,0BAAkB,EAAE;AAC1C,MAAM,MAAM,UAAU;AACtB,QAAQ,GAAG,OAAO,CAAC,OAAO;AAC1B,QAAQ,GAAG,KAAK,CAAC,OAAO,EAAE,OAAO;AACjC,OAAO;;AAEP,MAAM,KAAK,CAAC,OAAA,GAAU;AACtB,QAAQ,GAAG,OAAO;AAClB,QAAQ,GAAG,KAAK,CAAC,OAAO;AACxB,QAAQ,OAAO;AACf,OAAO;AACP,KAAK;AACL,GAAG;AACH,CAAC;;;;"}
1
+ {"version":3,"file":"httpcontext.js","sources":["../../../../src/integrations/httpcontext.ts"],"sourcesContent":["import { defineIntegration } from '@sentry/core';\nimport { getHttpRequestData, WINDOW } from '../helpers';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nexport const httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext',\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const reqData = getHttpRequestData();\n const headers = {\n ...reqData.headers,\n ...event.request?.headers,\n };\n\n event.request = {\n ...reqData,\n ...event.request,\n headers,\n };\n },\n };\n});\n"],"names":["defineIntegration","WINDOW","getHttpRequestData"],"mappings":";;;;;AAGA;AACA;AACA;AACA;MACa,sBAAA,GAAyBA,sBAAiB,CAAC,MAAM;AAC9D,EAAE,OAAO;AACT,IAAI,IAAI,EAAE,aAAa;AACvB,IAAI,eAAe,CAAC,KAAK,EAAE;AAC3B;AACA,MAAM,IAAI,CAACC,cAAM,CAAC,aAAa,CAACA,cAAM,CAAC,YAAY,CAACA,cAAM,CAAC,QAAQ,EAAE;AACrE,QAAQ;AACR;;AAEA,MAAM,MAAM,OAAA,GAAUC,0BAAkB,EAAE;AAC1C,MAAM,MAAM,UAAU;AACtB,QAAQ,GAAG,OAAO,CAAC,OAAO;AAC1B,QAAQ,GAAG,KAAK,CAAC,OAAO,EAAE,OAAO;AACjC,OAAO;;AAEP,MAAM,KAAK,CAAC,OAAA,GAAU;AACtB,QAAQ,GAAG,OAAO;AAClB,QAAQ,GAAG,KAAK,CAAC,OAAO;AACxB,QAAQ,OAAO;AACf,OAAO;AACP,KAAK;AACL,GAAG;AACH,CAAC;;;;"}
@@ -2,6 +2,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  const core = require('@sentry/core');
4
4
  const debugBuild = require('../debug-build.js');
5
+ const helpers = require('../helpers.js');
6
+ const traceLifecycleProfiler = require('./lifecycleMode/traceLifecycleProfiler.js');
5
7
  const startProfileForSpan = require('./startProfileForSpan.js');
6
8
  const utils = require('./utils.js');
7
9
 
@@ -11,73 +13,133 @@ const _browserProfilingIntegration = (() => {
11
13
  return {
12
14
  name: INTEGRATION_NAME,
13
15
  setup(client) {
16
+ const options = client.getOptions() ;
17
+
18
+ if (!utils.hasLegacyProfiling(options) && !options.profileLifecycle) {
19
+ // Set default lifecycle mode
20
+ options.profileLifecycle = 'manual';
21
+ }
22
+
23
+ if (utils.hasLegacyProfiling(options) && !options.profilesSampleRate) {
24
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Profiling disabled, no profiling options found.');
25
+ return;
26
+ }
27
+
14
28
  const activeSpan = core.getActiveSpan();
15
29
  const rootSpan = activeSpan && core.getRootSpan(activeSpan);
16
30
 
17
- if (rootSpan && utils.isAutomatedPageLoadSpan(rootSpan)) {
18
- if (utils.shouldProfileSpan(rootSpan)) {
19
- startProfileForSpan.startProfileForSpan(rootSpan);
20
- }
31
+ if (utils.hasLegacyProfiling(options) && options.profileSessionSampleRate !== undefined) {
32
+ debugBuild.DEBUG_BUILD &&
33
+ core.debug.warn(
34
+ '[Profiling] Both legacy profiling (`profilesSampleRate`) and UI profiling settings are defined. `profileSessionSampleRate` has no effect when legacy profiling is enabled.',
35
+ );
21
36
  }
22
37
 
23
- client.on('spanStart', (span) => {
24
- if (span === core.getRootSpan(span) && utils.shouldProfileSpan(span)) {
25
- startProfileForSpan.startProfileForSpan(span);
38
+ // UI PROFILING (Profiling V2)
39
+ if (!utils.hasLegacyProfiling(options)) {
40
+ const sessionSampled = utils.shouldProfileSession(options);
41
+ if (!sessionSampled) {
42
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Session not sampled. Skipping lifecycle profiler initialization.');
26
43
  }
27
- });
28
44
 
29
- client.on('beforeEnvelope', (envelope) => {
30
- // if not profiles are in queue, there is nothing to add to the envelope.
31
- if (!utils.getActiveProfilesCount()) {
32
- return;
33
- }
45
+ const lifecycleMode = options.profileLifecycle;
34
46
 
35
- const profiledTransactionEvents = utils.findProfiledTransactionsFromEnvelope(envelope);
36
- if (!profiledTransactionEvents.length) {
37
- return;
38
- }
47
+ if (lifecycleMode === 'trace') {
48
+ if (!core.hasSpansEnabled(options)) {
49
+ debugBuild.DEBUG_BUILD &&
50
+ core.debug.warn(
51
+ "[Profiling] `profileLifecycle` is 'trace' but tracing is disabled. Set a `tracesSampleRate` or `tracesSampler` to enable span tracing.",
52
+ );
53
+ return;
54
+ }
39
55
 
40
- const profilesToAddToEnvelope = [];
56
+ const traceLifecycleProfiler$1 = new traceLifecycleProfiler.BrowserTraceLifecycleProfiler();
57
+ traceLifecycleProfiler$1.initialize(client, sessionSampled);
41
58
 
42
- for (const profiledTransaction of profiledTransactionEvents) {
43
- const context = profiledTransaction?.contexts;
44
- const profile_id = context?.profile?.['profile_id'];
45
- const start_timestamp = context?.profile?.['start_timestamp'];
59
+ // If there is an active, sampled root span already, notify the profiler
60
+ if (rootSpan) {
61
+ traceLifecycleProfiler$1.notifyRootSpanActive(rootSpan);
62
+ }
46
63
 
47
- if (typeof profile_id !== 'string') {
48
- debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] cannot find profile for a span without a profile context');
49
- continue;
64
+ // In case rootSpan is created slightly after setup -> schedule microtask to re-check and notify.
65
+ helpers.WINDOW.setTimeout(() => {
66
+ const laterActiveSpan = core.getActiveSpan();
67
+ const laterRootSpan = laterActiveSpan && core.getRootSpan(laterActiveSpan);
68
+ if (laterRootSpan) {
69
+ traceLifecycleProfiler$1.notifyRootSpanActive(laterRootSpan);
70
+ }
71
+ }, 0);
72
+ }
73
+ } else {
74
+ // LEGACY PROFILING (v1)
75
+ if (rootSpan && utils.isAutomatedPageLoadSpan(rootSpan)) {
76
+ if (utils.shouldProfileSpanLegacy(rootSpan)) {
77
+ startProfileForSpan.startProfileForSpan(rootSpan);
50
78
  }
79
+ }
51
80
 
52
- if (!profile_id) {
53
- debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] cannot find profile for a span without a profile context');
54
- continue;
81
+ client.on('spanStart', (span) => {
82
+ if (span === core.getRootSpan(span) && utils.shouldProfileSpanLegacy(span)) {
83
+ startProfileForSpan.startProfileForSpan(span);
55
84
  }
85
+ });
56
86
 
57
- // Remove the profile from the span context before sending, relay will take care of the rest.
58
- if (context?.profile) {
59
- delete context.profile;
87
+ client.on('beforeEnvelope', (envelope) => {
88
+ // if not profiles are in queue, there is nothing to add to the envelope.
89
+ if (!utils.getActiveProfilesCount()) {
90
+ return;
60
91
  }
61
92
 
62
- const profile = utils.takeProfileFromGlobalCache(profile_id);
63
- if (!profile) {
64
- debugBuild.DEBUG_BUILD && core.debug.log(`[Profiling] Could not retrieve profile for span: ${profile_id}`);
65
- continue;
93
+ const profiledTransactionEvents = utils.findProfiledTransactionsFromEnvelope(envelope);
94
+ if (!profiledTransactionEvents.length) {
95
+ return;
66
96
  }
67
97
 
68
- const profileEvent = utils.createProfilingEvent(
69
- profile_id,
70
- start_timestamp ,
71
- profile,
72
- profiledTransaction ,
73
- );
74
- if (profileEvent) {
75
- profilesToAddToEnvelope.push(profileEvent);
98
+ const profilesToAddToEnvelope = [];
99
+
100
+ for (const profiledTransaction of profiledTransactionEvents) {
101
+ const context = profiledTransaction?.contexts;
102
+ const profile_id = context?.profile?.['profile_id'];
103
+ const start_timestamp = context?.profile?.['start_timestamp'];
104
+
105
+ if (typeof profile_id !== 'string') {
106
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] cannot find profile for a span without a profile context');
107
+ continue;
108
+ }
109
+
110
+ if (!profile_id) {
111
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] cannot find profile for a span without a profile context');
112
+ continue;
113
+ }
114
+
115
+ // Remove the profile from the span context before sending, relay will take care of the rest.
116
+ if (context?.profile) {
117
+ delete context.profile;
118
+ }
119
+
120
+ const profile = utils.takeProfileFromGlobalCache(profile_id);
121
+ if (!profile) {
122
+ debugBuild.DEBUG_BUILD && core.debug.log(`[Profiling] Could not retrieve profile for span: ${profile_id}`);
123
+ continue;
124
+ }
125
+
126
+ const profileEvent = utils.createProfilingEvent(
127
+ profile_id,
128
+ start_timestamp ,
129
+ profile,
130
+ profiledTransaction ,
131
+ );
132
+ if (profileEvent) {
133
+ profilesToAddToEnvelope.push(profileEvent);
134
+ }
76
135
  }
77
- }
78
136
 
79
- utils.addProfilesToEnvelope(envelope , profilesToAddToEnvelope);
80
- });
137
+ utils.addProfilesToEnvelope(envelope , profilesToAddToEnvelope);
138
+ });
139
+ }
140
+ },
141
+ processEvent(event) {
142
+ return utils.attachProfiledThreadToEvent(event);
81
143
  },
82
144
  };
83
145
  }) ;
@@ -1 +1 @@
1
- {"version":3,"file":"integration.js","sources":["../../../../src/profiling/integration.ts"],"sourcesContent":["import type { EventEnvelope, IntegrationFn, Profile, Span } from '@sentry/core';\nimport { debug, defineIntegration, getActiveSpan, getRootSpan } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { startProfileForSpan } from './startProfileForSpan';\nimport type { ProfiledEvent } from './utils';\nimport {\n addProfilesToEnvelope,\n createProfilingEvent,\n findProfiledTransactionsFromEnvelope,\n getActiveProfilesCount,\n isAutomatedPageLoadSpan,\n shouldProfileSpan,\n takeProfileFromGlobalCache,\n} from './utils';\n\nconst INTEGRATION_NAME = 'BrowserProfiling';\n\nconst _browserProfilingIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n\n if (rootSpan && isAutomatedPageLoadSpan(rootSpan)) {\n if (shouldProfileSpan(rootSpan)) {\n startProfileForSpan(rootSpan);\n }\n }\n\n client.on('spanStart', (span: Span) => {\n if (span === getRootSpan(span) && shouldProfileSpan(span)) {\n startProfileForSpan(span);\n }\n });\n\n client.on('beforeEnvelope', (envelope): void => {\n // if not profiles are in queue, there is nothing to add to the envelope.\n if (!getActiveProfilesCount()) {\n return;\n }\n\n const profiledTransactionEvents = findProfiledTransactionsFromEnvelope(envelope);\n if (!profiledTransactionEvents.length) {\n return;\n }\n\n const profilesToAddToEnvelope: Profile[] = [];\n\n for (const profiledTransaction of profiledTransactionEvents) {\n const context = profiledTransaction?.contexts;\n const profile_id = context?.profile?.['profile_id'];\n const start_timestamp = context?.profile?.['start_timestamp'];\n\n if (typeof profile_id !== 'string') {\n DEBUG_BUILD && debug.log('[Profiling] cannot find profile for a span without a profile context');\n continue;\n }\n\n if (!profile_id) {\n DEBUG_BUILD && debug.log('[Profiling] cannot find profile for a span without a profile context');\n continue;\n }\n\n // Remove the profile from the span context before sending, relay will take care of the rest.\n if (context?.profile) {\n delete context.profile;\n }\n\n const profile = takeProfileFromGlobalCache(profile_id);\n if (!profile) {\n DEBUG_BUILD && debug.log(`[Profiling] Could not retrieve profile for span: ${profile_id}`);\n continue;\n }\n\n const profileEvent = createProfilingEvent(\n profile_id,\n start_timestamp as number | undefined,\n profile,\n profiledTransaction as ProfiledEvent,\n );\n if (profileEvent) {\n profilesToAddToEnvelope.push(profileEvent);\n }\n }\n\n addProfilesToEnvelope(envelope as EventEnvelope, profilesToAddToEnvelope);\n });\n },\n };\n}) satisfies IntegrationFn;\n\nexport const browserProfilingIntegration = defineIntegration(_browserProfilingIntegration);\n"],"names":["getActiveSpan","getRootSpan","isAutomatedPageLoadSpan","shouldProfileSpan","startProfileForSpan","getActiveProfilesCount","findProfiledTransactionsFromEnvelope","DEBUG_BUILD","debug","takeProfileFromGlobalCache","createProfilingEv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AAG,iBAAiB,CAAC;;AAEvE,UAAU,IAAI,OAAO,UAAA,KAAe,QAAQ,EAAE;AAC9C,YAAYC,0BAAeC,UAAK,CAAC,GAAG,CAAC,sEAAsE,CAAC;AAC5G,YAAY;AACZ;;AAEA,UAAU,IAAI,CAAC,UAAU,EAAE;AAC3B,YAAYD,0BAAeC,UAAK,CAAC,GAAG,CAAC,sEAAsE,CAAC;AAC5G,YAAY;AACZ;;AAEA;AACA,UAAU,IAAI,OAAO,EAAE,OAAO,EAAE;AAChC,YAAY,OAAO,OAAO,CAAC,OAAO;AAClC;;AAEA,UAAU,MAAM,OAAA,GAAUC,gCAA0B,CAAC,UAAU,CAAC;AAChE,UAAU,IAAI,CAAC,OAAO,EAAE;AACxB,YAAYF,sBAAA,IAAeC,UAAK,CAAC,GAAG,CAAC,CAAC,iDAAiD,EAAE,UAAU,CAAC,CAAA,CAAA;AACA,YAAA;AACA;;AAEA,UAAA,MAAA,YAAA,GAAAE,0BAAA;AACA,YAAA,UAAA;AACA,YAAA,eAAA;AACA,YAAA,OAAA;AACA,YAAA,mBAAA;AACA,WAAA;AACA,UAAA,IAAA,YAAA,EAAA;AACA,YAAA,uBAAA,CAAA,IAAA,CAAA,YAAA,CAAA;AACA;AACA;;AAEA,QAAAC,2BAAA,CAAA,QAAA,GAAA,uBAAA,CAAA;AACA,OAAA,CAAA;AACA,KAAA;AACA,GAAA;AACA,CAAA,CAAA;;AAEA,MAAA,2BAAA,GAAAC,sBAAA,CAAA,4BAAA;;;;"}
1
+ {"version":3,"file":"integration.js","sources":["../../../../src/profiling/integration.ts"],"sourcesContent":["import type { EventEnvelope, IntegrationFn, Profile, Span } from '@sentry/core';\nimport { debug, defineIntegration, getActiveSpan, getRootSpan, hasSpansEnabled } from '@sentry/core';\nimport type { BrowserOptions } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\nimport { BrowserTraceLifecycleProfiler } from './lifecycleMode/traceLifecycleProfiler';\nimport { startProfileForSpan } from './startProfileForSpan';\nimport type { ProfiledEvent } from './utils';\nimport {\n addProfilesToEnvelope,\n attachProfiledThreadToEvent,\n createProfilingEvent,\n findProfiledTransactionsFromEnvelope,\n getActiveProfilesCount,\n hasLegacyProfiling,\n isAutomatedPageLoadSpan,\n shouldProfileSession,\n shouldProfileSpanLegacy,\n takeProfileFromGlobalCache,\n} from './utils';\n\nconst INTEGRATION_NAME = 'BrowserProfiling';\n\nconst _browserProfilingIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n const options = client.getOptions() as BrowserOptions;\n\n if (!hasLegacyProfiling(options) && !options.profileLifecycle) {\n // Set default lifecycle mode\n options.profileLifecycle = 'manual';\n }\n\n if (hasLegacyProfiling(options) && !options.profilesSampleRate) {\n DEBUG_BUILD && debug.log('[Profiling] Profiling disabled, no profiling options found.');\n return;\n }\n\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n\n if (hasLegacyProfiling(options) && options.profileSessionSampleRate !== undefined) {\n DEBUG_BUILD &&\n debug.warn(\n '[Profiling] Both legacy profiling (`profilesSampleRate`) and UI profiling settings are defined. `profileSessionSampleRate` has no effect when legacy profiling is enabled.',\n );\n }\n\n // UI PROFILING (Profiling V2)\n if (!hasLegacyProfiling(options)) {\n const sessionSampled = shouldProfileSession(options);\n if (!sessionSampled) {\n DEBUG_BUILD && debug.log('[Profiling] Session not sampled. Skipping lifecycle profiler initialization.');\n }\n\n const lifecycleMode = options.profileLifecycle;\n\n if (lifecycleMode === 'trace') {\n if (!hasSpansEnabled(options)) {\n DEBUG_BUILD &&\n debug.warn(\n \"[Profiling] `profileLifecycle` is 'trace' but tracing is disabled. Set a `tracesSampleRate` or `tracesSampler` to enable span tracing.\",\n );\n return;\n }\n\n const traceLifecycleProfiler = new BrowserTraceLifecycleProfiler();\n traceLifecycleProfiler.initialize(client, sessionSampled);\n\n // If there is an active, sampled root span already, notify the profiler\n if (rootSpan) {\n traceLifecycleProfiler.notifyRootSpanActive(rootSpan);\n }\n\n // In case rootSpan is created slightly after setup -> schedule microtask to re-check and notify.\n WINDOW.setTimeout(() => {\n const laterActiveSpan = getActiveSpan();\n const laterRootSpan = laterActiveSpan && getRootSpan(laterActiveSpan);\n if (laterRootSpan) {\n traceLifecycleProfiler.notifyRootSpanActive(laterRootSpan);\n }\n }, 0);\n }\n } else {\n // LEGACY PROFILING (v1)\n if (rootSpan && isAutomatedPageLoadSpan(rootSpan)) {\n if (shouldProfileSpanLegacy(rootSpan)) {\n startProfileForSpan(rootSpan);\n }\n }\n\n client.on('spanStart', (span: Span) => {\n if (span === getRootSpan(span) && shouldProfileSpanLegacy(span)) {\n startProfileForSpan(span);\n }\n });\n\n client.on('beforeEnvelope', (envelope): void => {\n // if not profiles are in queue, there is nothing to add to the envelope.\n if (!getActiveProfilesCount()) {\n return;\n }\n\n const profiledTransactionEvents = findProfiledTransactionsFromEnvelope(envelope);\n if (!profiledTransactionEvents.length) {\n return;\n }\n\n const profilesToAddToEnvelope: Profile[] = [];\n\n for (const profiledTransaction of profiledTransactionEvents) {\n const context = profiledTransaction?.contexts;\n const profile_id = context?.profile?.['profile_id'];\n const start_timestamp = context?.profile?.['start_timestamp'];\n\n if (typeof profile_id !== 'string') {\n DEBUG_BUILD && debug.log('[Profiling] cannot find profile for a span without a profile context');\n continue;\n }\n\n if (!profile_id) {\n DEBUG_BUILD && debug.log('[Profiling] cannot find profile for a span without a profile context');\n continue;\n }\n\n // Remove the profile from the span context before sending, relay will take care of the rest.\n if (context?.profile) {\n delete context.profile;\n }\n\n const profile = takeProfileFromGlobalCache(profile_id);\n if (!profile) {\n DEBUG_BUILD && debug.log(`[Profiling] Could not retrieve profile for span: ${profile_id}`);\n continue;\n }\n\n const profileEvent = createProfilingEvent(\n profile_id,\n start_timestamp as number | undefined,\n profile,\n profiledTransaction as ProfiledEvent,\n );\n if (profileEvent) {\n profilesToAddToEnvelope.push(profileEvent);\n }\n }\n\n addProfilesToEnvelope(envelope as EventEnvelope, profilesToAddToEnvelope);\n });\n }\n },\n processEvent(event) {\n return attachProfiledThreadToEvent(event);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const browserProfilingIntegration = defineIntegration(_browserProfilingIntegration);\n"],"names":["hasLegacyProfiling","DEBUG_BUILD","debug","getActiveSpan","getRootSpan","shouldProfileSession","hasSpansEnabled","traceLifecycleProfiler","BrowserTraceLifecycleProfiler","WINDOW","isAutomatedPageLoadSpan","shouldProfileSpanLegacy","startProfileForSpan","getActiveProfilesCount","findProfiledTransactionsFromEnvelope","takeProfileFromGlobalCache","createProfilingEvent","addProfilesToEnvelope","attachProfiledThreadToEvent","defineIntegration"],"mappings":";;;;;;;;;AAqBA,MAAM,gBAAA,GAAmB,kBAAkB;;AAE3C,MAAM,4BAAA,IAAgC,MAAM;AAC5C,EAAE,OAAO;AACT,IAAI,IAAI,EAAE,gBAAgB;AAC1B,IAAI,KAAK,CAAC,MAAM,EAAE;AAClB,MAAM,MAAM,OAAA,GAAU,MAAM,CAAC,UAAU,EAAC;;AAExC,MAAM,IAAI,CAACA,wBAAkB,CAAC,OAAO,CAAA,IAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE;AACrE;AACA,QAAQ,OAAO,CAAC,gBAAA,GAAmB,QAAQ;AAC3C;;AAEA,MAAM,IAAIA,wBAAkB,CAAC,OAAO,CAAA,IAAK,CAAC,OAAO,CAAC,kBAAkB,EAAE;AACtE,QAAQC,0BAAeC,UAAK,CAAC,GAAG,CAAC,6DAA6D,CAAC;AAC/F,QAAQ;AACR;;AAEA,MAAM,MAAM,UAAA,GAAaC,kBAAa,EAAE;AACxC,MAAM,MAAM,WAAW,UAAA,IAAcC,gBAAW,CAAC,UAAU,CAAC;;AAE5D,MAAM,IAAIJ,wBAAkB,CAAC,OAAO,CAAA,IAAK,OAAO,CAAC,wBAAA,KAA6B,SAAS,EAAE;AACzF,QAAQC,sBAAA;AACR,UAAUC,UAAK,CAAC,IAAI;AACpB,YAAY,4KAA4K;AACx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DAAiD,EAAE,UAAU,CAAC,CAAA,CAAA;AACA,cAAA;AACA;;AAEA,YAAA,MAAA,YAAA,GAAAc,0BAAA;AACA,cAAA,UAAA;AACA,cAAA,eAAA;AACA,cAAA,OAAA;AACA,cAAA,mBAAA;AACA,aAAA;AACA,YAAA,IAAA,YAAA,EAAA;AACA,cAAA,uBAAA,CAAA,IAAA,CAAA,YAAA,CAAA;AACA;AACA;;AAEA,UAAAC,2BAAA,CAAA,QAAA,GAAA,uBAAA,CAAA;AACA,SAAA,CAAA;AACA;AACA,KAAA;AACA,IAAA,YAAA,CAAA,KAAA,EAAA;AACA,MAAA,OAAAC,iCAAA,CAAA,KAAA,CAAA;AACA,KAAA;AACA,GAAA;AACA,CAAA,CAAA;;AAEA,MAAA,2BAAA,GAAAC,sBAAA,CAAA,4BAAA;;;;"}
@@ -0,0 +1,343 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const core = require('@sentry/core');
4
+ const debugBuild = require('../../debug-build.js');
5
+ const utils = require('../utils.js');
6
+
7
+ const CHUNK_INTERVAL_MS = 60000; // 1 minute
8
+ // Maximum length for trace lifecycle profiling per root span (e.g. if spanEnd never fires)
9
+ const MAX_ROOT_SPAN_PROFILE_MS = 300000; // 5 minutes
10
+
11
+ /**
12
+ * Browser trace-lifecycle profiler (UI Profiling / Profiling V2):
13
+ * - Starts when the first sampled root span starts
14
+ * - Stops when the last sampled root span ends
15
+ * - While running, periodically stops and restarts the JS self-profiling API to collect chunks
16
+ *
17
+ * Profiles are emitted as standalone `profile_chunk` envelopes either when:
18
+ * - there are no more sampled root spans, or
19
+ * - the 60s chunk timer elapses while profiling is running.
20
+ */
21
+ class BrowserTraceLifecycleProfiler {
22
+
23
+ // For keeping track of active root spans
24
+
25
+ // ID for Profiler session
26
+
27
+ constructor() {
28
+ this._client = undefined;
29
+ this._profiler = undefined;
30
+ this._chunkTimer = undefined;
31
+ this._activeRootSpanIds = new Set();
32
+ this._rootSpanTimeouts = new Map();
33
+ this._profilerId = undefined;
34
+ this._isRunning = false;
35
+ this._sessionSampled = false;
36
+ }
37
+
38
+ /**
39
+ * Initialize the profiler with client and session sampling decision computed by the integration.
40
+ */
41
+ initialize(client, sessionSampled) {
42
+ // One Profiler ID per profiling session (user session)
43
+ this._profilerId = core.uuid4();
44
+
45
+ debugBuild.DEBUG_BUILD && core.debug.log("[Profiling] Initializing profiler (lifecycle='trace').");
46
+
47
+ this._client = client;
48
+ this._sessionSampled = sessionSampled;
49
+
50
+ client.on('spanStart', span => {
51
+ if (!this._sessionSampled) {
52
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Session not sampled because of negative sampling decision.');
53
+ return;
54
+ }
55
+ if (span !== core.getRootSpan(span)) {
56
+ return;
57
+ }
58
+ // Only count sampled root spans
59
+ if (!span.isRecording()) {
60
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Discarding profile because root span was not sampled.');
61
+ return;
62
+ }
63
+
64
+ // Matching root spans with profiles
65
+ core.getGlobalScope().setContext('profile', {
66
+ profiler_id: this._profilerId,
67
+ });
68
+
69
+ const spanId = span.spanContext().spanId;
70
+ if (!spanId) {
71
+ return;
72
+ }
73
+ if (this._activeRootSpanIds.has(spanId)) {
74
+ return;
75
+ }
76
+
77
+ this._activeRootSpanIds.add(spanId);
78
+ const rootSpanCount = this._activeRootSpanIds.size;
79
+
80
+ const timeout = setTimeout(() => {
81
+ this._onRootSpanTimeout(spanId);
82
+ }, MAX_ROOT_SPAN_PROFILE_MS);
83
+ this._rootSpanTimeouts.set(spanId, timeout);
84
+
85
+ if (rootSpanCount === 1) {
86
+ debugBuild.DEBUG_BUILD &&
87
+ core.debug.log(
88
+ `[Profiling] Root span with ID ${spanId} started. Will continue profiling for as long as there are active root spans (currently: ${rootSpanCount}).`,
89
+ );
90
+
91
+ this.start();
92
+ }
93
+ });
94
+
95
+ client.on('spanEnd', span => {
96
+ if (!this._sessionSampled) {
97
+ return;
98
+ }
99
+
100
+ const spanId = span.spanContext().spanId;
101
+ if (!spanId || !this._activeRootSpanIds.has(spanId)) {
102
+ return;
103
+ }
104
+
105
+ this._activeRootSpanIds.delete(spanId);
106
+ const rootSpanCount = this._activeRootSpanIds.size;
107
+
108
+ debugBuild.DEBUG_BUILD &&
109
+ core.debug.log(
110
+ `[Profiling] Root span with ID ${spanId} ended. Will continue profiling for as long as there are active root spans (currently: ${rootSpanCount}).`,
111
+ );
112
+ if (rootSpanCount === 0) {
113
+ this._collectCurrentChunk().catch(e => {
114
+ debugBuild.DEBUG_BUILD && core.debug.error('[Profiling] Failed to collect current profile chunk on `spanEnd`:', e);
115
+ });
116
+
117
+ this.stop();
118
+ }
119
+ });
120
+ }
121
+
122
+ /**
123
+ * Handle an already-active root span at integration setup time.
124
+ */
125
+ notifyRootSpanActive(rootSpan) {
126
+ if (!this._sessionSampled) {
127
+ return;
128
+ }
129
+
130
+ const spanId = rootSpan.spanContext().spanId;
131
+ if (!spanId || this._activeRootSpanIds.has(spanId)) {
132
+ return;
133
+ }
134
+
135
+ this._activeRootSpanIds.add(spanId);
136
+
137
+ const rootSpanCount = this._activeRootSpanIds.size;
138
+
139
+ if (rootSpanCount === 1) {
140
+ debugBuild.DEBUG_BUILD &&
141
+ core.debug.log('[Profiling] Detected already active root span during setup. Active root spans now:', rootSpanCount);
142
+
143
+ this.start();
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Start profiling if not already running.
149
+ */
150
+ start() {
151
+ if (this._isRunning) {
152
+ return;
153
+ }
154
+ this._isRunning = true;
155
+
156
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Started profiling with profile ID:', this._profilerId);
157
+
158
+ this._startProfilerInstance();
159
+
160
+ if (!this._profiler) {
161
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Stopping trace lifecycle profiling.');
162
+ this._resetProfilerInfo();
163
+ return;
164
+ }
165
+
166
+ this._startPeriodicChunking();
167
+ }
168
+
169
+ /**
170
+ * Stop profiling; final chunk will be collected and sent.
171
+ */
172
+ stop() {
173
+ if (!this._isRunning) {
174
+ return;
175
+ }
176
+
177
+ this._isRunning = false;
178
+ if (this._chunkTimer) {
179
+ clearTimeout(this._chunkTimer);
180
+ this._chunkTimer = undefined;
181
+ }
182
+
183
+ this._clearAllRootSpanTimeouts();
184
+
185
+ // Collect whatever was currently recording
186
+ this._collectCurrentChunk().catch(e => {
187
+ debugBuild.DEBUG_BUILD && core.debug.error('[Profiling] Failed to collect current profile chunk on `stop()`:', e);
188
+ });
189
+ }
190
+
191
+ /**
192
+ * Resets profiling information from scope and resets running state
193
+ */
194
+ _resetProfilerInfo() {
195
+ this._isRunning = false;
196
+ core.getGlobalScope().setContext('profile', {});
197
+ }
198
+
199
+ /**
200
+ * Clear and reset all per-root-span timeouts.
201
+ */
202
+ _clearAllRootSpanTimeouts() {
203
+ this._rootSpanTimeouts.forEach(timeout => clearTimeout(timeout));
204
+ this._rootSpanTimeouts.clear();
205
+ }
206
+
207
+ /**
208
+ * Start a profiler instance if needed.
209
+ */
210
+ _startProfilerInstance() {
211
+ if (this._profiler?.stopped === false) {
212
+ return;
213
+ }
214
+ const profiler = utils.startJSSelfProfile();
215
+ if (!profiler) {
216
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Failed to start JS Profiler in trace lifecycle.');
217
+ return;
218
+ }
219
+ this._profiler = profiler;
220
+ }
221
+
222
+ /**
223
+ * Schedule the next 60s chunk while running.
224
+ * Each tick collects a chunk and restarts the profiler.
225
+ * A chunk should be closed when there are no active root spans anymore OR when the maximum chunk interval is reached.
226
+ */
227
+ _startPeriodicChunking() {
228
+ if (!this._isRunning) {
229
+ return;
230
+ }
231
+
232
+ this._chunkTimer = setTimeout(() => {
233
+ this._collectCurrentChunk().catch(e => {
234
+ debugBuild.DEBUG_BUILD && core.debug.error('[Profiling] Failed to collect current profile chunk during periodic chunking:', e);
235
+ });
236
+
237
+ if (this._isRunning) {
238
+ this._startProfilerInstance();
239
+
240
+ if (!this._profiler) {
241
+ // If restart failed, stop scheduling further chunks and reset context.
242
+ this._resetProfilerInfo();
243
+ return;
244
+ }
245
+
246
+ this._startPeriodicChunking();
247
+ }
248
+ }, CHUNK_INTERVAL_MS);
249
+ }
250
+
251
+ /**
252
+ * Handle timeout for a specific root span ID to avoid indefinitely running profiler if `spanEnd` never fires.
253
+ * If this was the last active root span, collect the current chunk and stop profiling.
254
+ */
255
+ _onRootSpanTimeout(rootSpanId) {
256
+ // If span already ended, ignore
257
+ if (!this._rootSpanTimeouts.has(rootSpanId)) {
258
+ return;
259
+ }
260
+ this._rootSpanTimeouts.delete(rootSpanId);
261
+
262
+ if (!this._activeRootSpanIds.has(rootSpanId)) {
263
+ return;
264
+ }
265
+
266
+ debugBuild.DEBUG_BUILD &&
267
+ core.debug.log(
268
+ `[Profiling] Reached 5-minute timeout for root span ${rootSpanId}. You likely started a manual root span that never called \`.end()\`.`,
269
+ );
270
+
271
+ this._activeRootSpanIds.delete(rootSpanId);
272
+
273
+ const rootSpanCount = this._activeRootSpanIds.size;
274
+ if (rootSpanCount === 0) {
275
+ this.stop();
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Stop the current profiler, convert and send a profile chunk.
281
+ */
282
+ async _collectCurrentChunk() {
283
+ const prevProfiler = this._profiler;
284
+ this._profiler = undefined;
285
+
286
+ if (!prevProfiler) {
287
+ return;
288
+ }
289
+
290
+ try {
291
+ const profile = await prevProfiler.stop();
292
+
293
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
294
+ const chunk = utils.createProfileChunkPayload(profile, this._client, this._profilerId);
295
+
296
+ // Validate chunk before sending
297
+ const validationReturn = utils.validateProfileChunk(chunk);
298
+ if ('reason' in validationReturn) {
299
+ debugBuild.DEBUG_BUILD &&
300
+ core.debug.log(
301
+ '[Profiling] Discarding invalid profile chunk (this is probably a bug in the SDK):',
302
+ validationReturn.reason,
303
+ );
304
+ return;
305
+ }
306
+
307
+ this._sendProfileChunk(chunk);
308
+
309
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Collected browser profile chunk.');
310
+ } catch (e) {
311
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Error while stopping JS Profiler for chunk:', e);
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Send a profile chunk as a standalone envelope.
317
+ */
318
+ _sendProfileChunk(chunk) {
319
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
320
+ const client = this._client;
321
+
322
+ const sdkInfo = core.getSdkMetadataForEnvelopeHeader(client.getSdkMetadata?.());
323
+ const dsn = client.getDsn();
324
+ const tunnel = client.getOptions().tunnel;
325
+
326
+ const envelope = core.createEnvelope(
327
+ {
328
+ event_id: core.uuid4(),
329
+ sent_at: new Date().toISOString(),
330
+ ...(sdkInfo && { sdk: sdkInfo }),
331
+ ...(!!tunnel && dsn && { dsn: core.dsnToString(dsn) }),
332
+ },
333
+ [[{ type: 'profile_chunk' }, chunk]],
334
+ );
335
+
336
+ client.sendEnvelope(envelope).then(null, reason => {
337
+ debugBuild.DEBUG_BUILD && core.debug.error('Error while sending profile chunk envelope:', reason);
338
+ });
339
+ }
340
+ }
341
+
342
+ exports.BrowserTraceLifecycleProfiler = BrowserTraceLifecycleProfiler;
343
+ //# sourceMappingURL=traceLifecycleProfiler.js.map