@cloudcare/browser-rum 3.3.14 → 3.3.16

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 (106) hide show
  1. package/README.md +60 -0
  2. package/README.zh.md +48 -0
  3. package/bundle/dataflux-rum.js +1 -1
  4. package/cjs/boot/buildEnv.js +1 -1
  5. package/cjs/boot/perStartRum.js +3 -0
  6. package/cjs/boot/perStartRum.js.map +1 -1
  7. package/cjs/boot/recorderApi.js +72 -56
  8. package/cjs/boot/recorderApi.js.map +1 -1
  9. package/cjs/boot/rumPublicApi.js +35 -3
  10. package/cjs/boot/rumPublicApi.js.map +1 -1
  11. package/cjs/boot/startRecording.js +4 -4
  12. package/cjs/boot/startRecording.js.map +1 -1
  13. package/cjs/constants.js +8 -8
  14. package/cjs/constants.js.map +1 -1
  15. package/cjs/domain/assembly.js +14 -1
  16. package/cjs/domain/assembly.js.map +1 -1
  17. package/cjs/domain/configuration.js +62 -0
  18. package/cjs/domain/configuration.js.map +1 -1
  19. package/cjs/domain/deflate/deflateWorker.js +1 -1
  20. package/cjs/domain/encoderStreamId.js +2 -1
  21. package/cjs/domain/encoderStreamId.js.map +1 -1
  22. package/cjs/domain/replay/record/canvasEncodeWorker.js +1 -1
  23. package/cjs/domain/replay/record/record.js +2 -3
  24. package/cjs/domain/replay/record/record.js.map +1 -1
  25. package/cjs/domain/replay/record/serializationUtils.js +8 -15
  26. package/cjs/domain/replay/record/serializationUtils.js.map +1 -1
  27. package/cjs/domain/replay/record/serialize.js +14 -6
  28. package/cjs/domain/replay/record/serialize.js.map +1 -1
  29. package/cjs/domain/requestCollection.js +3 -1
  30. package/cjs/domain/requestCollection.js.map +1 -1
  31. package/cjs/domain/rumEventsCollection/error/errorCollection.js +6 -8
  32. package/cjs/domain/rumEventsCollection/error/errorCollection.js.map +1 -1
  33. package/cjs/domain/rumEventsCollection/resource/resourceCollection.js +5 -0
  34. package/cjs/domain/rumEventsCollection/resource/resourceCollection.js.map +1 -1
  35. package/cjs/domain/rumSessionManager.js +3 -3
  36. package/cjs/domain/rumSessionManager.js.map +1 -1
  37. package/cjs/domain/tracing/tracer.js +5 -1
  38. package/cjs/domain/tracing/tracer.js.map +1 -1
  39. package/cjs/domain/visitorId/index.js +417 -0
  40. package/cjs/domain/visitorId/index.js.map +1 -0
  41. package/cjs/index.js +7 -0
  42. package/cjs/index.js.map +1 -1
  43. package/cjs/transport/startRumBatch.js +44 -3
  44. package/cjs/transport/startRumBatch.js.map +1 -1
  45. package/esm/boot/buildEnv.js +1 -1
  46. package/esm/boot/perStartRum.js +3 -0
  47. package/esm/boot/perStartRum.js.map +1 -1
  48. package/esm/boot/recorderApi.js +72 -56
  49. package/esm/boot/recorderApi.js.map +1 -1
  50. package/esm/boot/rumPublicApi.js +36 -4
  51. package/esm/boot/rumPublicApi.js.map +1 -1
  52. package/esm/boot/startRecording.js +4 -4
  53. package/esm/boot/startRecording.js.map +1 -1
  54. package/esm/constants.js +1 -8
  55. package/esm/constants.js.map +1 -1
  56. package/esm/domain/assembly.js +15 -2
  57. package/esm/domain/assembly.js.map +1 -1
  58. package/esm/domain/configuration.js +62 -1
  59. package/esm/domain/configuration.js.map +1 -1
  60. package/esm/domain/deflate/deflateWorker.js +1 -1
  61. package/esm/domain/encoderStreamId.js +2 -1
  62. package/esm/domain/encoderStreamId.js.map +1 -1
  63. package/esm/domain/replay/record/canvasEncodeWorker.js +1 -1
  64. package/esm/domain/replay/record/record.js +1 -2
  65. package/esm/domain/replay/record/record.js.map +1 -1
  66. package/esm/domain/replay/record/serializationUtils.js +8 -15
  67. package/esm/domain/replay/record/serializationUtils.js.map +1 -1
  68. package/esm/domain/replay/record/serialize.js +13 -5
  69. package/esm/domain/replay/record/serialize.js.map +1 -1
  70. package/esm/domain/requestCollection.js +4 -2
  71. package/esm/domain/requestCollection.js.map +1 -1
  72. package/esm/domain/rumEventsCollection/error/errorCollection.js +6 -8
  73. package/esm/domain/rumEventsCollection/error/errorCollection.js.map +1 -1
  74. package/esm/domain/rumEventsCollection/resource/resourceCollection.js +5 -0
  75. package/esm/domain/rumEventsCollection/resource/resourceCollection.js.map +1 -1
  76. package/esm/domain/rumSessionManager.js +3 -3
  77. package/esm/domain/rumSessionManager.js.map +1 -1
  78. package/esm/domain/tracing/tracer.js +6 -2
  79. package/esm/domain/tracing/tracer.js.map +1 -1
  80. package/esm/domain/visitorId/index.js +406 -0
  81. package/esm/domain/visitorId/index.js.map +1 -0
  82. package/esm/index.js +1 -0
  83. package/esm/index.js.map +1 -1
  84. package/esm/transport/startRumBatch.js +45 -4
  85. package/esm/transport/startRumBatch.js.map +1 -1
  86. package/package.json +4 -4
  87. package/src/boot/perStartRum.js +4 -0
  88. package/src/boot/recorderApi.js +73 -59
  89. package/src/boot/rumPublicApi.js +38 -4
  90. package/src/boot/startRecording.js +7 -3
  91. package/src/constants.js +1 -8
  92. package/src/domain/assembly.js +28 -2
  93. package/src/domain/configuration.js +154 -0
  94. package/src/domain/encoderStreamId.js +2 -2
  95. package/src/domain/replay/record/record.js +1 -2
  96. package/src/domain/replay/record/serializationUtils.js +10 -24
  97. package/src/domain/replay/record/serialize.js +25 -5
  98. package/src/domain/requestCollection.js +4 -1
  99. package/src/domain/rumEventsCollection/error/errorCollection.js +10 -8
  100. package/src/domain/rumEventsCollection/resource/resourceCollection.js +3 -0
  101. package/src/domain/rumSessionManager.js +8 -7
  102. package/src/domain/tracing/tracer.js +15 -2
  103. package/src/domain/visitorId/index.js +571 -0
  104. package/src/index.js +1 -0
  105. package/src/transport/startRumBatch.js +61 -3
  106. package/types/index.d.ts +23 -1
@@ -0,0 +1,571 @@
1
+ import {
2
+ DOM_EVENT,
3
+ ONE_HOUR,
4
+ UUID,
5
+ WeakSet,
6
+ addEventListener,
7
+ canUseEventBridge,
8
+ display,
9
+ getEventBridge,
10
+ getOrigin,
11
+ initFetchObservable,
12
+ initXhrObservable,
13
+ isRequest,
14
+ noop,
15
+ normalizeUrl,
16
+ shallowClone,
17
+ timeStampNow
18
+ } from '@cloudcare/browser-core'
19
+ import { isAllowedRequestUrl } from '../rumEventsCollection/resource/resourceUtils'
20
+ import { createRandomHexIdentifier } from '../tracing/traceIdentifier'
21
+
22
+ export var VISITOR_ID_CONTEXT_KEY = 'visitor_id'
23
+ export var VISITOR_ID_STORAGE_KEY = '_gc_visitor_id'
24
+ export var DEFAULT_VISITOR_ID_TTL_HOURS = 24
25
+
26
+ var PERSISTENT_ID_PREFIX = 'p'
27
+ var SESSION_ID_PREFIX = 's'
28
+ var VISITOR_ID_PATTERN = /^[ps][0-9a-f]{32}$/
29
+ var FETCH_INIT_FIELDS = [
30
+ 'method', 'headers', 'body', 'referrer', 'referrerPolicy', 'mode',
31
+ 'credentials', 'cache', 'redirect', 'integrity', 'keepalive', 'signal',
32
+ 'window', 'duplex', 'priority', 'attributionReporting', 'browsingTopics'
33
+ ]
34
+
35
+ export function startVisitorId(configuration) {
36
+ if (!configuration.visitorId.enabled) {
37
+ return createVisitorIdStub()
38
+ }
39
+
40
+ var manager = createVisitorIdManager(configuration.visitorId)
41
+ var requestCollection = startVisitorIdRequestCollection(
42
+ configuration,
43
+ manager
44
+ )
45
+
46
+ return {
47
+ getId: manager.getId,
48
+ reset: manager.reset,
49
+ stop: function () {
50
+ requestCollection.stop()
51
+ manager.stop()
52
+ }
53
+ }
54
+ }
55
+
56
+ export function createVisitorIdManager(visitorIdConfiguration, options) {
57
+ var browserManager = getNativeVisitorId()
58
+ ? undefined
59
+ : createBrowserVisitorIdManager(visitorIdConfiguration, options)
60
+
61
+ function getBrowserManager() {
62
+ if (!browserManager) {
63
+ browserManager = createBrowserVisitorIdManager(visitorIdConfiguration, options)
64
+ }
65
+ return browserManager
66
+ }
67
+
68
+ return {
69
+ getId: function () {
70
+ return getNativeVisitorId() || getBrowserManager().getId()
71
+ },
72
+ reset: function () {
73
+ // The App owns native identity rotation. A Web-only reset would split it.
74
+ if (!getNativeVisitorId()) {
75
+ getBrowserManager().reset()
76
+ }
77
+ },
78
+ stop: function () {
79
+ if (browserManager) {
80
+ browserManager.stop()
81
+ }
82
+ }
83
+ }
84
+ }
85
+
86
+ function getNativeVisitorId() {
87
+ try {
88
+ if (canUseEventBridge()) {
89
+ var id = getEventBridge().getVisitorId()
90
+ // Preserve the App value exactly, while keeping it safe for HTTP headers.
91
+ if (
92
+ typeof id === 'string' && id.length > 0 && id.length <= 256 &&
93
+ !/[^\x21-\x7e]/.test(id)
94
+ ) {
95
+ return id
96
+ }
97
+ }
98
+ } catch (error) {
99
+ // Older or not-yet-ready native bridges must not break Web collection.
100
+ }
101
+ }
102
+
103
+ function createBrowserVisitorIdManager(visitorIdConfiguration, options) {
104
+ if (options === undefined) {
105
+ options = {}
106
+ }
107
+
108
+ var getNow = options.getNow || timeStampNow
109
+ var createIdentifier = options.createIdentifier || createIdentifierValue
110
+ var localStorage = getStorage(options, 'localStorage')
111
+ var sessionStorage = getStorage(options, 'sessionStorage')
112
+ var ttl = visitorIdConfiguration.ttlHours * ONE_HOUR
113
+ var currentRecord = loadOrCreateRecord()
114
+ var storageListener = localStorage
115
+ ? addEventListener(window, DOM_EVENT.STORAGE, function (event) {
116
+ if (event.key !== VISITOR_ID_STORAGE_KEY) {
117
+ return
118
+ }
119
+ if (event.storageArea && event.storageArea !== localStorage) {
120
+ return
121
+ }
122
+ // Storage events may be queued before a later reset in this or another tab.
123
+ // Read the current value instead of replaying the event's stale snapshot.
124
+ var nextRecord = readRecord(
125
+ localStorage,
126
+ PERSISTENT_ID_PREFIX,
127
+ getNow(),
128
+ ttl
129
+ )
130
+ if (
131
+ nextRecord &&
132
+ currentRecord &&
133
+ compareRecords(nextRecord, currentRecord) < 0
134
+ ) {
135
+ return
136
+ }
137
+ currentRecord = nextRecord
138
+ })
139
+ : { stop: noop }
140
+
141
+ function loadOrCreateRecord() {
142
+ var now = getNow()
143
+ var persistentRecord = readRecord(
144
+ localStorage,
145
+ PERSISTENT_ID_PREFIX,
146
+ now,
147
+ ttl
148
+ )
149
+ var sessionRecord = readRecord(sessionStorage, SESSION_ID_PREFIX, now, ttl)
150
+ if (sessionRecord && persistentRecord) {
151
+ var order = compareRecords(sessionRecord, persistentRecord)
152
+ return order > 0 ||
153
+ (order === 0 &&
154
+ sessionRecord.revision === undefined &&
155
+ persistentRecord.revision === undefined)
156
+ ? sessionRecord
157
+ : persistentRecord
158
+ }
159
+ if (sessionRecord || persistentRecord) {
160
+ return sessionRecord || persistentRecord
161
+ }
162
+
163
+ return createAndPersistRecord(now)
164
+ }
165
+
166
+ function createAndPersistRecord(now) {
167
+ var identifier = createIdentifier()
168
+ // Date.now() can return the same value for several resets. Keep their order
169
+ // independently from the TTL timestamp, including when session cleanup fails.
170
+ var revision = 0
171
+ ;[
172
+ currentRecord,
173
+ readRecord(localStorage, PERSISTENT_ID_PREFIX, now, ttl),
174
+ readRecord(sessionStorage, SESSION_ID_PREFIX, now, ttl)
175
+ ].forEach(function (record) {
176
+ if (record && record.createdAt === now) {
177
+ revision = Math.max(revision, (record.revision || 0) + 1)
178
+ }
179
+ })
180
+ var persistentRecord = {
181
+ id: PERSISTENT_ID_PREFIX + identifier,
182
+ createdAt: now,
183
+ revision: revision
184
+ }
185
+ var storedPersistentRecord = writeRecord(
186
+ localStorage,
187
+ persistentRecord,
188
+ PERSISTENT_ID_PREFIX,
189
+ now,
190
+ ttl
191
+ )
192
+ if (storedPersistentRecord) {
193
+ try {
194
+ sessionStorage && sessionStorage.removeItem(VISITOR_ID_STORAGE_KEY)
195
+ } catch (error) {
196
+ // Ordering metadata still supersedes the stale session record.
197
+ }
198
+ return storedPersistentRecord
199
+ }
200
+
201
+ var sessionRecord = {
202
+ id: SESSION_ID_PREFIX + identifier,
203
+ createdAt: now,
204
+ revision: revision
205
+ }
206
+ return (
207
+ writeRecord(sessionStorage, sessionRecord, SESSION_ID_PREFIX, now, ttl) ||
208
+ sessionRecord
209
+ )
210
+ }
211
+
212
+ function ensureCurrentRecord() {
213
+ var now = getNow()
214
+ if (!isValidRecord(currentRecord, undefined, now, ttl)) {
215
+ currentRecord = loadOrCreateRecord()
216
+ }
217
+ return currentRecord
218
+ }
219
+
220
+ return {
221
+ getId: function () {
222
+ return ensureCurrentRecord().id
223
+ },
224
+ reset: function () {
225
+ currentRecord = createAndPersistRecord(getNow())
226
+ },
227
+ stop: storageListener.stop
228
+ }
229
+ }
230
+
231
+ export function startVisitorIdRequestCollection(configuration, manager) {
232
+ var xhrHeaderReservation
233
+ var xhrSubscription = initXhrObservable().subscribe(function (context) {
234
+ if (context.state === 'start') {
235
+ context.visitorId = xhrHeaderReservation.apply(context)
236
+ }
237
+ })
238
+ xhrHeaderReservation = startVisitorIdXhrHeaderReservation(
239
+ configuration,
240
+ manager
241
+ )
242
+ var fetchSubscription = initFetchObservable().subscribe(function (context) {
243
+ if (
244
+ context.state === 'start' &&
245
+ shouldInjectVisitorId(configuration, context.url)
246
+ ) {
247
+ var visitorId = manager.getId()
248
+ if (
249
+ injectVisitorIdIntoFetch(
250
+ context,
251
+ configuration.visitorId.header,
252
+ visitorId
253
+ )
254
+ ) {
255
+ context.visitorId = visitorId
256
+ }
257
+ }
258
+ })
259
+
260
+ return {
261
+ stop: function () {
262
+ xhrHeaderReservation.stop()
263
+ xhrSubscription.unsubscribe()
264
+ fetchSubscription.unsubscribe()
265
+ }
266
+ }
267
+ }
268
+
269
+ export function shouldInjectVisitorId(configuration, url) {
270
+ return (
271
+ isAllowedRequestUrl(configuration, url) &&
272
+ matchesVisitorIdUrl(configuration.visitorId.match, url)
273
+ )
274
+ }
275
+
276
+ export function matchesVisitorIdUrl(matchOptions, url) {
277
+ for (var index = 0; index < matchOptions.length; index += 1) {
278
+ var matchOption = matchOptions[index]
279
+ try {
280
+ if (typeof matchOption === 'function' && matchOption(url)) {
281
+ return true
282
+ }
283
+ if (matchOption instanceof RegExp) {
284
+ var matched
285
+ try {
286
+ matchOption.lastIndex = 0
287
+ matched = matchOption.test(url)
288
+ } finally {
289
+ matchOption.lastIndex = 0
290
+ }
291
+ if (matched) {
292
+ return true
293
+ }
294
+ }
295
+ if (
296
+ typeof matchOption === 'string' &&
297
+ url.indexOf(matchOption) === 0 &&
298
+ getOrigin(matchOption) === getOrigin(url)
299
+ ) {
300
+ return true
301
+ }
302
+ } catch (error) {
303
+ display.error('Visitor ID URL matcher threw an error:', error)
304
+ }
305
+ }
306
+ return false
307
+ }
308
+
309
+ function injectVisitorIdIntoFetch(context, header, visitorId) {
310
+ try {
311
+ var originalInit = context.init
312
+ if (
313
+ originalInit != null &&
314
+ typeof originalInit !== 'object' &&
315
+ typeof originalInit !== 'function'
316
+ ) {
317
+ return
318
+ }
319
+ var init = shallowClone(originalInit)
320
+ // RequestInit is a WebIDL dictionary: inherited and non-enumerable fields
321
+ // count too. Materialize them so later tracing instrumentation preserves them.
322
+ FETCH_INIT_FIELDS.forEach(function (field) {
323
+ if (
324
+ originalInit &&
325
+ field in originalInit &&
326
+ !Object.prototype.hasOwnProperty.call(init, field)
327
+ ) {
328
+ init[field] = originalInit[field]
329
+ }
330
+ })
331
+ var headers = new Headers(
332
+ init.headers === undefined && isRequest(context.input)
333
+ ? context.input.headers
334
+ : init.headers
335
+ )
336
+ if (headers.has(header)) {
337
+ displayVisitorIdHeaderOverrideWarning('fetch')
338
+ }
339
+ headers.set(header, visitorId)
340
+ init.headers = headers
341
+ // Avoid constructing a Request here: that can consume the caller's body even
342
+ // if a later header operation fails. Native fetch handles the body once.
343
+ context.init = init
344
+ return true
345
+ } catch (error) {
346
+ display.error('Unable to inject the Visitor ID header into fetch:', error)
347
+ }
348
+ }
349
+
350
+ function startVisitorIdXhrHeaderReservation(configuration, manager) {
351
+ var header = configuration.visitorId.header
352
+ var matchedXhrs = new WeakSet()
353
+ var callerHeaderXhrs = new WeakSet()
354
+ var sentXhrs = new WeakSet()
355
+ var injectedIds = new WeakMap()
356
+ var originalOpen = XMLHttpRequest.prototype.open
357
+ var stopped = false
358
+ var openInstrumentation = function () {
359
+ if (stopped) {
360
+ return originalOpen.apply(this, arguments)
361
+ }
362
+ var xhr = this
363
+ matchedXhrs.delete(xhr)
364
+ callerHeaderXhrs.delete(xhr)
365
+ sentXhrs.delete(xhr)
366
+ injectedIds.delete(xhr)
367
+ try {
368
+ if (
369
+ shouldInjectVisitorId(configuration, normalizeUrl(String(arguments[1])))
370
+ ) {
371
+ matchedXhrs.add(xhr)
372
+ }
373
+ } catch (error) {
374
+ // Let native open() validate the URL and preserve its original exception.
375
+ }
376
+ try {
377
+ // open() synchronously dispatches OPENED; handlers may set headers/send.
378
+ return originalOpen.apply(xhr, arguments)
379
+ } catch (error) {
380
+ matchedXhrs.delete(xhr)
381
+ callerHeaderXhrs.delete(xhr)
382
+ sentXhrs.delete(xhr)
383
+ injectedIds.delete(xhr)
384
+ throw error
385
+ }
386
+ }
387
+ XMLHttpRequest.prototype.open = openInstrumentation
388
+ var originalSend = XMLHttpRequest.prototype.send
389
+ var sendInstrumentation = function () {
390
+ if (stopped || !matchedXhrs.has(this)) {
391
+ return originalSend.apply(this, arguments)
392
+ }
393
+ var xhr = this
394
+ var wasSent = sentXhrs.has(xhr)
395
+ sentXhrs.add(xhr)
396
+ try {
397
+ return originalSend.apply(xhr, arguments)
398
+ } catch (error) {
399
+ // A failed first send leaves the native XHR open for header edits/retry.
400
+ // A failed duplicate send must not reopen an already-sent reservation.
401
+ if (!wasSent) {
402
+ sentXhrs.delete(xhr)
403
+ }
404
+ throw error
405
+ }
406
+ }
407
+ XMLHttpRequest.prototype.send = sendInstrumentation
408
+ var originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader
409
+ var setRequestHeaderInstrumentation = function (name, value) {
410
+ if (
411
+ !stopped &&
412
+ typeof name === 'string' &&
413
+ name.toLowerCase() === header &&
414
+ matchedXhrs.has(this) &&
415
+ !sentXhrs.has(this)
416
+ ) {
417
+ callerHeaderXhrs.add(this)
418
+ return
419
+ }
420
+ return originalSetRequestHeader.apply(this, arguments)
421
+ }
422
+ XMLHttpRequest.prototype.setRequestHeader = setRequestHeaderInstrumentation
423
+
424
+ return {
425
+ apply: function (context) {
426
+ var xhr = context.xhr
427
+ if (!matchedXhrs.has(xhr)) {
428
+ return
429
+ }
430
+ if (callerHeaderXhrs.delete(xhr)) {
431
+ displayVisitorIdHeaderOverrideWarning('XHR')
432
+ }
433
+ if (injectedIds.has(xhr)) {
434
+ // Native send() may throw before sending and leave the XHR reusable.
435
+ // Headers cannot be replaced once set, so retain the first injected ID
436
+ // even if resetVisitorId() was called before the retry.
437
+ return injectedIds.get(xhr)
438
+ }
439
+
440
+ var visitorId = manager.getId()
441
+ try {
442
+ originalSetRequestHeader.call(xhr, header, visitorId)
443
+ injectedIds.set(xhr, visitorId)
444
+ return visitorId
445
+ } catch (error) {
446
+ display.error(
447
+ 'Unable to inject the Visitor ID header into XHR:',
448
+ error
449
+ )
450
+ return
451
+ }
452
+ },
453
+ stop: function () {
454
+ stopped = true
455
+ if (XMLHttpRequest.prototype.open === openInstrumentation) {
456
+ XMLHttpRequest.prototype.open = originalOpen
457
+ }
458
+ if (XMLHttpRequest.prototype.send === sendInstrumentation) {
459
+ XMLHttpRequest.prototype.send = originalSend
460
+ }
461
+ if (
462
+ XMLHttpRequest.prototype.setRequestHeader ===
463
+ setRequestHeaderInstrumentation
464
+ ) {
465
+ XMLHttpRequest.prototype.setRequestHeader = originalSetRequestHeader
466
+ }
467
+ }
468
+ }
469
+ }
470
+
471
+ function displayVisitorIdHeaderOverrideWarning(requestType) {
472
+ display.warn(
473
+ 'Visitor ID header is already set on this ' +
474
+ requestType +
475
+ ' request. It was replaced with the SDK-managed value.'
476
+ )
477
+ }
478
+
479
+ function getStorage(options, storageName) {
480
+ if (Object.prototype.hasOwnProperty.call(options, storageName)) {
481
+ return options[storageName]
482
+ }
483
+ try {
484
+ return window[storageName]
485
+ } catch (error) {
486
+ return undefined
487
+ }
488
+ }
489
+
490
+ function readRecord(storage, expectedPrefix, now, ttl) {
491
+ if (!storage) {
492
+ return undefined
493
+ }
494
+ try {
495
+ return parseRecord(
496
+ storage.getItem(VISITOR_ID_STORAGE_KEY),
497
+ expectedPrefix,
498
+ now,
499
+ ttl
500
+ )
501
+ } catch (error) {
502
+ return undefined
503
+ }
504
+ }
505
+
506
+ function writeRecord(storage, record, expectedPrefix, now, ttl) {
507
+ if (!storage) {
508
+ return undefined
509
+ }
510
+ try {
511
+ storage.setItem(VISITOR_ID_STORAGE_KEY, JSON.stringify(record))
512
+ } catch (error) {
513
+ return undefined
514
+ }
515
+
516
+ var storedRecord = readRecord(storage, expectedPrefix, now, ttl)
517
+ return storedRecord &&
518
+ storedRecord.id === record.id &&
519
+ compareRecords(storedRecord, record) === 0
520
+ ? storedRecord
521
+ : undefined
522
+ }
523
+
524
+ function parseRecord(rawRecord, expectedPrefix, now, ttl) {
525
+ if (!rawRecord) {
526
+ return undefined
527
+ }
528
+ try {
529
+ var record = JSON.parse(rawRecord)
530
+ return isValidRecord(record, expectedPrefix, now, ttl) ? record : undefined
531
+ } catch (error) {
532
+ return undefined
533
+ }
534
+ }
535
+
536
+ function isValidRecord(record, expectedPrefix, now, ttl) {
537
+ return (
538
+ !!record &&
539
+ VISITOR_ID_PATTERN.test(record.id) &&
540
+ (!expectedPrefix || record.id.charAt(0) === expectedPrefix) &&
541
+ typeof record.createdAt === 'number' &&
542
+ (record.revision === undefined ||
543
+ (typeof record.revision === 'number' &&
544
+ isFinite(record.revision) &&
545
+ record.revision >= 0 &&
546
+ Math.floor(record.revision) === record.revision)) &&
547
+ record.createdAt <= now &&
548
+ record.createdAt + ttl > now
549
+ )
550
+ }
551
+
552
+ function compareRecords(first, second) {
553
+ return first.createdAt - second.createdAt ||
554
+ (first.revision || 0) - (second.revision || 0)
555
+ }
556
+
557
+ function createIdentifierValue() {
558
+ try {
559
+ return createRandomHexIdentifier(16)
560
+ } catch (error) {
561
+ return UUID().replace(/-/g, '')
562
+ }
563
+ }
564
+
565
+ function createVisitorIdStub() {
566
+ return {
567
+ getId: noop,
568
+ reset: noop,
569
+ stop: noop
570
+ }
571
+ }
package/src/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  import { datafluxRum } from './boot/rum.entry'
2
2
  export { datafluxRum }
3
+ export { TraceType } from '@cloudcare/browser-core'
@@ -1,6 +1,8 @@
1
1
  import {
2
2
  createIdentityEncoder,
3
+ createHttpRequest,
3
4
  LifeCycleEventType,
5
+ Observable,
4
6
  RumEventType,
5
7
  startBatchWithReplica
6
8
  } from '@cloudcare/browser-core'
@@ -15,10 +17,21 @@ export function startRumBatch(
15
17
  createEncoder
16
18
  ) {
17
19
  const rumEncoder = createEncoder(EncoderStreamId.RUM)
20
+ // Both batches share the same retry queue and bandwidth limits.
21
+ const request = createHttpRequest(
22
+ configuration.rumEndpoint,
23
+ configuration.batchBytesLimit,
24
+ configuration.retryMaxSize,
25
+ reportError
26
+ )
27
+ const flushRequestObservable = new Observable()
28
+ let initialViewBatch
29
+ let initialViewEncoder
18
30
  const batch = startBatchWithReplica(
19
31
  configuration,
20
32
  {
21
33
  endpoint: configuration.rumEndpoint,
34
+ request,
22
35
  encoder: rumEncoder,
23
36
  encoderFallback: rumEncoder.isAsync
24
37
  ? createIdentityEncoder
@@ -28,7 +41,7 @@ export function startRumBatch(
28
41
  pageExitObservable,
29
42
  sessionExpireObservable
30
43
  )
31
- lifeCycle.subscribe(
44
+ const rumEventSubscription = lifeCycle.subscribe(
32
45
  LifeCycleEventType.RUM_EVENT_COLLECTED,
33
46
  function (serverRumEvent) {
34
47
  if (serverRumEvent.type === RumEventType.VIEW) {
@@ -38,8 +51,53 @@ export function startRumBatch(
38
51
  }
39
52
  }
40
53
  )
41
- telemetryEventObservable.subscribe(function (event) {
54
+ const initialViewSubscription = lifeCycle.subscribe(
55
+ LifeCycleEventType.RUM_VIEW_FIRST_COLLECTED,
56
+ function (event) {
57
+ if (!initialViewBatch) {
58
+ initialViewEncoder = createEncoder(EncoderStreamId.RUM_INITIAL_VIEW)
59
+ initialViewBatch = startBatchWithReplica(
60
+ configuration,
61
+ {
62
+ request,
63
+ encoder: initialViewEncoder,
64
+ encoderFallback: initialViewEncoder.isAsync
65
+ ? createIdentityEncoder
66
+ : undefined,
67
+ flushRequestObservable
68
+ },
69
+ reportError,
70
+ // The regular batch already owns the exit copy. Do not promote an
71
+ // older first version from this encoder's journal on the same exit.
72
+ new Observable(),
73
+ sessionExpireObservable
74
+ )
75
+ }
76
+ // Send the first eligible version separately. The normal batch retains
77
+ // each View's latest version for its original deadline and exit beacon,
78
+ // including rapid routes whose first fetches have not completed yet.
79
+ initialViewBatch.upsert(event, event.view.id)
80
+ flushRequestObservable.notify('view_created')
81
+ }
82
+ )
83
+ const telemetrySubscription = telemetryEventObservable.subscribe(function (event) {
42
84
  batch.add(event)
43
85
  })
44
- return batch
86
+ return {
87
+ flushObservable: batch.flushObservable,
88
+ add: batch.add,
89
+ upsert: batch.upsert,
90
+ stop: function () {
91
+ rumEventSubscription.unsubscribe()
92
+ initialViewSubscription.unsubscribe()
93
+ telemetrySubscription.unsubscribe()
94
+ batch.stop()
95
+ if (initialViewBatch) {
96
+ initialViewBatch.stop()
97
+ if (initialViewEncoder.stop) {
98
+ initialViewEncoder.stop()
99
+ }
100
+ }
101
+ }
102
+ }
45
103
  }