/
index.tsx
1449 lines (1366 loc) · 42.1 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
addCustomEvent as rrwebAddCustomEvent,
getRecordSequentialIdPlugin,
record,
} from '@highlight-run/rrweb'
import { eventWithTime, listenerHandler } from '@highlight-run/rrweb-types'
import { FirstLoadListeners } from './listeners/first-load-listeners'
import {
AmplitudeIntegrationOptions,
ConsoleMethods,
DebugOptions,
MetricCategory,
MetricName,
MixpanelIntegrationOptions,
NetworkRecordingOptions,
SessionShortcutOptions,
} from './types/client'
import {
HighlightOptions,
HighlightPublicInterface,
Integration,
Metadata,
Metric,
SamplingStrategy,
SessionDetails,
StartOptions,
} from './types/types'
import { PathListener } from './listeners/path-listener'
import { GraphQLClient } from 'graphql-request'
import ErrorStackParser from 'error-stack-parser'
import {
getSdk,
PushPayloadDocument,
PushPayloadMutationVariables,
Sdk,
} from './graph/generated/operations'
import StackTrace from 'stacktrace-js'
import stringify from 'json-stringify-safe'
import { print } from 'graphql'
import { ViewportResizeListener } from './listeners/viewport-resize-listener'
import { SegmentIntegrationListener } from './listeners/segment-integration-listener'
import { ClickListener } from './listeners/click-listener/click-listener'
import { FocusListener } from './listeners/focus-listener/focus-listener'
import { SESSION_STORAGE_KEYS } from './utils/sessionStorage/sessionStorageKeys'
import SessionShortcutListener from './listeners/session-shortcut/session-shortcut-listener'
import { WebVitalsListener } from './listeners/web-vitals-listener/web-vitals-listener'
import { getPerformanceMethods } from './utils/performance/performance'
import {
PerformanceListener,
PerformancePayload,
} from './listeners/performance-listener/performance-listener'
import { PageVisibilityListener } from './listeners/page-visibility-listener'
import { clearHighlightLogs, getHighlightLogs } from './utils/highlight-logging'
import { GenerateSecureID } from './utils/secure-id'
import { getSimpleSelector } from './utils/dom'
import {
getPreviousSessionData,
SessionData,
} from './utils/sessionStorage/highlightSession'
import type { HighlightClientRequestWorker } from './workers/highlight-client-worker'
import HighlightClientWorker from './workers/highlight-client-worker?worker&inline'
import { getGraphQLRequestWrapper } from './utils/graph'
import { ReplayEventsInput } from './graph/generated/schemas'
import { MessageType, PropertyType, Source } from './workers/types'
import { Logger } from './logger'
import { HighlightFetchWindow } from './listeners/network-listener/utils/fetch-listener'
import { ConsoleMessage } from './types/shared-types'
import { RequestResponsePair } from './listeners/network-listener/utils/models'
import {
JankListener,
JankPayload,
} from './listeners/jank-listener/jank-listener'
import {
HighlightIframeMessage,
HighlightIframeReponse,
IFRAME_PARENT_READY,
IFRAME_PARENT_RESPONSE,
} from './types/iframe'
import { getItem, setItem, setStorageMode } from './utils/storage'
export const HighlightWarning = (context: string, msg: any) => {
console.warn(`Highlight Warning: (${context}): `, { output: msg })
}
enum LOCAL_STORAGE_KEYS {
CLIENT_ID = 'highlightClientID',
}
export type HighlightClassOptions = {
organizationID: number | string
debug?: boolean | DebugOptions
backendUrl?: string
tracingOrigins?: boolean | (string | RegExp)[]
disableNetworkRecording?: boolean
networkRecording?: boolean | NetworkRecordingOptions
disableBackgroundRecording?: boolean
disableConsoleRecording?: boolean
disableSessionRecording?: boolean
reportConsoleErrors?: boolean
consoleMethodsToRecord?: ConsoleMethods[]
enableSegmentIntegration?: boolean
enableStrictPrivacy?: boolean
enableCanvasRecording?: boolean
enablePerformanceRecording?: boolean
samplingStrategy?: SamplingStrategy
inlineImages?: boolean
inlineStylesheet?: boolean
recordCrossOriginIframe?: boolean
firstloadVersion?: string
environment?: 'development' | 'production' | 'staging' | string
appVersion?: string
serviceName?: string
sessionShortcut?: SessionShortcutOptions
sessionSecureID: string // Introduced in firstLoad 3.0.1
storageMode?: 'sessionStorage' | 'localStorage'
}
/**
* Subset of HighlightClassOptions that is stored with the session. These fields are stored for debugging purposes.
*/
type HighlightClassOptionsInternal = Omit<
HighlightClassOptions,
'firstloadVersion'
>
/**
* The amount of time to wait until sending the first payload.
*/
const FIRST_SEND_FREQUENCY = 1000
/**
* The amount of time between sending the client-side payload to Highlight backend client.
* In milliseconds.
*/
const SEND_FREQUENCY = 1000 * 2
/**
* Maximum length of a session
*/
const MAX_SESSION_LENGTH = 4 * 60 * 60 * 1000
const EXTENDED_MAX_SESSION_LENGTH = 12 * 60 * 60 * 1000
const HIGHLIGHT_URL = 'app.highlight.run'
/*
* Don't take another full snapshot unless it's been at least
* 4 minutes AND the cumulative payload size since the last
* snapshot is > 10MB.
*/
const SNAPSHOT_SETTINGS = {
normal: {
bytes: 10e6,
time: 4 * 60 * 1000,
},
canvas: {
bytes: 16e6,
time: 5000,
},
} as const
// Debounce duplicate visibility events
const VISIBILITY_DEBOUNCE_MS = 100
export class Highlight {
options!: HighlightClassOptions
/** Determines if the client is running on a Highlight property (e.g. frontend). */
isRunningOnHighlight!: boolean
/** Verbose project ID that is exposed to users. Legacy users may still be using ints. */
organizationID!: string
graphqlSDK!: Sdk
events!: eventWithTime[]
sessionData!: SessionData
ready!: boolean
manualStopped!: boolean
state!: 'NotRecording' | 'Recording'
logger!: Logger
enableSegmentIntegration!: boolean
enableStrictPrivacy!: boolean
enableCanvasRecording!: boolean
enablePerformanceRecording!: boolean
samplingStrategy!: SamplingStrategy
inlineImages!: boolean
inlineStylesheet!: boolean
debugOptions!: DebugOptions
listeners!: listenerHandler[]
firstloadVersion!: string
environment!: string
sessionShortcut!: SessionShortcutOptions
/** The end-user's app version. This isn't Highlight's version. */
appVersion!: string | undefined
serviceName!: string
_worker!: HighlightClientRequestWorker
_optionsInternal!: HighlightClassOptionsInternal
_backendUrl!: string
_recordingStartTime!: number
_isOnLocalHost!: boolean
_onToggleFeedbackFormVisibility!: () => void
_firstLoadListeners!: FirstLoadListeners
_isCrossOriginIframe!: boolean
_eventBytesSinceSnapshot!: number
_lastSnapshotTime!: number
_lastVisibilityChangeTime!: number
pushPayloadTimerId!: ReturnType<typeof setTimeout> | undefined
hasSessionUnloaded!: boolean
hasPushedData!: boolean
reloaded!: boolean
_hasPreviouslyInitialized!: boolean
_payloadId!: number
_recordStop!: listenerHandler | undefined
static create(options: HighlightClassOptions): Highlight {
return new Highlight(options)
}
constructor(
options: HighlightClassOptions,
firstLoadListeners?: FirstLoadListeners,
) {
if (!options.sessionSecureID) {
// Firstload versions before 3.0.1 did not have this property
options.sessionSecureID = GenerateSecureID()
}
this.options = options
if (typeof this.options?.debug === 'boolean') {
this.debugOptions = this.options.debug
? { clientInteractions: true }
: {}
} else {
this.debugOptions = this.options?.debug ?? {}
}
this.logger = new Logger(this.debugOptions.clientInteractions)
if (options.storageMode === 'sessionStorage') {
this.logger.log(
'initializing in sessionStorage non-persistent session mode',
)
setStorageMode('sessionStorage')
}
this._worker =
new HighlightClientWorker() as HighlightClientRequestWorker
this._worker.onmessage = (e) => {
if (e.data.response?.type === MessageType.AsyncEvents) {
this._eventBytesSinceSnapshot += e.data.response.eventsSize
this.logger.log(
`Web worker sent payloadID ${e.data.response.id} size ${
e.data.response.eventsSize
}.
Total since snapshot: ${(
this._eventBytesSinceSnapshot / 1000000
).toFixed(1)}MB`,
)
} else if (e.data.response?.type === MessageType.CustomEvent) {
this.addCustomEvent(
e.data.response.tag,
e.data.response.payload,
)
}
}
let storedSessionData = getPreviousSessionData()
this.reloaded = false
// only fetch session data from local storage on the first `initialize` call
if (
!this.sessionData?.sessionSecureID &&
storedSessionData?.sessionSecureID
) {
this.sessionData = storedSessionData
this.options.sessionSecureID = storedSessionData.sessionSecureID
this.reloaded = true
this.logger.log(
`Tab reloaded, continuing previous session: ${this.sessionData.sessionSecureID}`,
)
} else {
// new session. we should clear any session storage data
for (const storageKeyName of Object.values(SESSION_STORAGE_KEYS)) {
window.sessionStorage.removeItem(storageKeyName)
}
this.sessionData = {
sessionSecureID: this.options.sessionSecureID,
projectID: 0,
sessionStartTime: Date.now(),
}
}
// these should not be in initMembers since we want them to
// persist across session resets
this._hasPreviouslyInitialized = false
// Old firstLoad versions (Feb 2022) do not pass in FirstLoadListeners, so we have to fallback to creating it
this._firstLoadListeners =
firstLoadListeners || new FirstLoadListeners(this.options)
try {
// throws if parent is cross-origin
if (window.parent.document) {
this._isCrossOriginIframe = false
}
} catch (e) {
// if recordCrossOriginIframe is set to false, operate as if highlight is only recording the iframe as a dedicated web app.
// this is useful if you are running highlight on your app that is used in a cross-origin iframe with no access to the parent page.
this._isCrossOriginIframe =
this.options.recordCrossOriginIframe ?? true
}
this._initMembers(this.options)
}
// Start a new session
async _reset() {
if (this.pushPayloadTimerId) {
clearTimeout(this.pushPayloadTimerId)
this.pushPayloadTimerId = undefined
}
let user_identifier, user_object
try {
user_identifier = window.sessionStorage.getItem(
SESSION_STORAGE_KEYS.USER_IDENTIFIER,
)
const user_object_string = window.sessionStorage.getItem(
SESSION_STORAGE_KEYS.USER_OBJECT,
)
if (user_object_string) {
user_object = JSON.parse(user_object_string)
}
} catch (err) {}
for (const storageKeyName of Object.values(SESSION_STORAGE_KEYS)) {
window.sessionStorage.removeItem(storageKeyName)
}
// no need to set the sessionStorage value here since firstload won't call
// init again after a reset, and `this.initialize()` will set sessionStorage
this.sessionData.sessionSecureID = GenerateSecureID()
this.sessionData.sessionStartTime = Date.now()
this.options.sessionSecureID = this.sessionData.sessionSecureID
this._payloadId = 0
this.stopRecording()
this._firstLoadListeners = new FirstLoadListeners(this.options)
await this.initialize()
if (user_identifier && user_object) {
await this.identify(user_identifier, user_object)
}
}
_initMembers(options: HighlightClassOptions) {
this.sessionShortcut = false
this._recordingStartTime = 0
this._isOnLocalHost =
window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1' ||
window.location.hostname === ''
this.ready = false
this.state = 'NotRecording'
this.manualStopped = false
this.enableSegmentIntegration = !!options.enableSegmentIntegration
this.enableStrictPrivacy = options.enableStrictPrivacy ?? false
this.enableCanvasRecording = options.enableCanvasRecording ?? false
this.enablePerformanceRecording =
options.enablePerformanceRecording ?? true
// default to inlining stylesheets/images locally to help with recording accuracy
this.inlineImages = options.inlineImages ?? this._isOnLocalHost
this.inlineStylesheet = options.inlineStylesheet ?? this._isOnLocalHost
this.samplingStrategy = {
canvasFactor: 0.5,
canvasMaxSnapshotDimension: 360,
canvasClearWebGLBuffer: true,
...(options.samplingStrategy ?? {}),
}
this._backendUrl = options?.backendUrl ?? 'https://pub.highlight.run'
// If _backendUrl is a relative URL, convert it to an absolute URL
// so that it's usable from a web worker.
if (this._backendUrl[0] === '/') {
this._backendUrl = new URL(this._backendUrl, document.baseURI).href
}
const client = new GraphQLClient(`${this._backendUrl}`, {
headers: {},
})
this.graphqlSDK = getSdk(
client,
getGraphQLRequestWrapper(
this.sessionData?.sessionSecureID ||
this.options?.sessionSecureID,
),
)
this.environment = options.environment ?? 'production'
this.appVersion = options.appVersion
this.serviceName = options.serviceName ?? ''
if (typeof options.organizationID === 'string') {
this.organizationID = options.organizationID
} else {
this.organizationID = options.organizationID.toString()
}
// disable inline stylesheets for aerotime
if (this.organizationID === 'jgoqo9el') {
this.inlineStylesheet = false
}
this.isRunningOnHighlight =
this.organizationID === '1' || this.organizationID === '1jdkoe52'
this.firstloadVersion = options.firstloadVersion || 'unknown'
this.sessionShortcut = options.sessionShortcut || false
this._onToggleFeedbackFormVisibility = () => {}
// We only want to store a subset of the options for debugging purposes. Firstload version is stored as another field so we don't need to store it here.
const { firstloadVersion: _, ...optionsInternal } = options
this._optionsInternal = optionsInternal
this.listeners = []
this.events = []
this.hasSessionUnloaded = false
this.hasPushedData = false
if (window.Intercom) {
window.Intercom('onShow', () => {
window.Intercom('update', {
highlightSessionURL:
this.getCurrentSessionURLWithTimestamp(),
})
this.addProperties({ event: 'Intercom onShow' })
})
}
this._eventBytesSinceSnapshot = 0
this._lastSnapshotTime = new Date().getTime()
this._lastVisibilityChangeTime = new Date().getTime()
this._payloadId =
Number(
window.sessionStorage.getItem(SESSION_STORAGE_KEYS.PAYLOAD_ID),
) ?? 1
window.sessionStorage.setItem(
SESSION_STORAGE_KEYS.PAYLOAD_ID,
this._payloadId.toString(),
)
}
identify(user_identifier: string, user_object = {}, source?: Source) {
if (!user_identifier || user_identifier === '') {
console.warn(
`Highlight's identify() call was passed an empty identifier.`,
{ user_identifier, user_object },
)
return
}
this.sessionData.userIdentifier = user_identifier.toString()
this.sessionData.userObject = user_object
window.sessionStorage.setItem(
SESSION_STORAGE_KEYS.USER_IDENTIFIER,
user_identifier.toString(),
)
window.sessionStorage.setItem(
SESSION_STORAGE_KEYS.USER_OBJECT,
JSON.stringify(user_object),
)
this._worker.postMessage({
message: {
type: MessageType.Identify,
userIdentifier: user_identifier,
userObject: user_object,
source,
},
})
}
async pushCustomError(message: string, payload?: string) {
const result = await StackTrace.get()
const frames = result.slice(1)
this._firstLoadListeners.errors.push({
event: message,
type: 'custom',
url: window.location.href,
source: frames[0].fileName ?? '',
lineNumber: frames[0].lineNumber ?? 0,
columnNumber: frames[0].columnNumber ?? 0,
stackTrace: frames,
timestamp: new Date().toISOString(),
payload: payload,
})
}
async consumeCustomError(error: Error, message?: string, payload?: string) {
const res = ErrorStackParser.parse(error)
this._firstLoadListeners.errors.push({
event: message ? message + ':' + error.message : error.message,
type: 'custom',
url: window.location.href,
source: '',
lineNumber: res[0]?.lineNumber ? res[0]?.lineNumber : 0,
columnNumber: res[0]?.columnNumber ? res[0]?.columnNumber : 0,
stackTrace: res,
timestamp: new Date().toISOString(),
payload: payload,
})
}
addProperties(properties_obj = {}, typeArg?: PropertyType) {
// Remove any properties which throw on structuredClone
// (structuredClone is used when posting messages to the worker)
const obj = { ...properties_obj } as any
Object.entries(obj).forEach(([key, val]) => {
try {
structuredClone(val)
} catch {
delete obj[key]
}
})
this._worker.postMessage({
message: {
type: MessageType.Properties,
propertiesObject: obj,
propertyType: typeArg,
},
})
}
async initialize(options?: StartOptions): Promise<undefined> {
if (
(navigator?.webdriver && !window.Cypress) ||
navigator?.userAgent?.includes('Googlebot') ||
navigator?.userAgent?.includes('AdsBot')
) {
this._firstLoadListeners?.stopListening()
return
}
try {
// disable recording for filtered projects while allowing for reloaded sessions
if (!this.reloaded && this.organizationID === '6glrjqg9') {
if (Math.random() >= 0.02) {
this._firstLoadListeners?.stopListening()
return
}
}
if (options?.forceNew) {
await this._reset()
// effectively 'restart' recording by starting the new payload with a full snapshot
this.takeFullSnapshot()
return
}
const recordingStartTime = window.sessionStorage.getItem(
SESSION_STORAGE_KEYS.RECORDING_START_TIME,
)
if (!recordingStartTime) {
this._recordingStartTime = new Date().getTime()
window.sessionStorage.setItem(
SESSION_STORAGE_KEYS.RECORDING_START_TIME,
this._recordingStartTime.toString(),
)
} else {
this._recordingStartTime = parseInt(recordingStartTime, 10)
}
let clientID = getItem(LOCAL_STORAGE_KEYS['CLIENT_ID'])
if (!clientID) {
clientID = GenerateSecureID()
setItem(LOCAL_STORAGE_KEYS['CLIENT_ID'], clientID)
}
// To handle the 'Duplicate Tab' function, remove id from storage until page unload
window.sessionStorage.removeItem(SESSION_STORAGE_KEYS.SESSION_DATA)
// Duplicate of logic inside FirstLoadListeners.setupNetworkListener,
// needed for initializeSession
let enableNetworkRecording
if (this.options.disableSessionRecording) {
enableNetworkRecording = false
} else if (this.options.disableNetworkRecording !== undefined) {
enableNetworkRecording = false
} else if (typeof this.options.networkRecording === 'boolean') {
enableNetworkRecording = false
} else {
enableNetworkRecording =
this.options.networkRecording?.recordHeadersAndBody || false
}
let destinationDomains: string[] = []
if (
typeof this.options.networkRecording === 'object' &&
this.options.networkRecording.destinationDomains?.length
) {
destinationDomains =
this.options.networkRecording.destinationDomains
}
if (this._isCrossOriginIframe) {
// wait for 'cross-origin iframe ready' message
await this._setupCrossOriginIframe()
} else {
const gr = await this.graphqlSDK.initializeSession({
organization_verbose_id: this.organizationID,
enable_strict_privacy: this.enableStrictPrivacy,
enable_recording_network_contents: enableNetworkRecording,
clientVersion: this.firstloadVersion,
firstloadVersion: this.firstloadVersion,
clientConfig: JSON.stringify(this._optionsInternal),
environment: this.environment,
id: clientID,
appVersion: this.appVersion,
serviceName: this.serviceName,
session_secure_id: this.sessionData.sessionSecureID,
client_id: clientID,
network_recording_domains: destinationDomains,
disable_session_recording:
this.options.disableSessionRecording,
})
if (
gr.initializeSession.secure_id !==
this.sessionData.sessionSecureID
) {
this.logger.log(
`Unexpected secure id returned by initializeSession: ${gr.initializeSession.secure_id}`,
)
}
this.sessionData.sessionSecureID =
gr.initializeSession.secure_id
this.sessionData.projectID = parseInt(
gr?.initializeSession?.project_id || '0',
)
if (
!this.sessionData.projectID ||
!this.sessionData.sessionSecureID
) {
console.error(
'Failed to initialize Highlight; an error occurred on our end.',
this.sessionData,
)
return
}
}
this.logger.log(
`Loaded Highlight
Remote: ${this._backendUrl}
Project ID: ${this.sessionData.projectID}
SessionSecureID: ${this.sessionData.sessionSecureID}`,
)
this.options.sessionSecureID = this.sessionData.sessionSecureID
this._worker.postMessage({
message: {
type: MessageType.Initialize,
sessionSecureID: this.sessionData.sessionSecureID,
backend: this._backendUrl,
debug: !!this.debugOptions.clientInteractions,
recordingStartTime: this._recordingStartTime,
},
})
window.sessionStorage.setItem(
SESSION_STORAGE_KEYS.SESSION_SECURE_ID,
this.sessionData.sessionSecureID,
)
if (this.sessionData.userIdentifier) {
this.identify(
this.sessionData.userIdentifier,
this.sessionData.userObject,
)
}
if (!this._firstLoadListeners.isListening()) {
this._firstLoadListeners.startListening()
} else if (!this._firstLoadListeners.hasNetworkRecording) {
// for firstload versions < 3.0. even if they are listening, add network listeners
FirstLoadListeners.setupNetworkListener(
this._firstLoadListeners,
this.options,
)
}
if (this.pushPayloadTimerId) {
clearTimeout(this.pushPayloadTimerId)
this.pushPayloadTimerId = undefined
}
if (!this._isCrossOriginIframe) {
this.pushPayloadTimerId = setTimeout(() => {
this._save()
}, FIRST_SEND_FREQUENCY)
}
// if disabled, do not record session events / rrweb events.
// we still use firstload listeners to record frontend js console logs and errors.
if (this.options.disableSessionRecording) {
this.logger.log(
`Highlight is NOT RECORDING a session replay per H.init setting.`,
)
this.ready = true
this.state = 'Recording'
this.manualStopped = false
return
}
const { getDeviceDetails } = getPerformanceMethods()
if (getDeviceDetails) {
this.recordMetric([
{
name: MetricName.DeviceMemory,
value: getDeviceDetails().deviceMemory,
category: MetricCategory.Device,
group: window.location.href,
},
])
}
const emit = (event: eventWithTime) => {
this.events.push(event)
}
emit.bind(this)
if (!this._recordStop) {
let logger = undefined
if (
(typeof this.options.debug === 'boolean' &&
this.options.debug) ||
(typeof this.options.debug === 'object' &&
this.options.debug.domRecording)
) {
logger = {
debug: this.logger.log,
warn: HighlightWarning,
}
}
this._recordStop = record({
ignoreClass: 'highlight-ignore',
blockClass: 'highlight-block',
emit,
recordCrossOriginIframes:
this.options.recordCrossOriginIframe,
enableStrictPrivacy: this.enableStrictPrivacy,
maskAllInputs: this.enableStrictPrivacy,
recordCanvas: this.enableCanvasRecording,
sampling: {
canvas: {
fps: this.samplingStrategy.canvas,
fpsManual:
this.samplingStrategy.canvasManualSnapshot,
resizeFactor: this.samplingStrategy.canvasFactor,
clearWebGLBuffer:
this.samplingStrategy.canvasClearWebGLBuffer,
initialSnapshotDelay:
this.samplingStrategy
.canvasInitialSnapshotDelay,
dataURLOptions: {
type: 'image/webp',
quality: 0.9,
},
maxSnapshotDimension:
this.samplingStrategy
.canvasMaxSnapshotDimension,
},
},
keepIframeSrcFn: (_src) => {
return !this.options.recordCrossOriginIframe
},
inlineImages: this.inlineImages,
inlineStylesheet: this.inlineStylesheet,
plugins: [getRecordSequentialIdPlugin()],
logger,
})
if (this.options.recordCrossOriginIframe) {
this._setupCrossOriginIframeParent()
}
// recordStop is not part of listeners because we do not actually want to stop rrweb
// rrweb has some bugs that make the stop -> restart workflow broken (eg iframe listeners)
const viewport = {
height: window.innerHeight,
width: window.innerWidth,
}
this.addCustomEvent('Viewport', viewport)
this.submitViewportMetrics(viewport)
}
if (document.referrer) {
// Don't record the referrer if it's the same origin.
// Non-single page apps might have the referrer set to the same origin.
// If we record this then the referrer data will not be useful.
// Most users will want to see referrers outside of their website/app.
// This will be a configuration set in `H.init()` later.
if (
!(
window &&
document.referrer.includes(window.location.origin)
)
) {
this.addCustomEvent<string>('Referrer', document.referrer)
this.addProperties(
{ referrer: document.referrer },
{ type: 'session' },
)
}
}
this._setupWindowListeners()
this.ready = true
this.state = 'Recording'
this.manualStopped = false
} catch (e) {
if (this._isOnLocalHost) {
console.error(e)
HighlightWarning('initializeSession', e)
}
}
}
async _visibilityHandler(hidden: boolean) {
if (this.manualStopped) {
this.logger.log(`Ignoring visibility event due to manual stop.`)
return
}
if (
new Date().getTime() - this._lastVisibilityChangeTime <
VISIBILITY_DEBOUNCE_MS
) {
return
}
this._lastVisibilityChangeTime = new Date().getTime()
this.logger.log(`Detected window ${hidden ? 'hidden' : 'visible'}.`)
if (!hidden) {
if (this.options.disableBackgroundRecording) {
await this.initialize()
}
this.addCustomEvent('TabHidden', false)
} else {
this.addCustomEvent('TabHidden', true)
if ('sendBeacon' in navigator) {
try {
await this._sendPayload({
isBeacon: true,
sendFn: (payload) => {
let blob = new Blob(
[
JSON.stringify({
query: print(PushPayloadDocument),
variables: payload,
}),
],
{
type: 'application/json',
},
)
navigator.sendBeacon(`${this._backendUrl}`, blob)
return Promise.resolve(0)
},
})
} catch (e) {
if (this._isOnLocalHost) {
console.error(e)
HighlightWarning('_sendPayload', e)
}
}
}
if (this.options.disableBackgroundRecording) {
this.stopRecording()
}
}
}
async _setupCrossOriginIframe() {
this.logger.log(`highlight in cross-origin iframe is waiting `)
// wait until we get a initialization message from the parent window
await new Promise<void>((r) => {
const listener = (message: MessageEvent) => {
if (message.data.highlight === IFRAME_PARENT_READY) {
const msg = message.data as HighlightIframeMessage
this.logger.log(`highlight got window message `, msg)
this.sessionData.projectID = msg.projectID
this.sessionData.sessionSecureID = msg.sessionSecureID
// reply back that we got the message and are set up
window.parent.postMessage(
{
highlight: IFRAME_PARENT_RESPONSE,
} as HighlightIframeReponse,
'*',
)
// stop listening to parent messages
window.removeEventListener('message', listener)
r()
}
}
window.addEventListener('message', listener)
})
}
_setupCrossOriginIframeParent() {
this.logger.log(
`highlight setting up cross origin iframe parent notification`,
)
// notify iframes that highlight is ready
const iframeInterval = setInterval(() => {
window.document.querySelectorAll('iframe').forEach((iframe) => {
iframe.contentWindow?.postMessage(
{
highlight: IFRAME_PARENT_READY,
projectID: this.sessionData.projectID,
sessionSecureID: this.sessionData.sessionSecureID,
} as HighlightIframeMessage,
'*',
)
})
}, 100) as unknown as number
// once an iframe responds that it got our message and it ready, clear the interval
const listener = (message: MessageEvent) => {
if (message.data.highlight === IFRAME_PARENT_RESPONSE) {
this.logger.log(
`highlight got response from initialized iframe`,
)
// stop sending iframe messages
window.clearInterval(iframeInterval)
// stop listening to parent messages
window.removeEventListener('message', listener)
}
}
window.addEventListener('message', listener)
}
_setupWindowListeners() {
try {
const highlightThis = this
if (this.enableSegmentIntegration) {
this.listeners.push(
SegmentIntegrationListener((obj: any) => {
if (obj.type === 'track') {
const properties: { [key: string]: string } = {}
properties['segment-event'] = obj.event
highlightThis.addProperties(properties, {
type: 'track',
source: 'segment',
})
} else if (obj.type === 'identify') {
// Removes the starting and end quotes
// Example: "boba" -> boba
const trimmedUserId = obj.userId.replace(
/^"(.*)"$/,
'$1',
)
highlightThis.identify(
trimmedUserId,
obj.traits,
'segment',
)
}
}),
)
}
this.listeners.push(
PathListener((url: string) => {
if (this.reloaded) {
this.addCustomEvent<string>('Reload', url)
this.reloaded = false
highlightThis.addProperties(
{ reload: true },
{ type: 'session' },
)
} else {
this.addCustomEvent<string>('Navigate', url)
}
highlightThis.addProperties(
{ 'visited-url': url },
{ type: 'session' },
)
}),
)
this.listeners.push(
ViewportResizeListener((viewport) => {
this.addCustomEvent('Viewport', viewport)
this.submitViewportMetrics(viewport)
}),
)
this.listeners.push(
ClickListener((clickTarget, event) => {
if (clickTarget) {
this.addCustomEvent('Click', clickTarget)
}
let selector = null
let textContent = null
if (event && event.target) {
const t = event.target as HTMLElement
selector = getSimpleSelector(t)
textContent = t.textContent
// avoid sending huge strings here
if (textContent && textContent.length > 2000) {
textContent = textContent.substring(0, 2000)
}
}
highlightThis.addProperties(
{
clickTextContent: textContent,
clickSelector: selector,
},
{ type: 'session' },
)
}),
)
this.listeners.push(
FocusListener((focusTarget) => {
if (focusTarget) {
this.addCustomEvent('Focus', focusTarget)
}
}),
)