@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"traceLifecycleProfiler.js","sources":["../../../../../src/profiling/lifecycleMode/traceLifecycleProfiler.ts"],"sourcesContent":["import type { Client, ProfileChunk, Span } from '@sentry/core';\nimport {\n type ProfileChunkEnvelope,\n createEnvelope,\n debug,\n dsnToString,\n getGlobalScope,\n getRootSpan,\n getSdkMetadataForEnvelopeHeader,\n uuid4,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { JSSelfProfiler } from '../jsSelfProfiling';\nimport { createProfileChunkPayload, startJSSelfProfile, validateProfileChunk } from '../utils';\n\nconst CHUNK_INTERVAL_MS = 60_000; // 1 minute\n// Maximum length for trace lifecycle profiling per root span (e.g. if spanEnd never fires)\nconst MAX_ROOT_SPAN_PROFILE_MS = 300_000; // 5 minutes\n\n/**\n * Browser trace-lifecycle profiler (UI Profiling / Profiling V2):\n * - Starts when the first sampled root span starts\n * - Stops when the last sampled root span ends\n * - While running, periodically stops and restarts the JS self-profiling API to collect chunks\n *\n * Profiles are emitted as standalone `profile_chunk` envelopes either when:\n * - there are no more sampled root spans, or\n * - the 60s chunk timer elapses while profiling is running.\n */\nexport class BrowserTraceLifecycleProfiler {\n private _client: Client | undefined;\n private _profiler: JSSelfProfiler | undefined;\n private _chunkTimer: ReturnType<typeof setTimeout> | undefined;\n // For keeping track of active root spans\n private _activeRootSpanIds: Set<string>;\n private _rootSpanTimeouts: Map<string, ReturnType<typeof setTimeout>>;\n // ID for Profiler session\n private _profilerId: string | undefined;\n private _isRunning: boolean;\n private _sessionSampled: boolean;\n\n public constructor() {\n this._client = undefined;\n this._profiler = undefined;\n this._chunkTimer = undefined;\n this._activeRootSpanIds = new Set<string>();\n this._rootSpanTimeouts = new Map<string, ReturnType<typeof setTimeout>>();\n this._profilerId = undefined;\n this._isRunning = false;\n this._sessionSampled = false;\n }\n\n /**\n * Initialize the profiler with client and session sampling decision computed by the integration.\n */\n public initialize(client: Client, sessionSampled: boolean): void {\n // One Profiler ID per profiling session (user session)\n this._profilerId = uuid4();\n\n DEBUG_BUILD && debug.log(\"[Profiling] Initializing profiler (lifecycle='trace').\");\n\n this._client = client;\n this._sessionSampled = sessionSampled;\n\n client.on('spanStart', span => {\n if (!this._sessionSampled) {\n DEBUG_BUILD && debug.log('[Profiling] Session not sampled because of negative sampling decision.');\n return;\n }\n if (span !== getRootSpan(span)) {\n return;\n }\n // Only count sampled root spans\n if (!span.isRecording()) {\n DEBUG_BUILD && debug.log('[Profiling] Discarding profile because root span was not sampled.');\n return;\n }\n\n // Matching root spans with profiles\n getGlobalScope().setContext('profile', {\n profiler_id: this._profilerId,\n });\n\n const spanId = span.spanContext().spanId;\n if (!spanId) {\n return;\n }\n if (this._activeRootSpanIds.has(spanId)) {\n return;\n }\n\n this._activeRootSpanIds.add(spanId);\n const rootSpanCount = this._activeRootSpanIds.size;\n\n const timeout = setTimeout(() => {\n this._onRootSpanTimeout(spanId);\n }, MAX_ROOT_SPAN_PROFILE_MS);\n this._rootSpanTimeouts.set(spanId, timeout);\n\n if (rootSpanCount === 1) {\n DEBUG_BUILD &&\n debug.log(\n `[Profiling] Root span with ID ${spanId} started. Will continue profiling for as long as there are active root spans (currently: ${rootSpanCount}).`,\n );\n\n this.start();\n }\n });\n\n client.on('spanEnd', span => {\n if (!this._sessionSampled) {\n return;\n }\n\n const spanId = span.spanContext().spanId;\n if (!spanId || !this._activeRootSpanIds.has(spanId)) {\n return;\n }\n\n this._activeRootSpanIds.delete(spanId);\n const rootSpanCount = this._activeRootSpanIds.size;\n\n DEBUG_BUILD &&\n debug.log(\n `[Profiling] Root span with ID ${spanId} ended. Will continue profiling for as long as there are active root spans (currently: ${rootSpanCount}).`,\n );\n if (rootSpanCount === 0) {\n this._collectCurrentChunk().catch(e => {\n DEBUG_BUILD && debug.error('[Profiling] Failed to collect current profile chunk on `spanEnd`:', e);\n });\n\n this.stop();\n }\n });\n }\n\n /**\n * Handle an already-active root span at integration setup time.\n */\n public notifyRootSpanActive(rootSpan: Span): void {\n if (!this._sessionSampled) {\n return;\n }\n\n const spanId = rootSpan.spanContext().spanId;\n if (!spanId || this._activeRootSpanIds.has(spanId)) {\n return;\n }\n\n this._activeRootSpanIds.add(spanId);\n\n const rootSpanCount = this._activeRootSpanIds.size;\n\n if (rootSpanCount === 1) {\n DEBUG_BUILD &&\n debug.log('[Profiling] Detected already active root span during setup. Active root spans now:', rootSpanCount);\n\n this.start();\n }\n }\n\n /**\n * Start profiling if not already running.\n */\n public start(): void {\n if (this._isRunning) {\n return;\n }\n this._isRunning = true;\n\n DEBUG_BUILD && debug.log('[Profiling] Started profiling with profile ID:', this._profilerId);\n\n this._startProfilerInstance();\n\n if (!this._profiler) {\n DEBUG_BUILD && debug.log('[Profiling] Stopping trace lifecycle profiling.');\n this._resetProfilerInfo();\n return;\n }\n\n this._startPeriodicChunking();\n }\n\n /**\n * Stop profiling; final chunk will be collected and sent.\n */\n public stop(): void {\n if (!this._isRunning) {\n return;\n }\n\n this._isRunning = false;\n if (this._chunkTimer) {\n clearTimeout(this._chunkTimer);\n this._chunkTimer = undefined;\n }\n\n this._clearAllRootSpanTimeouts();\n\n // Collect whatever was currently recording\n this._collectCurrentChunk().catch(e => {\n DEBUG_BUILD && debug.error('[Profiling] Failed to collect current profile chunk on `stop()`:', e);\n });\n }\n\n /**\n * Resets profiling information from scope and resets running state\n */\n private _resetProfilerInfo(): void {\n this._isRunning = false;\n getGlobalScope().setContext('profile', {});\n }\n\n /**\n * Clear and reset all per-root-span timeouts.\n */\n private _clearAllRootSpanTimeouts(): void {\n this._rootSpanTimeouts.forEach(timeout => clearTimeout(timeout));\n this._rootSpanTimeouts.clear();\n }\n\n /**\n * Start a profiler instance if needed.\n */\n private _startProfilerInstance(): void {\n if (this._profiler?.stopped === false) {\n return;\n }\n const profiler = startJSSelfProfile();\n if (!profiler) {\n DEBUG_BUILD && debug.log('[Profiling] Failed to start JS Profiler in trace lifecycle.');\n return;\n }\n this._profiler = profiler;\n }\n\n /**\n * Schedule the next 60s chunk while running.\n * Each tick collects a chunk and restarts the profiler.\n * A chunk should be closed when there are no active root spans anymore OR when the maximum chunk interval is reached.\n */\n private _startPeriodicChunking(): void {\n if (!this._isRunning) {\n return;\n }\n\n this._chunkTimer = setTimeout(() => {\n this._collectCurrentChunk().catch(e => {\n DEBUG_BUILD && debug.error('[Profiling] Failed to collect current profile chunk during periodic chunking:', e);\n });\n\n if (this._isRunning) {\n this._startProfilerInstance();\n\n if (!this._profiler) {\n // If restart failed, stop scheduling further chunks and reset context.\n this._resetProfilerInfo();\n return;\n }\n\n this._startPeriodicChunking();\n }\n }, CHUNK_INTERVAL_MS);\n }\n\n /**\n * Handle timeout for a specific root span ID to avoid indefinitely running profiler if `spanEnd` never fires.\n * If this was the last active root span, collect the current chunk and stop profiling.\n */\n private _onRootSpanTimeout(rootSpanId: string): void {\n // If span already ended, ignore\n if (!this._rootSpanTimeouts.has(rootSpanId)) {\n return;\n }\n this._rootSpanTimeouts.delete(rootSpanId);\n\n if (!this._activeRootSpanIds.has(rootSpanId)) {\n return;\n }\n\n DEBUG_BUILD &&\n debug.log(\n `[Profiling] Reached 5-minute timeout for root span ${rootSpanId}. You likely started a manual root span that never called \\`.end()\\`.`,\n );\n\n this._activeRootSpanIds.delete(rootSpanId);\n\n const rootSpanCount = this._activeRootSpanIds.size;\n if (rootSpanCount === 0) {\n this.stop();\n }\n }\n\n /**\n * Stop the current profiler, convert and send a profile chunk.\n */\n private async _collectCurrentChunk(): Promise<void> {\n const prevProfiler = this._profiler;\n this._profiler = undefined;\n\n if (!prevProfiler) {\n return;\n }\n\n try {\n const profile = await prevProfiler.stop();\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const chunk = createProfileChunkPayload(profile, this._client!, this._profilerId);\n\n // Validate chunk before sending\n const validationReturn = validateProfileChunk(chunk);\n if ('reason' in validationReturn) {\n DEBUG_BUILD &&\n debug.log(\n '[Profiling] Discarding invalid profile chunk (this is probably a bug in the SDK):',\n validationReturn.reason,\n );\n return;\n }\n\n this._sendProfileChunk(chunk);\n\n DEBUG_BUILD && debug.log('[Profiling] Collected browser profile chunk.');\n } catch (e) {\n DEBUG_BUILD && debug.log('[Profiling] Error while stopping JS Profiler for chunk:', e);\n }\n }\n\n /**\n * Send a profile chunk as a standalone envelope.\n */\n private _sendProfileChunk(chunk: ProfileChunk): void {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const client = this._client!;\n\n const sdkInfo = getSdkMetadataForEnvelopeHeader(client.getSdkMetadata?.());\n const dsn = client.getDsn();\n const tunnel = client.getOptions().tunnel;\n\n const envelope = createEnvelope<ProfileChunkEnvelope>(\n {\n event_id: uuid4(),\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n },\n [[{ type: 'profile_chunk' }, chunk]],\n );\n\n client.sendEnvelope(envelope).then(null, reason => {\n DEBUG_BUILD && debug.error('Error while sending profile chunk envelope:', reason);\n });\n }\n}\n"],"names":["uuid4","DEBUG_BUILD","debug","getRootSpan","getGlobalScope","startJSSelfProfile","createProfileChunkPayload","validateProfileChunk","getSdkMetadataForEnvelopeHeader","createEnvelope","dsnToString"],"mappings":";;;;;;AAeA,MAAM,iBAAA,GAAoB,KAAM,CAAA;AAChC;AACA,MAAM,wBAAA,GAA2B,MAAO,CAAA;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,6BAAA,CAA8B;;AAI3C;;AAGA;;AAKA,GAAS,WAAW,GAAG;AACvB,IAAI,IAAI,CAAC,OAAA,GAAU,SAAS;AAC5B,IAAI,IAAI,CAAC,SAAA,GAAY,SAAS;AAC9B,IAAI,IAAI,CAAC,WAAA,GAAc,SAAS;AAChC,IAAI,IAAI,CAAC,kBAAA,GAAqB,IAAI,GAAG,EAAU;AAC/C,IA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I,MAAM,QAAA,GAAWC,mBAAc;AACnC,MAAM;AACN,QAAQ,QAAQ,EAAET,UAAK,EAAE;AACzB,QAAQ,OAAO,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;AACzC,QAAQ,IAAI,OAAA,IAAW,EAAE,GAAG,EAAE,OAAA,EAAS,CAAC;AACxC,QAAQ,IAAI,CAAC,CAAC,MAAA,IAAU,GAAA,IAAO,EAAE,GAAG,EAAEU,gBAAW,CAAC,GAAG,CAAA,EAAG,CAAC;AACzD,OAAO;AACP,MAAM,CAAC,CAAC,EAAE,IAAI,EAAE,iBAAiB,EAAE,KAAK,CAAC,CAAC;AAC1C,KAAK;;AAEL,IAAI,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,MAAA,IAAU;AACvD,MAAMT,sBAAA,IAAeC,UAAK,CAAC,KAAK,CAAC,6CAA6C,EAAE,MAAM,CAAC;AACvF,KAAK,CAAC;AACN;AACA;;;;"}
@@ -34,6 +34,15 @@ function startProfileForSpan(span) {
34
34
  // calling the profiler methods. Note: we log the original name to the user to avoid confusion.
35
35
  const profileId = core.uuid4();
36
36
 
37
+ // A couple of important things to note here:
38
+ // `CpuProfilerBindings.stopProfiling` will be scheduled to run in 30seconds in order to exceed max profile duration.
39
+ // Whichever of the two (span.finish/timeout) is first to run, the profiling will be stopped and the gathered profile
40
+ // will be processed when the original span is finished. Since onProfileHandler can be invoked multiple times in the
41
+ // event of an error or user mistake (calling span.finish multiple times), it is important that the behavior of onProfileHandler
42
+ // is idempotent as we do not want any timings or profiles to be overridden by the last call to onProfileHandler.
43
+ // After the original finish method is called, the event will be reported through the integration and delegated to transport.
44
+ let processedProfile = null;
45
+
37
46
  core.getCurrentScope().setContext('profile', {
38
47
  profile_id: profileId,
39
48
  start_timestamp: startTimestamp,
@@ -51,6 +60,12 @@ function startProfileForSpan(span) {
51
60
  if (!profiler) {
52
61
  return;
53
62
  }
63
+ if (processedProfile) {
64
+ if (debugBuild.DEBUG_BUILD) {
65
+ core.debug.log('[Profiling] profile for:', core.spanToJSON(span).description, 'already exists, returning early');
66
+ }
67
+ return;
68
+ }
54
69
 
55
70
  return profiler
56
71
  .stop()
@@ -75,6 +90,7 @@ function startProfileForSpan(span) {
75
90
  return;
76
91
  }
77
92
 
93
+ processedProfile = profile;
78
94
  utils.addProfileToGlobalCache(profileId, profile);
79
95
  })
80
96
  .catch(error => {
@@ -1 +1 @@
1
- {"version":3,"file":"startProfileForSpan.js","sources":["../../../../src/profiling/startProfileForSpan.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { debug, getCurrentScope, spanToJSON, timestampInSeconds, uuid4 } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\nimport type { JSSelfProfile } from './jsSelfProfiling';\nimport { addProfileToGlobalCache, isAutomatedPageLoadSpan, MAX_PROFILE_DURATION_MS, startJSSelfProfile } from './utils';\n\n/**\n * Wraps startTransaction and stopTransaction with profiling related logic.\n * startProfileForTransaction is called after the call to startTransaction in order to avoid our own code from\n * being profiled. Because of that same reason, stopProfiling is called before the call to stopTransaction.\n */\nexport function startProfileForSpan(span: Span): void {\n // Start the profiler and get the profiler instance.\n let startTimestamp: number | undefined;\n if (isAutomatedPageLoadSpan(span)) {\n startTimestamp = timestampInSeconds() * 1000;\n }\n\n const profiler = startJSSelfProfile();\n\n // We failed to construct the profiler, so we skip.\n // No need to log anything as this has already been logged in startProfile.\n if (!profiler) {\n return;\n }\n\n if (DEBUG_BUILD) {\n debug.log(`[Profiling] started profiling span: ${spanToJSON(span).description}`);\n }\n\n // We create \"unique\" span names to avoid concurrent spans with same names\n // from being ignored by the profiler. From here on, only this span name should be used when\n // calling the profiler methods. Note: we log the original name to the user to avoid confusion.\n const profileId = uuid4();\n\n // A couple of important things to note here:\n // `CpuProfilerBindings.stopProfiling` will be scheduled to run in 30seconds in order to exceed max profile duration.\n // Whichever of the two (span.finish/timeout) is first to run, the profiling will be stopped and the gathered profile\n // will be processed when the original span is finished. Since onProfileHandler can be invoked multiple times in the\n // event of an error or user mistake (calling span.finish multiple times), it is important that the behavior of onProfileHandler\n // is idempotent as we do not want any timings or profiles to be overridden by the last call to onProfileHandler.\n // After the original finish method is called, the event will be reported through the integration and delegated to transport.\n const processedProfile: JSSelfProfile | null = null;\n\n getCurrentScope().setContext('profile', {\n profile_id: profileId,\n start_timestamp: startTimestamp,\n });\n\n /**\n * Idempotent handler for profile stop\n */\n async function onProfileHandler(): Promise<void> {\n // Check if the profile exists and return it the behavior has to be idempotent as users may call span.finish multiple times.\n if (!span) {\n return;\n }\n // Satisfy the type checker, but profiler will always be defined here.\n if (!profiler) {\n return;\n }\n if (processedProfile) {\n if (DEBUG_BUILD) {\n debug.log('[Profiling] profile for:', spanToJSON(span).description, 'already exists, returning early');\n }\n return;\n }\n\n return profiler\n .stop()\n .then((profile: JSSelfProfile): void => {\n if (maxDurationTimeoutID) {\n WINDOW.clearTimeout(maxDurationTimeoutID);\n maxDurationTimeoutID = undefined;\n }\n\n if (DEBUG_BUILD) {\n debug.log(`[Profiling] stopped profiling of span: ${spanToJSON(span).description}`);\n }\n\n // In case of an overlapping span, stopProfiling may return null and silently ignore the overlapping profile.\n if (!profile) {\n if (DEBUG_BUILD) {\n debug.log(\n `[Profiling] profiler returned null profile for: ${spanToJSON(span).description}`,\n 'this may indicate an overlapping span or a call to stopProfiling with a profile title that was never started',\n );\n }\n return;\n }\n\n addProfileToGlobalCache(profileId, profile);\n })\n .catch(error => {\n if (DEBUG_BUILD) {\n debug.log('[Profiling] error while stopping profiler:', error);\n }\n });\n }\n\n // Enqueue a timeout to prevent profiles from running over max duration.\n let maxDurationTimeoutID: number | undefined = WINDOW.setTimeout(() => {\n if (DEBUG_BUILD) {\n debug.log('[Profiling] max profile duration elapsed, stopping profiling for:', spanToJSON(span).description);\n }\n // If the timeout exceeds, we want to stop profiling, but not finish the span\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n onProfileHandler();\n }, MAX_PROFILE_DURATION_MS);\n\n // We need to reference the original end call to avoid creating an infinite loop\n const originalEnd = span.end.bind(span);\n\n /**\n * Wraps span `end()` with profiling related logic.\n * startProfiling is called after the call to spanStart in order to avoid our own code from\n * being profiled. Because of that same reason, stopProfiling is called before the call to spanEnd.\n */\n function profilingWrappedSpanEnd(): Span {\n if (!span) {\n return originalEnd();\n }\n // onProfileHandler should always return the same profile even if this is called multiple times.\n // Always call onProfileHandler to ensure stopProfiling is called and the timeout is cleared.\n void onProfileHandler().then(\n () => {\n originalEnd();\n },\n () => {\n // If onProfileHandler fails, we still want to call the original finish method.\n originalEnd();\n },\n );\n\n return span;\n }\n\n span.end = profilingWrappedSpanEnd;\n}\n"],"names":["isAutomatedPageLoadSpan","timestampInSeconds","startJSSelfProfile","DEBUG_BUILD","debug","spanToJSON","uuid4","getCurrentScope","WINDOW","addProfileToGlobalCache","MAX_PROFILE_DURATION_MS"],"mappings":";;;;;;;AAOA;AACA;AACA;AACA;AACA;AACO,SAAS,mBAAmB,CAAC,IAAI,EAAc;AACtD;AACA,EAAE,IAAI,cAAc;AACpB,EAAE,IAAIA,6BAAuB,CAAC,IAAI,CAAC,EAAE;AACrC,IAAI,iBAAiBC,uBAAkB,EAAC,GAAI,IAAI;AAChD;;AAEA,EAAE,MAAM,QAAA,GAAWC,wBAAkB,EAAE;;AAEvC;AACA;AACA,EAAE,IAAI,CAAC,QAAQ,EAAE;AACjB,IAAI;AACJ;;AAEA,EAAE,IAAIC,sBAAW,EAAE;AACnB,IAAIC,UAAK,CAAC,GAAG,CAAC,CAAC,oCAAoC,EAAEC,eAAU,CAAC,IAAI,CAAC,CAAC,WAAW,CAAC,CAAA,CAAA;AACA;;AAEA;AACA;AACA;AACA,EAAA,MAAA,SAAA,GAAAC,UAAA,EAAA;;AAWA,EAAAC,oBAAA,EAAA,CAAA,UAAA,CAAA,SAAA,EAAA;AACA,IAAA,UAAA,EAAA,SAAA;AACA,IAAA,eAAA,EA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AA;;AAEA;AACA,EAAA,MAAA,WAAA,GAAA,IAAA,CAAA,GAAA,CAAA,IAAA,CAAA,IAAA,CAAA;;AAEA;AACA;AACA;AACA;AACA;AACA,EAAA,SAAA,uBAAA,GAAA;AACA,IAAA,IAAA,CAAA,IAAA,EAAA;AACA,MAAA,OAAA,WAAA,EAAA;AACA;AACA;AACA;AACA,IAAA,KAAA,gBAAA,EAAA,CAAA,IAAA;AACA,MAAA,MAAA;AACA,QAAA,WAAA,EAAA;AACA,OAAA;AACA,MAAA,MAAA;AACA;AACA,QAAA,WAAA,EAAA;AACA,OAAA;AACA,KAAA;;AAEA,IAAA,OAAA,IAAA;AACA;;AAEA,EAAA,IAAA,CAAA,GAAA,GAAA,uBAAA;AACA;;;;"}
1
+ {"version":3,"file":"startProfileForSpan.js","sources":["../../../../src/profiling/startProfileForSpan.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { debug, getCurrentScope, spanToJSON, timestampInSeconds, uuid4 } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\nimport type { JSSelfProfile } from './jsSelfProfiling';\nimport { addProfileToGlobalCache, isAutomatedPageLoadSpan, MAX_PROFILE_DURATION_MS, startJSSelfProfile } from './utils';\n\n/**\n * Wraps startTransaction and stopTransaction with profiling related logic.\n * startProfileForTransaction is called after the call to startTransaction in order to avoid our own code from\n * being profiled. Because of that same reason, stopProfiling is called before the call to stopTransaction.\n */\nexport function startProfileForSpan(span: Span): void {\n // Start the profiler and get the profiler instance.\n let startTimestamp: number | undefined;\n if (isAutomatedPageLoadSpan(span)) {\n startTimestamp = timestampInSeconds() * 1000;\n }\n\n const profiler = startJSSelfProfile();\n\n // We failed to construct the profiler, so we skip.\n // No need to log anything as this has already been logged in startProfile.\n if (!profiler) {\n return;\n }\n\n if (DEBUG_BUILD) {\n debug.log(`[Profiling] started profiling span: ${spanToJSON(span).description}`);\n }\n\n // We create \"unique\" span names to avoid concurrent spans with same names\n // from being ignored by the profiler. From here on, only this span name should be used when\n // calling the profiler methods. Note: we log the original name to the user to avoid confusion.\n const profileId = uuid4();\n\n // A couple of important things to note here:\n // `CpuProfilerBindings.stopProfiling` will be scheduled to run in 30seconds in order to exceed max profile duration.\n // Whichever of the two (span.finish/timeout) is first to run, the profiling will be stopped and the gathered profile\n // will be processed when the original span is finished. Since onProfileHandler can be invoked multiple times in the\n // event of an error or user mistake (calling span.finish multiple times), it is important that the behavior of onProfileHandler\n // is idempotent as we do not want any timings or profiles to be overridden by the last call to onProfileHandler.\n // After the original finish method is called, the event will be reported through the integration and delegated to transport.\n let processedProfile: JSSelfProfile | null = null;\n\n getCurrentScope().setContext('profile', {\n profile_id: profileId,\n start_timestamp: startTimestamp,\n });\n\n /**\n * Idempotent handler for profile stop\n */\n async function onProfileHandler(): Promise<void> {\n // Check if the profile exists and return it the behavior has to be idempotent as users may call span.finish multiple times.\n if (!span) {\n return;\n }\n // Satisfy the type checker, but profiler will always be defined here.\n if (!profiler) {\n return;\n }\n if (processedProfile) {\n if (DEBUG_BUILD) {\n debug.log('[Profiling] profile for:', spanToJSON(span).description, 'already exists, returning early');\n }\n return;\n }\n\n return profiler\n .stop()\n .then((profile: JSSelfProfile): void => {\n if (maxDurationTimeoutID) {\n WINDOW.clearTimeout(maxDurationTimeoutID);\n maxDurationTimeoutID = undefined;\n }\n\n if (DEBUG_BUILD) {\n debug.log(`[Profiling] stopped profiling of span: ${spanToJSON(span).description}`);\n }\n\n // In case of an overlapping span, stopProfiling may return null and silently ignore the overlapping profile.\n if (!profile) {\n if (DEBUG_BUILD) {\n debug.log(\n `[Profiling] profiler returned null profile for: ${spanToJSON(span).description}`,\n 'this may indicate an overlapping span or a call to stopProfiling with a profile title that was never started',\n );\n }\n return;\n }\n\n processedProfile = profile;\n addProfileToGlobalCache(profileId, profile);\n })\n .catch(error => {\n if (DEBUG_BUILD) {\n debug.log('[Profiling] error while stopping profiler:', error);\n }\n });\n }\n\n // Enqueue a timeout to prevent profiles from running over max duration.\n let maxDurationTimeoutID: number | undefined = WINDOW.setTimeout(() => {\n if (DEBUG_BUILD) {\n debug.log('[Profiling] max profile duration elapsed, stopping profiling for:', spanToJSON(span).description);\n }\n // If the timeout exceeds, we want to stop profiling, but not finish the span\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n onProfileHandler();\n }, MAX_PROFILE_DURATION_MS);\n\n // We need to reference the original end call to avoid creating an infinite loop\n const originalEnd = span.end.bind(span);\n\n /**\n * Wraps span `end()` with profiling related logic.\n * startProfiling is called after the call to spanStart in order to avoid our own code from\n * being profiled. Because of that same reason, stopProfiling is called before the call to spanEnd.\n */\n function profilingWrappedSpanEnd(): Span {\n if (!span) {\n return originalEnd();\n }\n // onProfileHandler should always return the same profile even if this is called multiple times.\n // Always call onProfileHandler to ensure stopProfiling is called and the timeout is cleared.\n void onProfileHandler().then(\n () => {\n originalEnd();\n },\n () => {\n // If onProfileHandler fails, we still want to call the original finish method.\n originalEnd();\n },\n );\n\n return span;\n }\n\n span.end = profilingWrappedSpanEnd;\n}\n"],"names":["isAutomatedPageLoadSpan","timestampInSeconds","startJSSelfProfile","DEBUG_BUILD","debug","spanToJSON","uuid4","getCurrentScope","WINDOW","addProfileToGlobalCache","MAX_PROFILE_DURATION_MS"],"mappings":";;;;;;;AAOA;AACA;AACA;AACA;AACA;AACO,SAAS,mBAAmB,CAAC,IAAI,EAAc;AACtD;AACA,EAAE,IAAI,cAAc;AACpB,EAAE,IAAIA,6BAAuB,CAAC,IAAI,CAAC,EAAE;AACrC,IAAI,iBAAiBC,uBAAkB,EAAC,GAAI,IAAI;AAChD;;AAEA,EAAE,MAAM,QAAA,GAAWC,wBAAkB,EAAE;;AAEvC;AACA;AACA,EAAE,IAAI,CAAC,QAAQ,EAAE;AACjB,IAAI;AACJ;;AAEA,EAAE,IAAIC,sBAAW,EAAE;AACnB,IAAIC,UAAK,CAAC,GAAG,CAAC,CAAC,oCAAoC,EAAEC,eAAU,CAAC,IAAI,CAAC,CAAC,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GAAA,OAAA;AACA,QAAAI,6BAAA,CAAA,SAAA,EAAA,OAAA,CAAA;AACA,OAAA;AACA,OAAA,KAAA,CAAA,KAAA,IAAA;AACA,QAAA,IAAAN,sBAAA,EAAA;AACA,UAAAC,UAAA,CAAA,GAAA,CAAA,4CAAA,EAAA,KAAA,CAAA;AACA;AACA,OAAA,CAAA;AACA;;AAEA;AACA,EAAA,IAAA,oBAAA,GAAAI,cAAA,CAAA,UAAA,CAAA,MAAA;AACA,IAAA,IAAAL,sBAAA,EAAA;AACA,MAAAC,UAAA,CAAA,GAAA,CAAA,mEAAA,EAAAC,eAAA,CAAA,IAAA,CAAA,CAAA,WAAA,CAAA;AACA;AACA;AACA;AACA,IAAA,gBAAA,EAAA;AACA,GAAA,EAAAK,6BAAA,CAAA;;AAEA;AACA,EAAA,MAAA,WAAA,GAAA,IAAA,CAAA,GAAA,CAAA,IAAA,CAAA,IAAA,CAAA;;AAEA;AACA;AACA;AACA;AACA;AACA,EAAA,SAAA,uBAAA,GAAA;AACA,IAAA,IAAA,CAAA,IAAA,EAAA;AACA,MAAA,OAAA,WAAA,EAAA;AACA;AACA;AACA;AACA,IAAA,KAAA,gBAAA,EAAA,CAAA,IAAA;AACA,MAAA,MAAA;AACA,QAAA,WAAA,EAAA;AACA,OAAA;AACA,MAAA,MAAA;AACA;AACA,QAAA,WAAA,EAAA;AACA,OAAA;AACA,KAAA;;AAEA,IAAA,OAAA,IAAA;AACA;;AAEA,EAAA,IAAA,CAAA,GAAA,GAAA,uBAAA;AACA;;;;"}
@@ -5,10 +5,13 @@ const debugBuild = require('../debug-build.js');
5
5
  const helpers = require('../helpers.js');
6
6
 
7
7
  const MS_TO_NS = 1e6;
8
- // Use 0 as main thread id which is identical to threadId in node:worker_threads
9
- // where main logs 0 and workers seem to log in increments of 1
10
- const THREAD_ID_STRING = String(0);
11
- const THREAD_NAME = 'main';
8
+
9
+ // Checking if we are in Main or Worker thread: `self` (not `window`) is the `globalThis` in Web Workers and `importScripts` are only available in Web Workers
10
+ const isMainThread = 'window' in core.GLOBAL_OBJ && core.GLOBAL_OBJ.window === core.GLOBAL_OBJ && typeof importScripts === 'undefined';
11
+
12
+ // Setting ID to 0 as we cannot get an ID from Web Workers
13
+ const PROFILER_THREAD_ID_STRING = String(0);
14
+ const PROFILER_THREAD_NAME = isMainThread ? 'main' : 'worker';
12
15
 
13
16
  // We force make this optional to be on the safe side...
14
17
  const navigator = helpers.WINDOW.navigator ;
@@ -154,7 +157,7 @@ function createProfilePayload(
154
157
  name: event.transaction || '',
155
158
  id: event.event_id || core.uuid4(),
156
159
  trace_id: traceId,
157
- active_thread_id: THREAD_ID_STRING,
160
+ active_thread_id: PROFILER_THREAD_ID_STRING,
158
161
  relative_start_ns: '0',
159
162
  relative_end_ns: ((transactionEndMs - transactionStartMs) * 1e6).toFixed(0),
160
163
  },
@@ -164,6 +167,158 @@ function createProfilePayload(
164
167
  return profile;
165
168
  }
166
169
 
170
+ /**
171
+ * Create a profile chunk envelope item
172
+ */
173
+ function createProfileChunkPayload(
174
+ jsSelfProfile,
175
+ client,
176
+ profilerId,
177
+ ) {
178
+ // only == to catch null and undefined
179
+ if (jsSelfProfile == null) {
180
+ throw new TypeError(
181
+ `Cannot construct profiling event envelope without a valid profile. Got ${jsSelfProfile} instead.`,
182
+ );
183
+ }
184
+
185
+ const continuousProfile = convertToContinuousProfile(jsSelfProfile);
186
+
187
+ const options = client.getOptions();
188
+ const sdk = client.getSdkMetadata?.()?.sdk;
189
+
190
+ return {
191
+ chunk_id: core.uuid4(),
192
+ client_sdk: {
193
+ name: sdk?.name ?? 'sentry.javascript.browser',
194
+ version: sdk?.version ?? '0.0.0',
195
+ },
196
+ profiler_id: profilerId || core.uuid4(),
197
+ platform: 'javascript',
198
+ version: '2',
199
+ release: options.release ?? '',
200
+ environment: options.environment ?? 'production',
201
+ debug_meta: {
202
+ // function name obfuscation
203
+ images: applyDebugMetadata(jsSelfProfile.resources),
204
+ },
205
+ profile: continuousProfile,
206
+ };
207
+ }
208
+
209
+ /**
210
+ * Validate a profile chunk against the Sample Format V2 requirements.
211
+ * https://develop.sentry.dev/sdk/telemetry/profiles/sample-format-v2/
212
+ * - Presence of samples, stacks, frames
213
+ * - Required metadata fields
214
+ */
215
+ function validateProfileChunk(chunk) {
216
+ try {
217
+ // Required metadata
218
+ if (!chunk || typeof chunk !== 'object') {
219
+ return { reason: 'chunk is not an object' };
220
+ }
221
+
222
+ // profiler_id and chunk_id must be 32 lowercase hex chars
223
+ const isHex32 = (val) => typeof val === 'string' && /^[a-f0-9]{32}$/.test(val);
224
+ if (!isHex32(chunk.profiler_id)) {
225
+ return { reason: 'missing or invalid profiler_id' };
226
+ }
227
+ if (!isHex32(chunk.chunk_id)) {
228
+ return { reason: 'missing or invalid chunk_id' };
229
+ }
230
+
231
+ if (!chunk.client_sdk) {
232
+ return { reason: 'missing client_sdk metadata' };
233
+ }
234
+
235
+ // Profile data must have frames, stacks, samples
236
+ const profile = chunk.profile ;
237
+ if (!profile) {
238
+ return { reason: 'missing profile data' };
239
+ }
240
+
241
+ if (!Array.isArray(profile.frames) || !profile.frames.length) {
242
+ return { reason: 'profile has no frames' };
243
+ }
244
+ if (!Array.isArray(profile.stacks) || !profile.stacks.length) {
245
+ return { reason: 'profile has no stacks' };
246
+ }
247
+ if (!Array.isArray(profile.samples) || !profile.samples.length) {
248
+ return { reason: 'profile has no samples' };
249
+ }
250
+
251
+ return { valid: true };
252
+ } catch (e) {
253
+ return { reason: `unknown validation error: ${e}` };
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Convert from JSSelfProfile format to ContinuousThreadCpuProfile format.
259
+ */
260
+ function convertToContinuousProfile(input
261
+
262
+ ) {
263
+ // Frames map 1:1 by index; fill only when present to avoid sparse writes
264
+ const frames = [];
265
+ for (let i = 0; i < input.frames.length; i++) {
266
+ const frame = input.frames[i];
267
+ if (!frame) {
268
+ continue;
269
+ }
270
+ frames[i] = {
271
+ function: frame.name,
272
+ abs_path: typeof frame.resourceId === 'number' ? input.resources[frame.resourceId] : undefined,
273
+ lineno: frame.line,
274
+ colno: frame.column,
275
+ };
276
+ }
277
+
278
+ // Build stacks by following parent links, top->down order (root last)
279
+ const stacks = [];
280
+ for (let i = 0; i < input.stacks.length; i++) {
281
+ const stackHead = input.stacks[i];
282
+ if (!stackHead) {
283
+ continue;
284
+ }
285
+ const list = [];
286
+ let current = stackHead;
287
+ while (current) {
288
+ list.push(current.frameId);
289
+ current = current.parentId === undefined ? undefined : input.stacks[current.parentId];
290
+ }
291
+ stacks[i] = list;
292
+ }
293
+
294
+ // Align timestamps to SDK time origin to match span/event timelines
295
+ const perfOrigin = core.browserPerformanceTimeOrigin();
296
+ const origin = typeof performance.timeOrigin === 'number' ? performance.timeOrigin : perfOrigin || 0;
297
+ const adjustForOriginChange = origin - (perfOrigin || origin);
298
+
299
+ const samples = [];
300
+ for (let i = 0; i < input.samples.length; i++) {
301
+ const sample = input.samples[i];
302
+ if (!sample) {
303
+ continue;
304
+ }
305
+ // Convert ms to seconds epoch-based timestamp
306
+ const timestampSeconds = (origin + (sample.timestamp - adjustForOriginChange)) / 1000;
307
+ samples[i] = {
308
+ stack_id: sample.stackId ?? 0,
309
+ thread_id: PROFILER_THREAD_ID_STRING,
310
+ timestamp: timestampSeconds,
311
+ };
312
+ }
313
+
314
+ return {
315
+ frames,
316
+ stacks,
317
+ samples,
318
+ thread_metadata: { [PROFILER_THREAD_ID_STRING]: { name: PROFILER_THREAD_NAME } },
319
+ };
320
+ }
321
+
167
322
  /*
168
323
  See packages/browser-utils/src/browser/router.ts
169
324
  */
@@ -188,7 +343,7 @@ function convertJSSelfProfileToSampledFormat(input) {
188
343
  stacks: [],
189
344
  frames: [],
190
345
  thread_metadata: {
191
- [THREAD_ID_STRING]: { name: THREAD_NAME },
346
+ [PROFILER_THREAD_ID_STRING]: { name: PROFILER_THREAD_NAME },
192
347
  },
193
348
  };
194
349
 
@@ -220,7 +375,7 @@ function convertJSSelfProfileToSampledFormat(input) {
220
375
  // convert ms timestamp to ns
221
376
  elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0),
222
377
  stack_id: EMPTY_STACK_ID,
223
- thread_id: THREAD_ID_STRING,
378
+ thread_id: PROFILER_THREAD_ID_STRING,
224
379
  };
225
380
  return;
226
381
  }
@@ -253,7 +408,7 @@ function convertJSSelfProfileToSampledFormat(input) {
253
408
  // convert ms timestamp to ns
254
409
  elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0),
255
410
  stack_id: STACK_ID,
256
- thread_id: THREAD_ID_STRING,
411
+ thread_id: PROFILER_THREAD_ID_STRING,
257
412
  };
258
413
 
259
414
  profile['stacks'][STACK_ID] = stack;
@@ -421,7 +576,7 @@ function startJSSelfProfile() {
421
576
  /**
422
577
  * Determine if a profile should be profiled.
423
578
  */
424
- function shouldProfileSpan(span) {
579
+ function shouldProfileSpanLegacy(span) {
425
580
  // If constructor failed once, it will always fail, so we can early return.
426
581
  if (PROFILING_CONSTRUCTOR_FAILED) {
427
582
  if (debugBuild.DEBUG_BUILD) {
@@ -431,9 +586,7 @@ function shouldProfileSpan(span) {
431
586
  }
432
587
 
433
588
  if (!span.isRecording()) {
434
- if (debugBuild.DEBUG_BUILD) {
435
- core.debug.log('[Profiling] Discarding profile because transaction was not sampled.');
436
- }
589
+ debugBuild.DEBUG_BUILD && core.debug.log('[Profiling] Discarding profile because root span was not sampled.');
437
590
  return false;
438
591
  }
439
592
 
@@ -480,6 +633,46 @@ function shouldProfileSpan(span) {
480
633
  return true;
481
634
  }
482
635
 
636
+ /**
637
+ * Determine if a profile should be created for the current session (lifecycle profiling mode).
638
+ */
639
+ function shouldProfileSession(options) {
640
+ // If constructor failed once, it will always fail, so we can early return.
641
+ if (PROFILING_CONSTRUCTOR_FAILED) {
642
+ if (debugBuild.DEBUG_BUILD) {
643
+ core.debug.log('[Profiling] Profiling has been disabled for the duration of the current user session.');
644
+ }
645
+ return false;
646
+ }
647
+
648
+ if (options.profileLifecycle !== 'trace') {
649
+ return false;
650
+ }
651
+
652
+ // Session sampling: profileSessionSampleRate gates whether profiling is enabled for this session
653
+ const profileSessionSampleRate = options.profileSessionSampleRate;
654
+
655
+ if (!isValidSampleRate(profileSessionSampleRate)) {
656
+ debugBuild.DEBUG_BUILD && core.debug.warn('[Profiling] Discarding profile because of invalid profileSessionSampleRate.');
657
+ return false;
658
+ }
659
+
660
+ if (!profileSessionSampleRate) {
661
+ debugBuild.DEBUG_BUILD &&
662
+ core.debug.log('[Profiling] Discarding profile because profileSessionSampleRate is not defined or set to 0');
663
+ return false;
664
+ }
665
+
666
+ return Math.random() <= profileSessionSampleRate;
667
+ }
668
+
669
+ /**
670
+ * Checks if legacy profiling is configured.
671
+ */
672
+ function hasLegacyProfiling(options) {
673
+ return typeof options.profilesSampleRate !== 'undefined';
674
+ }
675
+
483
676
  /**
484
677
  * Creates a profiling envelope item, if the profile does not pass validation, returns null.
485
678
  * @param event
@@ -527,23 +720,67 @@ function addProfileToGlobalCache(profile_id, profile) {
527
720
 
528
721
  if (PROFILE_MAP.size > 30) {
529
722
  const last = PROFILE_MAP.keys().next().value;
530
- PROFILE_MAP.delete(last);
723
+ if (last !== undefined) {
724
+ PROFILE_MAP.delete(last);
725
+ }
726
+ }
727
+ }
728
+
729
+ /**
730
+ * Attaches the profiled thread information to the event's trace context.
731
+ */
732
+ function attachProfiledThreadToEvent(event) {
733
+ if (!event?.contexts?.profile) {
734
+ return event;
531
735
  }
736
+
737
+ if (!event.contexts) {
738
+ return event;
739
+ }
740
+
741
+ // @ts-expect-error the trace fallback value is wrong, though it should never happen
742
+ // and in case it does, we dont want to override whatever was passed initially.
743
+ event.contexts.trace = {
744
+ ...(event.contexts?.trace ?? {}),
745
+ data: {
746
+ ...(event.contexts?.trace?.data ?? {}),
747
+ ['thread.id']: PROFILER_THREAD_ID_STRING,
748
+ ['thread.name']: PROFILER_THREAD_NAME,
749
+ },
750
+ };
751
+
752
+ // Attach thread info to individual spans so that spans can be associated with the profiled thread on the UI even if contexts are missing.
753
+ event.spans?.forEach(span => {
754
+ span.data = {
755
+ ...(span.data || {}),
756
+ ['thread.id']: PROFILER_THREAD_ID_STRING,
757
+ ['thread.name']: PROFILER_THREAD_NAME,
758
+ };
759
+ });
760
+
761
+ return event;
532
762
  }
533
763
 
534
764
  exports.MAX_PROFILE_DURATION_MS = MAX_PROFILE_DURATION_MS;
765
+ exports.PROFILER_THREAD_ID_STRING = PROFILER_THREAD_ID_STRING;
766
+ exports.PROFILER_THREAD_NAME = PROFILER_THREAD_NAME;
535
767
  exports.addProfileToGlobalCache = addProfileToGlobalCache;
536
768
  exports.addProfilesToEnvelope = addProfilesToEnvelope;
537
769
  exports.applyDebugMetadata = applyDebugMetadata;
770
+ exports.attachProfiledThreadToEvent = attachProfiledThreadToEvent;
538
771
  exports.convertJSSelfProfileToSampledFormat = convertJSSelfProfileToSampledFormat;
772
+ exports.createProfileChunkPayload = createProfileChunkPayload;
539
773
  exports.createProfilePayload = createProfilePayload;
540
774
  exports.createProfilingEvent = createProfilingEvent;
541
775
  exports.enrichWithThreadInformation = enrichWithThreadInformation;
542
776
  exports.findProfiledTransactionsFromEnvelope = findProfiledTransactionsFromEnvelope;
543
777
  exports.getActiveProfilesCount = getActiveProfilesCount;
778
+ exports.hasLegacyProfiling = hasLegacyProfiling;
544
779
  exports.isAutomatedPageLoadSpan = isAutomatedPageLoadSpan;
545
780
  exports.isValidSampleRate = isValidSampleRate;
546
- exports.shouldProfileSpan = shouldProfileSpan;
781
+ exports.shouldProfileSession = shouldProfileSession;
782
+ exports.shouldProfileSpanLegacy = shouldProfileSpanLegacy;
547
783
  exports.startJSSelfProfile = startJSSelfProfile;
548
784
  exports.takeProfileFromGlobalCache = takeProfileFromGlobalCache;
785
+ exports.validateProfileChunk = validateProfileChunk;
549
786
  //# sourceMappingURL=utils.js.map