33import { DEFAULT_ENVIRONMENT , getCurrentHub } from '@sentry/core' ;
44import type { DebugImage , Envelope , Event , StackFrame , StackParser } from '@sentry/types' ;
55import type { Profile , ThreadCpuProfile } from '@sentry/types/src/profiling' ;
6- import { forEachEnvelopeItem , GLOBAL_OBJ , logger , uuid4 } from '@sentry/utils' ;
6+ import { browserPerformanceTimeOrigin , forEachEnvelopeItem , GLOBAL_OBJ , logger , uuid4 } from '@sentry/utils' ;
77
88import { WINDOW } from '../helpers' ;
99import type { JSSelfProfile , JSSelfProfileStack } from './jsSelfProfiling' ;
@@ -213,6 +213,13 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
213213
214214 // We assert samples.length > 0 above and timestamp should always be present
215215 const start = input . samples [ 0 ] . timestamp ;
216+ // The JS SDK might change it's time origin based on some heuristic (see See packages/utils/src/time.ts)
217+ // when that happens, we need to ensure we are correcting the profile timings so the two timelines stay in sync.
218+ // Since JS self profiling time origin is always initialized to performance.timeOrigin, we need to adjust for
219+ // the drift between the SDK selected value and our profile time origin.
220+ const origin =
221+ typeof performance . timeOrigin === 'number' ? performance . timeOrigin : browserPerformanceTimeOrigin || 0 ;
222+ const adjustForOriginChange = origin - ( browserPerformanceTimeOrigin || origin ) ;
216223
217224 for ( let i = 0 ; i < input . samples . length ; i ++ ) {
218225 const jsSample = input . samples [ i ] ;
@@ -227,7 +234,7 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
227234
228235 profile [ 'samples' ] [ i ] = {
229236 // convert ms timestamp to ns
230- elapsed_since_start_ns : ( ( jsSample . timestamp - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
237+ elapsed_since_start_ns : ( ( jsSample . timestamp + adjustForOriginChange - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
231238 stack_id : EMPTY_STACK_ID ,
232239 thread_id : THREAD_ID_STRING ,
233240 } ;
@@ -260,7 +267,7 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
260267
261268 const sample : Profile [ 'profile' ] [ 'samples' ] [ 0 ] = {
262269 // convert ms timestamp to ns
263- elapsed_since_start_ns : ( ( jsSample . timestamp - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
270+ elapsed_since_start_ns : ( ( jsSample . timestamp + adjustForOriginChange - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
264271 stack_id : STACK_ID ,
265272 thread_id : THREAD_ID_STRING ,
266273 } ;
0 commit comments