@cloudcare/browser-rum 3.3.6 → 3.3.8

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 (363) hide show
  1. package/README.md +24 -3
  2. package/README.zh.md +19 -3
  3. package/bundle/dataflux-rum.js +1 -1
  4. package/cjs/boot/buildEnv.js +1 -1
  5. package/cjs/boot/buildEnv.js.map +1 -1
  6. package/cjs/boot/perStartRum.js.map +1 -1
  7. package/cjs/boot/recorderApi.js +170 -200
  8. package/cjs/boot/recorderApi.js.map +1 -1
  9. package/cjs/boot/recorderApiStub.js +3 -29
  10. package/cjs/boot/recorderApiStub.js.map +1 -1
  11. package/cjs/boot/rum.entry.js.map +1 -1
  12. package/cjs/boot/rum.js.map +1 -1
  13. package/cjs/boot/rum.slim.entry.js.map +1 -1
  14. package/cjs/boot/rumEntryFactory.js.map +1 -1
  15. package/cjs/boot/rumPublicApi.js.map +1 -1
  16. package/cjs/boot/rumRecorderApiStub.js.map +1 -1
  17. package/cjs/boot/rumSlimConfiguration.js.map +1 -1
  18. package/cjs/boot/sessionReplayPublicApi.js +14 -27
  19. package/cjs/boot/sessionReplayPublicApi.js.map +1 -1
  20. package/cjs/boot/startRecording.js +333 -108
  21. package/cjs/boot/startRecording.js.map +1 -1
  22. package/cjs/constants.js.map +1 -1
  23. package/cjs/domain/assembly.js +1 -7
  24. package/cjs/domain/assembly.js.map +1 -1
  25. package/cjs/domain/configuration.js +31 -43
  26. package/cjs/domain/configuration.js.map +1 -1
  27. package/cjs/domain/contexts/commonContext.js.map +1 -1
  28. package/cjs/domain/contexts/displayContext.js.map +1 -1
  29. package/cjs/domain/contexts/foregroundContexts.js.map +1 -1
  30. package/cjs/domain/contexts/internalContext.js.map +1 -1
  31. package/cjs/domain/contexts/pageStateHistory.js.map +1 -1
  32. package/cjs/domain/contexts/urlContexts.js +10 -1
  33. package/cjs/domain/contexts/urlContexts.js.map +1 -1
  34. package/cjs/domain/contexts/viewContexts.js +1 -0
  35. package/cjs/domain/contexts/viewContexts.js.map +1 -1
  36. package/cjs/domain/deflate/deflateEncoder.js +517 -39
  37. package/cjs/domain/deflate/deflateEncoder.js.map +1 -1
  38. package/cjs/domain/deflate/deflateWorker.js +194 -115
  39. package/cjs/domain/deflate/deflateWorker.js.map +1 -1
  40. package/cjs/domain/deflate/index.js.map +1 -1
  41. package/cjs/domain/domMutationObservable.js.map +1 -1
  42. package/cjs/domain/encoderStreamId.js.map +1 -1
  43. package/cjs/domain/firstInputPolyfill.js.map +1 -1
  44. package/cjs/domain/initViewportObservable.js.map +1 -1
  45. package/cjs/domain/locationChangeObservable.js.map +1 -1
  46. package/cjs/domain/performanceObservable.js.map +1 -1
  47. package/cjs/domain/performanceUtils.js.map +1 -1
  48. package/cjs/domain/plugins.js.map +1 -1
  49. package/cjs/domain/replay/record/canvasAutoSnapshot.js.map +1 -1
  50. package/cjs/domain/replay/record/canvasCommandCapture.js +968 -167
  51. package/cjs/domain/replay/record/canvasCommandCapture.js.map +1 -1
  52. package/cjs/domain/replay/record/canvasCommandObserver.js +1058 -119
  53. package/cjs/domain/replay/record/canvasCommandObserver.js.map +1 -1
  54. package/cjs/domain/replay/record/canvasCommandSerializeArgs.js +61 -37
  55. package/cjs/domain/replay/record/canvasCommandSerializeArgs.js.map +1 -1
  56. package/cjs/domain/replay/record/canvasContext.js +63 -0
  57. package/cjs/domain/replay/record/canvasContext.js.map +1 -0
  58. package/cjs/domain/replay/record/canvasContinuousScheduler.js +246 -118
  59. package/cjs/domain/replay/record/canvasContinuousScheduler.js.map +1 -1
  60. package/cjs/domain/replay/record/canvasEncodeBridge.js +539 -87
  61. package/cjs/domain/replay/record/canvasEncodeBridge.js.map +1 -1
  62. package/cjs/domain/replay/record/canvasEncodeWorker.js +50 -32
  63. package/cjs/domain/replay/record/canvasEncodeWorker.js.map +1 -1
  64. package/cjs/domain/replay/record/canvasFrameSignature.js +49 -17
  65. package/cjs/domain/replay/record/canvasFrameSignature.js.map +1 -1
  66. package/cjs/domain/replay/record/canvasMutationRecord.js.map +1 -1
  67. package/cjs/domain/replay/record/canvasObserver.js +295 -59
  68. package/cjs/domain/replay/record/canvasObserver.js.map +1 -1
  69. package/cjs/domain/replay/record/canvasSerializeArgs.js.map +1 -1
  70. package/cjs/domain/replay/record/canvasWebGLPluginHost.js +33 -0
  71. package/cjs/domain/replay/record/canvasWebGLPluginHost.js.map +1 -0
  72. package/cjs/domain/replay/record/elementsScrollPositions.js +3 -0
  73. package/cjs/domain/replay/record/elementsScrollPositions.js.map +1 -1
  74. package/cjs/domain/replay/record/index.js.map +1 -1
  75. package/cjs/domain/replay/record/mutationBatch.js +542 -25
  76. package/cjs/domain/replay/record/mutationBatch.js.map +1 -1
  77. package/cjs/domain/replay/record/mutationObserver.js +1900 -191
  78. package/cjs/domain/replay/record/mutationObserver.js.map +1 -1
  79. package/cjs/domain/replay/record/mutationResourceBudget.js +144 -0
  80. package/cjs/domain/replay/record/mutationResourceBudget.js.map +1 -0
  81. package/cjs/domain/replay/record/observers.js +222 -53
  82. package/cjs/domain/replay/record/observers.js.map +1 -1
  83. package/cjs/domain/replay/record/privacy.js +31 -8
  84. package/cjs/domain/replay/record/privacy.js.map +1 -1
  85. package/cjs/domain/replay/record/record.js +3083 -321
  86. package/cjs/domain/replay/record/record.js.map +1 -1
  87. package/cjs/domain/replay/record/serializationUtils.js +426 -26
  88. package/cjs/domain/replay/record/serializationUtils.js.map +1 -1
  89. package/cjs/domain/replay/record/serialize.js +259 -49
  90. package/cjs/domain/replay/record/serialize.js.map +1 -1
  91. package/cjs/domain/replay/record/shadowRootsController.js +875 -21
  92. package/cjs/domain/replay/record/shadowRootsController.js.map +1 -1
  93. package/cjs/domain/replay/record/utils.js.map +1 -1
  94. package/cjs/domain/replay/record/viewports.js.map +1 -1
  95. package/cjs/domain/replay/replayStats.js.map +1 -1
  96. package/cjs/domain/replay/segmentCollection/buildReplayPayload.js.map +1 -1
  97. package/cjs/domain/replay/segmentCollection/index.js.map +1 -1
  98. package/cjs/domain/replay/segmentCollection/segment.js +315 -11
  99. package/cjs/domain/replay/segmentCollection/segment.js.map +1 -1
  100. package/cjs/domain/replay/segmentCollection/segmentCollection.js +956 -71
  101. package/cjs/domain/replay/segmentCollection/segmentCollection.js.map +1 -1
  102. package/cjs/domain/replay/startRecordBridge.js.map +1 -1
  103. package/cjs/domain/requestCollection.js.map +1 -1
  104. package/cjs/domain/rumEventsCollection/actions/actionCollection.js.map +1 -1
  105. package/cjs/domain/rumEventsCollection/actions/clickChain.js.map +1 -1
  106. package/cjs/domain/rumEventsCollection/actions/computeFrustration.js.map +1 -1
  107. package/cjs/domain/rumEventsCollection/actions/getActionNameFromElement.js.map +1 -1
  108. package/cjs/domain/rumEventsCollection/actions/getSelectorsFromElement.js.map +1 -1
  109. package/cjs/domain/rumEventsCollection/actions/interactionSelectorCache.js.map +1 -1
  110. package/cjs/domain/rumEventsCollection/actions/listenActionEvents.js.map +1 -1
  111. package/cjs/domain/rumEventsCollection/actions/trackClickActions.js.map +1 -1
  112. package/cjs/domain/rumEventsCollection/error/errorCollection.js.map +1 -1
  113. package/cjs/domain/rumEventsCollection/error/trackConsoleError.js.map +1 -1
  114. package/cjs/domain/rumEventsCollection/error/trackReportError.js.map +1 -1
  115. package/cjs/domain/rumEventsCollection/longTask/longAnimationFrameCollection.js.map +1 -1
  116. package/cjs/domain/rumEventsCollection/longTask/longTaskCollection.js.map +1 -1
  117. package/cjs/domain/rumEventsCollection/resource/matchRequestResourceEntry.js.map +1 -1
  118. package/cjs/domain/rumEventsCollection/resource/resourceCollection.js +1 -0
  119. package/cjs/domain/rumEventsCollection/resource/resourceCollection.js.map +1 -1
  120. package/cjs/domain/rumEventsCollection/resource/resourceTrackerManager.js.map +1 -1
  121. package/cjs/domain/rumEventsCollection/resource/resourceUtils.js.map +1 -1
  122. package/cjs/domain/rumEventsCollection/resource/retrieveInitialDocumentResourceTiming.js.map +1 -1
  123. package/cjs/domain/rumEventsCollection/resource/webSocketCollection.js +1 -0
  124. package/cjs/domain/rumEventsCollection/resource/webSocketCollection.js.map +1 -1
  125. package/cjs/domain/rumEventsCollection/view/interactionCountPolyfill.js.map +1 -1
  126. package/cjs/domain/rumEventsCollection/view/trackCommonViewMetrics.js.map +1 -1
  127. package/cjs/domain/rumEventsCollection/view/trackCumulativeLayoutShift.js.map +1 -1
  128. package/cjs/domain/rumEventsCollection/view/trackFirstContentfulPaint.js.map +1 -1
  129. package/cjs/domain/rumEventsCollection/view/trackFirstHidden.js.map +1 -1
  130. package/cjs/domain/rumEventsCollection/view/trackFirstInput.js.map +1 -1
  131. package/cjs/domain/rumEventsCollection/view/trackInitialViewTimings.js.map +1 -1
  132. package/cjs/domain/rumEventsCollection/view/trackInteractionToNextPaint.js.map +1 -1
  133. package/cjs/domain/rumEventsCollection/view/trackLargestContentfulPaint.js.map +1 -1
  134. package/cjs/domain/rumEventsCollection/view/trackLoadingTime.js.map +1 -1
  135. package/cjs/domain/rumEventsCollection/view/trackNavigationTimings.js.map +1 -1
  136. package/cjs/domain/rumEventsCollection/view/trackScrollMetrics.js.map +1 -1
  137. package/cjs/domain/rumEventsCollection/view/trackViewEventCounts.js.map +1 -1
  138. package/cjs/domain/rumEventsCollection/view/trackViews.js +29 -11
  139. package/cjs/domain/rumEventsCollection/view/trackViews.js.map +1 -1
  140. package/cjs/domain/rumEventsCollection/view/viewCollection.js.map +1 -1
  141. package/cjs/domain/rumSessionManager.js.map +1 -1
  142. package/cjs/domain/tracing/ddtraceTracer.js.map +1 -1
  143. package/cjs/domain/tracing/getDocumentTraceId.js.map +1 -1
  144. package/cjs/domain/tracing/jaegerTracer.js.map +1 -1
  145. package/cjs/domain/tracing/sampler.js.map +1 -1
  146. package/cjs/domain/tracing/skywalkingTracer.js.map +1 -1
  147. package/cjs/domain/tracing/traceIdentifier.js.map +1 -1
  148. package/cjs/domain/tracing/tracer.js +2 -2
  149. package/cjs/domain/tracing/tracer.js.map +1 -1
  150. package/cjs/domain/tracing/w3cTraceParentTracer.js.map +1 -1
  151. package/cjs/domain/tracing/zipkinMultiTracer.js.map +1 -1
  152. package/cjs/domain/tracing/zipkinSingleTracer.js.map +1 -1
  153. package/cjs/domain/trackEventCounts.js.map +1 -1
  154. package/cjs/domain/usr/index.js.map +1 -1
  155. package/cjs/domain/waitPageActivityEnd.js.map +1 -1
  156. package/cjs/index.js.map +1 -1
  157. package/cjs/transport/startRumBatch.js +3 -1
  158. package/cjs/transport/startRumBatch.js.map +1 -1
  159. package/cjs/transport/startRumEventBridge.js.map +1 -1
  160. package/cjs/types/index.js.map +1 -1
  161. package/cjs/types/sessionReplayConstants.js.map +1 -1
  162. package/esm/boot/buildEnv.js +1 -1
  163. package/esm/boot/buildEnv.js.map +1 -1
  164. package/esm/boot/perStartRum.js.map +1 -1
  165. package/esm/boot/recorderApi.js +172 -202
  166. package/esm/boot/recorderApi.js.map +1 -1
  167. package/esm/boot/recorderApiStub.js +3 -29
  168. package/esm/boot/recorderApiStub.js.map +1 -1
  169. package/esm/boot/rum.entry.js.map +1 -1
  170. package/esm/boot/rum.js.map +1 -1
  171. package/esm/boot/rum.slim.entry.js.map +1 -1
  172. package/esm/boot/rumEntryFactory.js.map +1 -1
  173. package/esm/boot/rumPublicApi.js.map +1 -1
  174. package/esm/boot/rumRecorderApiStub.js.map +1 -1
  175. package/esm/boot/rumSlimConfiguration.js.map +1 -1
  176. package/esm/boot/sessionReplayPublicApi.js +14 -27
  177. package/esm/boot/sessionReplayPublicApi.js.map +1 -1
  178. package/esm/boot/startRecording.js +334 -109
  179. package/esm/boot/startRecording.js.map +1 -1
  180. package/esm/constants.js.map +1 -1
  181. package/esm/domain/assembly.js +1 -7
  182. package/esm/domain/assembly.js.map +1 -1
  183. package/esm/domain/configuration.js +31 -43
  184. package/esm/domain/configuration.js.map +1 -1
  185. package/esm/domain/contexts/commonContext.js.map +1 -1
  186. package/esm/domain/contexts/displayContext.js.map +1 -1
  187. package/esm/domain/contexts/foregroundContexts.js.map +1 -1
  188. package/esm/domain/contexts/internalContext.js.map +1 -1
  189. package/esm/domain/contexts/pageStateHistory.js.map +1 -1
  190. package/esm/domain/contexts/urlContexts.js +11 -2
  191. package/esm/domain/contexts/urlContexts.js.map +1 -1
  192. package/esm/domain/contexts/viewContexts.js +2 -1
  193. package/esm/domain/contexts/viewContexts.js.map +1 -1
  194. package/esm/domain/deflate/deflateEncoder.js +517 -39
  195. package/esm/domain/deflate/deflateEncoder.js.map +1 -1
  196. package/esm/domain/deflate/deflateWorker.js +193 -116
  197. package/esm/domain/deflate/deflateWorker.js.map +1 -1
  198. package/esm/domain/deflate/index.js.map +1 -1
  199. package/esm/domain/domMutationObservable.js.map +1 -1
  200. package/esm/domain/encoderStreamId.js.map +1 -1
  201. package/esm/domain/firstInputPolyfill.js.map +1 -1
  202. package/esm/domain/initViewportObservable.js.map +1 -1
  203. package/esm/domain/locationChangeObservable.js.map +1 -1
  204. package/esm/domain/performanceObservable.js.map +1 -1
  205. package/esm/domain/performanceUtils.js.map +1 -1
  206. package/esm/domain/plugins.js.map +1 -1
  207. package/esm/domain/replay/record/canvasAutoSnapshot.js.map +1 -1
  208. package/esm/domain/replay/record/canvasCommandCapture.js +968 -168
  209. package/esm/domain/replay/record/canvasCommandCapture.js.map +1 -1
  210. package/esm/domain/replay/record/canvasCommandObserver.js +1058 -119
  211. package/esm/domain/replay/record/canvasCommandObserver.js.map +1 -1
  212. package/esm/domain/replay/record/canvasCommandSerializeArgs.js +60 -37
  213. package/esm/domain/replay/record/canvasCommandSerializeArgs.js.map +1 -1
  214. package/esm/domain/replay/record/canvasContext.js +50 -0
  215. package/esm/domain/replay/record/canvasContext.js.map +1 -0
  216. package/esm/domain/replay/record/canvasContinuousScheduler.js +246 -118
  217. package/esm/domain/replay/record/canvasContinuousScheduler.js.map +1 -1
  218. package/esm/domain/replay/record/canvasEncodeBridge.js +539 -87
  219. package/esm/domain/replay/record/canvasEncodeBridge.js.map +1 -1
  220. package/esm/domain/replay/record/canvasEncodeWorker.js +51 -33
  221. package/esm/domain/replay/record/canvasEncodeWorker.js.map +1 -1
  222. package/esm/domain/replay/record/canvasFrameSignature.js +50 -17
  223. package/esm/domain/replay/record/canvasFrameSignature.js.map +1 -1
  224. package/esm/domain/replay/record/canvasMutationRecord.js.map +1 -1
  225. package/esm/domain/replay/record/canvasObserver.js +295 -59
  226. package/esm/domain/replay/record/canvasObserver.js.map +1 -1
  227. package/esm/domain/replay/record/canvasSerializeArgs.js.map +1 -1
  228. package/esm/domain/replay/record/canvasWebGLPluginHost.js +26 -0
  229. package/esm/domain/replay/record/canvasWebGLPluginHost.js.map +1 -0
  230. package/esm/domain/replay/record/elementsScrollPositions.js +3 -0
  231. package/esm/domain/replay/record/elementsScrollPositions.js.map +1 -1
  232. package/esm/domain/replay/record/index.js.map +1 -1
  233. package/esm/domain/replay/record/mutationBatch.js +541 -25
  234. package/esm/domain/replay/record/mutationBatch.js.map +1 -1
  235. package/esm/domain/replay/record/mutationObserver.js +1892 -195
  236. package/esm/domain/replay/record/mutationObserver.js.map +1 -1
  237. package/esm/domain/replay/record/mutationResourceBudget.js +137 -0
  238. package/esm/domain/replay/record/mutationResourceBudget.js.map +1 -0
  239. package/esm/domain/replay/record/observers.js +224 -55
  240. package/esm/domain/replay/record/observers.js.map +1 -1
  241. package/esm/domain/replay/record/privacy.js +30 -7
  242. package/esm/domain/replay/record/privacy.js.map +1 -1
  243. package/esm/domain/replay/record/record.js +3086 -325
  244. package/esm/domain/replay/record/record.js.map +1 -1
  245. package/esm/domain/replay/record/serializationUtils.js +422 -25
  246. package/esm/domain/replay/record/serializationUtils.js.map +1 -1
  247. package/esm/domain/replay/record/serialize.js +258 -50
  248. package/esm/domain/replay/record/serialize.js.map +1 -1
  249. package/esm/domain/replay/record/shadowRootsController.js +875 -21
  250. package/esm/domain/replay/record/shadowRootsController.js.map +1 -1
  251. package/esm/domain/replay/record/utils.js.map +1 -1
  252. package/esm/domain/replay/record/viewports.js.map +1 -1
  253. package/esm/domain/replay/replayStats.js.map +1 -1
  254. package/esm/domain/replay/segmentCollection/buildReplayPayload.js.map +1 -1
  255. package/esm/domain/replay/segmentCollection/index.js.map +1 -1
  256. package/esm/domain/replay/segmentCollection/segment.js +315 -10
  257. package/esm/domain/replay/segmentCollection/segment.js.map +1 -1
  258. package/esm/domain/replay/segmentCollection/segmentCollection.js +957 -72
  259. package/esm/domain/replay/segmentCollection/segmentCollection.js.map +1 -1
  260. package/esm/domain/replay/startRecordBridge.js.map +1 -1
  261. package/esm/domain/requestCollection.js.map +1 -1
  262. package/esm/domain/rumEventsCollection/actions/actionCollection.js.map +1 -1
  263. package/esm/domain/rumEventsCollection/actions/clickChain.js.map +1 -1
  264. package/esm/domain/rumEventsCollection/actions/computeFrustration.js.map +1 -1
  265. package/esm/domain/rumEventsCollection/actions/getActionNameFromElement.js.map +1 -1
  266. package/esm/domain/rumEventsCollection/actions/getSelectorsFromElement.js.map +1 -1
  267. package/esm/domain/rumEventsCollection/actions/interactionSelectorCache.js.map +1 -1
  268. package/esm/domain/rumEventsCollection/actions/listenActionEvents.js.map +1 -1
  269. package/esm/domain/rumEventsCollection/actions/trackClickActions.js.map +1 -1
  270. package/esm/domain/rumEventsCollection/error/errorCollection.js.map +1 -1
  271. package/esm/domain/rumEventsCollection/error/trackConsoleError.js.map +1 -1
  272. package/esm/domain/rumEventsCollection/error/trackReportError.js.map +1 -1
  273. package/esm/domain/rumEventsCollection/longTask/longAnimationFrameCollection.js.map +1 -1
  274. package/esm/domain/rumEventsCollection/longTask/longTaskCollection.js.map +1 -1
  275. package/esm/domain/rumEventsCollection/resource/matchRequestResourceEntry.js.map +1 -1
  276. package/esm/domain/rumEventsCollection/resource/resourceCollection.js +1 -0
  277. package/esm/domain/rumEventsCollection/resource/resourceCollection.js.map +1 -1
  278. package/esm/domain/rumEventsCollection/resource/resourceTrackerManager.js.map +1 -1
  279. package/esm/domain/rumEventsCollection/resource/resourceUtils.js.map +1 -1
  280. package/esm/domain/rumEventsCollection/resource/retrieveInitialDocumentResourceTiming.js.map +1 -1
  281. package/esm/domain/rumEventsCollection/resource/webSocketCollection.js +1 -0
  282. package/esm/domain/rumEventsCollection/resource/webSocketCollection.js.map +1 -1
  283. package/esm/domain/rumEventsCollection/view/interactionCountPolyfill.js.map +1 -1
  284. package/esm/domain/rumEventsCollection/view/trackCommonViewMetrics.js.map +1 -1
  285. package/esm/domain/rumEventsCollection/view/trackCumulativeLayoutShift.js.map +1 -1
  286. package/esm/domain/rumEventsCollection/view/trackFirstContentfulPaint.js.map +1 -1
  287. package/esm/domain/rumEventsCollection/view/trackFirstHidden.js.map +1 -1
  288. package/esm/domain/rumEventsCollection/view/trackFirstInput.js.map +1 -1
  289. package/esm/domain/rumEventsCollection/view/trackInitialViewTimings.js.map +1 -1
  290. package/esm/domain/rumEventsCollection/view/trackInteractionToNextPaint.js.map +1 -1
  291. package/esm/domain/rumEventsCollection/view/trackLargestContentfulPaint.js.map +1 -1
  292. package/esm/domain/rumEventsCollection/view/trackLoadingTime.js.map +1 -1
  293. package/esm/domain/rumEventsCollection/view/trackNavigationTimings.js.map +1 -1
  294. package/esm/domain/rumEventsCollection/view/trackScrollMetrics.js.map +1 -1
  295. package/esm/domain/rumEventsCollection/view/trackViewEventCounts.js.map +1 -1
  296. package/esm/domain/rumEventsCollection/view/trackViews.js +30 -12
  297. package/esm/domain/rumEventsCollection/view/trackViews.js.map +1 -1
  298. package/esm/domain/rumEventsCollection/view/viewCollection.js.map +1 -1
  299. package/esm/domain/rumSessionManager.js.map +1 -1
  300. package/esm/domain/tracing/ddtraceTracer.js.map +1 -1
  301. package/esm/domain/tracing/getDocumentTraceId.js.map +1 -1
  302. package/esm/domain/tracing/jaegerTracer.js.map +1 -1
  303. package/esm/domain/tracing/sampler.js.map +1 -1
  304. package/esm/domain/tracing/skywalkingTracer.js.map +1 -1
  305. package/esm/domain/tracing/traceIdentifier.js.map +1 -1
  306. package/esm/domain/tracing/tracer.js +2 -2
  307. package/esm/domain/tracing/tracer.js.map +1 -1
  308. package/esm/domain/tracing/w3cTraceParentTracer.js.map +1 -1
  309. package/esm/domain/tracing/zipkinMultiTracer.js.map +1 -1
  310. package/esm/domain/tracing/zipkinSingleTracer.js.map +1 -1
  311. package/esm/domain/trackEventCounts.js.map +1 -1
  312. package/esm/domain/usr/index.js.map +1 -1
  313. package/esm/domain/waitPageActivityEnd.js.map +1 -1
  314. package/esm/index.js.map +1 -1
  315. package/esm/transport/startRumBatch.js +4 -2
  316. package/esm/transport/startRumBatch.js.map +1 -1
  317. package/esm/transport/startRumEventBridge.js.map +1 -1
  318. package/esm/types/index.js.map +1 -1
  319. package/esm/types/sessionReplayConstants.js.map +1 -1
  320. package/package.json +12 -7
  321. package/src/boot/recorderApi.js +247 -220
  322. package/src/boot/recorderApiStub.js +3 -29
  323. package/src/boot/sessionReplayPublicApi.js +15 -28
  324. package/src/boot/startRecording.js +429 -146
  325. package/src/domain/assembly.js +5 -4
  326. package/src/domain/configuration.js +63 -100
  327. package/src/domain/contexts/urlContexts.js +16 -4
  328. package/src/domain/contexts/viewContexts.js +3 -1
  329. package/src/domain/deflate/deflateEncoder.js +699 -43
  330. package/src/domain/deflate/deflateWorker.js +237 -136
  331. package/src/domain/replay/record/canvasCommandCapture.js +1374 -180
  332. package/src/domain/replay/record/canvasCommandObserver.js +1585 -150
  333. package/src/domain/replay/record/canvasCommandSerializeArgs.js +79 -42
  334. package/src/domain/replay/record/canvasContext.js +67 -0
  335. package/src/domain/replay/record/canvasContinuousScheduler.js +379 -143
  336. package/src/domain/replay/record/canvasEncodeBridge.js +691 -106
  337. package/src/domain/replay/record/canvasEncodeWorker.js +67 -43
  338. package/src/domain/replay/record/canvasFrameSignature.js +58 -24
  339. package/src/domain/replay/record/canvasObserver.js +461 -89
  340. package/src/domain/replay/record/canvasWebGLPluginHost.js +43 -0
  341. package/src/domain/replay/record/elementsScrollPositions.js +3 -0
  342. package/src/domain/replay/record/mutationBatch.js +761 -27
  343. package/src/domain/replay/record/mutationObserver.js +2992 -261
  344. package/src/domain/replay/record/mutationResourceBudget.js +191 -0
  345. package/src/domain/replay/record/observers.js +367 -97
  346. package/src/domain/replay/record/privacy.js +34 -12
  347. package/src/domain/replay/record/record.js +4284 -413
  348. package/src/domain/replay/record/serializationUtils.js +587 -28
  349. package/src/domain/replay/record/serialize.js +432 -66
  350. package/src/domain/replay/record/shadowRootsController.js +1108 -30
  351. package/src/domain/replay/segmentCollection/segment.js +441 -11
  352. package/src/domain/replay/segmentCollection/segmentCollection.js +1300 -77
  353. package/src/domain/rumEventsCollection/resource/resourceCollection.js +1 -0
  354. package/src/domain/rumEventsCollection/resource/webSocketCollection.js +1 -0
  355. package/src/domain/rumEventsCollection/view/trackViews.js +36 -12
  356. package/src/domain/tracing/tracer.js +4 -5
  357. package/src/transport/startRumBatch.js +6 -1
  358. package/types/index.d.ts +15 -2
  359. package/cjs/domain/replay/record/canvasReplayFixtures.js +0 -105
  360. package/cjs/domain/replay/record/canvasReplayFixtures.js.map +0 -1
  361. package/esm/domain/replay/record/canvasReplayFixtures.js +0 -96
  362. package/esm/domain/replay/record/canvasReplayFixtures.js.map +0 -1
  363. package/src/domain/replay/record/canvasReplayFixtures.js +0 -113
@@ -2,12 +2,21 @@ import {
2
2
  timeStampNow,
3
3
  getScrollX,
4
4
  getScrollY,
5
- assign
5
+ assign,
6
+ addTelemetryDebug,
7
+ getParentNode
6
8
  } from '@cloudcare/browser-core'
7
9
  import { getViewportDimension } from '../../initViewportObservable'
8
10
 
9
11
  import { RecordType, IncrementalSource } from '../../../types'
10
- import { serializeDocument, SerializationContextStatus } from './serialize'
12
+ import { NodePrivacyLevel } from '../../../constants'
13
+ import {
14
+ createMutationSerializerTask,
15
+ SerializationContextStatus,
16
+ getSerializedNodeApproxBytes,
17
+ SERIALIZATION_MAX_NODE_COUNT,
18
+ SERIALIZATION_MAX_APPROX_BYTES,
19
+ } from './serialize'
11
20
  import { initObservers } from './observers'
12
21
 
13
22
  import { getVisualViewport } from './viewports'
@@ -15,16 +24,68 @@ import { assembleIncrementalSnapshot } from './utils'
15
24
  import { createElementsScrollPositions } from './elementsScrollPositions'
16
25
  import { initShadowRootsController } from './shadowRootsController'
17
26
  import { createCanvasObserver } from './canvasObserver'
27
+ import { createCanvasEncodeBridge } from './canvasEncodeBridge'
28
+ import { isWebGLReplayCanvas } from './canvasContext'
29
+ import {
30
+ createNoopObserver,
31
+ createSessionReplayWebGLRuntime
32
+ } from './canvasWebGLPluginHost'
18
33
  import { startCanvasCommandCapture } from './canvasCommandObserver'
19
34
  import {
20
35
  getSerializedCanvasNodes,
21
- getSerializedNodeId
36
+ getSerializedCanvasNodesSnapshot,
37
+ getSerializedNodeId,
38
+ startSerializedCanvasTracking,
39
+ MAX_SERIALIZED_NODE_ANCESTOR_DEPTH
22
40
  } from './serializationUtils'
41
+ import {
42
+ cancelMutationAddPublicationToken,
43
+ consumeMutationAddPublicationToken,
44
+ consumeMutationRemoveSourceNode,
45
+ createMutationAddPublicationToken,
46
+ getMutationAddPublicationToken,
47
+ getMutationRemoveSourceNode,
48
+ publishMutationAddPublicationToken,
49
+ registerMutationAddPublicationToken
50
+ } from './mutationObserver'
51
+ import { createMutationResourceBudget } from './mutationResourceBudget'
52
+ import { getNodePrivacyLevel } from './privacy'
23
53
  import { startContinuousCanvasSnapshotLoop } from './canvasContinuousScheduler'
24
54
 
25
55
  var MUTATION_EMIT_DELAY_MS = 16
26
56
  var MAX_MUTATION_EMIT_APPROX_BYTES = 200000
57
+ var MUTATION_ADMISSION_RETRY_DELAY_MS = 32
58
+ var MUTATION_ADMISSION_DRAIN_SLICE_MS = 4
59
+ var MUTATION_ADMISSION_DRAIN_SLICE_APPROX_BYTES = 256 * 1024
60
+ var MUTATION_SOURCE_BOUNDARY_FLUSH_BUDGET_MS = 12
61
+ var MAX_PENDING_MUTATION_ADMISSION_PAYLOADS = 512
62
+ var MAX_PENDING_MUTATION_ADMISSION_APPROX_BYTES = 32 * 1024 * 1024
63
+ var DYNAMIC_SHADOW_ROOT_SERIALIZATION_MAX_NODE_COUNT = 5000
64
+ var DYNAMIC_SHADOW_ROOT_SERIALIZATION_MAX_APPROX_BYTES =
65
+ MAX_MUTATION_EMIT_APPROX_BYTES - 1024
66
+ var INITIAL_FULL_SNAPSHOT_SERIALIZATION_SLICE_MS = 8
67
+ var FULL_SNAPSHOT_SERIALIZATION_SLICE_MS = 4
68
+ // The churn fallback runs without yielding so the baseline cannot mix DOM
69
+ // generations. Keep the whole transaction within one frame.
70
+ var FULL_SNAPSHOT_SYNCHRONOUS_FINALIZATION_BUDGET_MS = 12
71
+ // Initial snapshots may need several serializer watermarks, but the complete
72
+ // record must still fit below the segment layer's 4 MiB pending-raw budget.
73
+ var FULL_SNAPSHOT_SERIALIZATION_MAX_NODE_COUNT =
74
+ SERIALIZATION_MAX_NODE_COUNT * 4
75
+ var FULL_SNAPSHOT_SERIALIZATION_MAX_APPROX_BYTES =
76
+ SERIALIZATION_MAX_APPROX_BYTES * 4 - 64 * 1024
77
+ var FULL_SNAPSHOT_MAX_RESTART_COUNT = 3
78
+ var FULL_SNAPSHOT_MAX_TOTAL_DURATION_MS = 1000
79
+ var FULL_SNAPSHOT_MAX_WALL_DURATION_MS = 30000
80
+ var FULL_SNAPSHOT_MUTATION_QUIET_DELAY_MS = 250
81
+ export var MAX_FULL_SNAPSHOT_CANVAS_BASELINE_COUNT = 64
82
+ var FULL_SNAPSHOT_CANVAS_BASELINE_TOTAL_TIMEOUT_MS = 2000
83
+ var FULL_SNAPSHOT_CANVAS_BASELINE_ITEM_TIMEOUT_MS = 1000
27
84
  var CANVAS_DEBUG_HISTORY_LIMIT = 200
85
+ var DOM_MUTATION_DEBUG_HISTORY_LIMIT = 20
86
+ var DOM_MUTATION_DEBUG_SAMPLE_LIMIT = 5
87
+ export var MAX_DEFERRED_RECORDS = 100
88
+ export var MAX_DEFERRED_RECORD_APPROX_BYTES = 512 * 1024
28
89
 
29
90
  function shouldUseCommandCapture(configuration) {
30
91
  return (
@@ -42,383 +103,3537 @@ function shouldUseContinuousCanvasSnapshot(configuration) {
42
103
  )
43
104
  }
44
105
 
106
+ function isDomMutationRecord(record) {
107
+ return (
108
+ record &&
109
+ record.type === RecordType.IncrementalSnapshot &&
110
+ record.data &&
111
+ record.data.source === IncrementalSource.Mutation
112
+ )
113
+ }
114
+
115
+ function isStatefulDeferredRecord(record) {
116
+ return (
117
+ record &&
118
+ (record.type === RecordType.Focus ||
119
+ record.type === RecordType.VisualViewport ||
120
+ (record.type === RecordType.IncrementalSnapshot &&
121
+ record.data &&
122
+ (record.data.source === IncrementalSource.CanvasMutation ||
123
+ record.data.source === IncrementalSource.StyleSheetRule ||
124
+ record.data.source === IncrementalSource.Input ||
125
+ record.data.source === IncrementalSource.Scroll ||
126
+ record.data.source === IncrementalSource.MediaInteraction ||
127
+ record.data.source === IncrementalSource.ViewportResize)))
128
+ )
129
+ }
130
+
131
+ function reportWebGLReplayFailure(phase, error) {
132
+ addTelemetryDebug(phase, { error: String(error) })
133
+ }
134
+
45
135
  export function record(options) {
46
- var emit = options.emit
136
+ var rawEmit = options.emit
137
+ var rawEmitBaseline = options.$rEmitBaseline
47
138
  // runtime checks for user options
48
- if (!emit) {
139
+ if (!rawEmit) {
49
140
  throw new Error('emit function is required')
50
141
  }
142
+ var configuration = options.configuration
143
+ var initializationCleanupTasks = []
144
+ var recordStopping = false
145
+ var recordStopped = false
51
146
 
52
- var elementsScrollPositions = createElementsScrollPositions()
53
- var replayPerformanceStats = createReplayPerformanceStats()
54
- var pendingMutationPayload
55
- var pendingMutationTimeout
147
+ function registerInitializationCleanup(cleanupTask) {
148
+ if (typeof cleanupTask === 'function') {
149
+ initializationCleanupTasks.push(cleanupTask)
150
+ }
151
+ }
56
152
 
57
- var updateReplayPerformanceStats = function (delta) {
58
- accumulateReplayPerformanceStats(replayPerformanceStats, delta)
153
+ function abortRecorderInitialization(reason, initializationError) {
154
+ recordStopping = true
155
+ recordStopped = true
156
+ var firstCleanupError
157
+ initializationCleanupTasks
158
+ .slice()
159
+ .reverse()
160
+ .forEach(function (cleanupTask) {
161
+ try {
162
+ cleanupTask()
163
+ } catch (error) {
164
+ if (!firstCleanupError) {
165
+ firstCleanupError = error
166
+ }
167
+ }
168
+ })
169
+ initializationCleanupTasks = []
170
+ addTelemetryDebug('Session Replay recorder initialization failed.', {
171
+ reason: reason,
172
+ error: String(initializationError || firstCleanupError)
173
+ })
174
+ if (options.onFullSnapshotFailure) {
175
+ try {
176
+ options.onFullSnapshotFailure(reason)
177
+ } catch (error) {
178
+ addTelemetryDebug(
179
+ 'Session Replay recorder initialization failure callback failed.',
180
+ {
181
+ reason: reason,
182
+ error: String(error)
183
+ }
184
+ )
185
+ }
186
+ }
187
+ return createInactiveRecorder()
59
188
  }
60
189
 
61
- var mutationCb = function (mutation) {
190
+ var stopSerializedCanvasTracking
191
+ try {
192
+ stopSerializedCanvasTracking =
193
+ shouldUseCommandCapture(configuration) ||
194
+ shouldUseContinuousCanvasSnapshot(configuration)
195
+ ? startSerializedCanvasTracking()
196
+ : function () {}
197
+ } catch (error) {
198
+ return abortRecorderInitialization(
199
+ 'recorder_initialization_error',
200
+ error
201
+ )
202
+ }
203
+ registerInitializationCleanup(stopSerializedCanvasTracking)
204
+ var suppressRecordsUntilFullSnapshot = false
205
+ var deferredRecords = []
206
+ var deferredRecordsApproxBytes = 0
207
+ var previousReplayTreeRecords = []
208
+ var previousReplayTreeRecordsApproxBytes = 0
209
+ var previousReplayTreeLastRecordTimestamp
210
+ var previousReplayTreeAdmissionActive = false
211
+ var captureRecordsAgainstPreviousReplayTree = false
212
+ var deferredRecordAdmissionTimeout
213
+ var mutationAdmissionEmitInProgress = false
214
+ var mutationPublicationBarrier
215
+ var lastEmitWasLocallyBackpressured = false
216
+
217
+ function deferNonDomRecord(
218
+ record,
219
+ mutationAdmissionBarrier,
220
+ insertBeforeLaterBarrier
221
+ ) {
222
+ var recordApproxBytes = estimateJsonValueBytes(
223
+ record,
224
+ MAX_DEFERRED_RECORD_APPROX_BYTES
225
+ )
226
+ if (recordApproxBytes > MAX_DEFERRED_RECORD_APPROX_BYTES) {
227
+ handleDeferredRecordLoss(record)
228
+ return false
229
+ }
230
+ var evictedStatefulRecord
231
+ while (
232
+ deferredRecords.length &&
233
+ (deferredRecords.length >= MAX_DEFERRED_RECORDS ||
234
+ deferredRecordsApproxBytes + recordApproxBytes >
235
+ MAX_DEFERRED_RECORD_APPROX_BYTES)
236
+ ) {
237
+ var removedEntry = deferredRecords.shift()
238
+ deferredRecordsApproxBytes -= removedEntry.$rApproxBytes
239
+ if (
240
+ !evictedStatefulRecord &&
241
+ isStatefulDeferredRecord(removedEntry.$rRecord)
242
+ ) {
243
+ evictedStatefulRecord = removedEntry.$rRecord
244
+ }
245
+ }
246
+ if (evictedStatefulRecord) {
247
+ handleDeferredRecordLoss(evictedStatefulRecord)
248
+ return false
249
+ }
250
+ if (mutationAdmissionBarrier) {
251
+ // Once a non-DOM record observes this exact boundary, later pure adds
252
+ // must not be folded into it and move ahead of the observed state.
253
+ mutationAdmissionBarrier.$rReferencedByDeferredRecord = true
254
+ }
255
+ var deferredEntry = {
256
+ $rRecord: record,
257
+ $rApproxBytes: recordApproxBytes,
258
+ // Keep the exact structural boundary that was pending when this
259
+ // record was observed. The drain uses it to interleave input/CSSOM
260
+ // and other node-dependent state after its add, but before later DOM
261
+ // mutations.
262
+ $rMutationAdmissionBarrier: mutationAdmissionBarrier
263
+ }
264
+ if (insertBeforeLaterBarrier && mutationAdmissionBarrier) {
265
+ var insertionIndex = deferredRecords.length
266
+ for (
267
+ var deferredIndex = 0;
268
+ deferredIndex < deferredRecords.length;
269
+ deferredIndex += 1
270
+ ) {
271
+ var queuedBarrier =
272
+ deferredRecords[deferredIndex].$rMutationAdmissionBarrier
273
+ if (queuedBarrier && queuedBarrier !== mutationAdmissionBarrier) {
274
+ insertionIndex = deferredIndex
275
+ break
276
+ }
277
+ }
278
+ deferredRecords.splice(insertionIndex, 0, deferredEntry)
279
+ } else {
280
+ deferredRecords.push(deferredEntry)
281
+ }
282
+ deferredRecordsApproxBytes += recordApproxBytes
283
+ return true
284
+ }
285
+
286
+ function clearPreviousReplayTreeRecords() {
287
+ previousReplayTreeRecords = []
288
+ previousReplayTreeRecordsApproxBytes = 0
289
+ }
290
+
291
+ function resetPreviousReplayTreeRecords() {
292
+ clearPreviousReplayTreeRecords()
293
+ previousReplayTreeLastRecordTimestamp = undefined
294
+ }
295
+
296
+ function updatePendingFullSnapshotTimestampFromRecord(record) {
62
297
  if (
63
- pendingMutationPayload &&
64
- shouldFlushPendingMutationPayloadBeforeMerge(
65
- pendingMutationPayload,
66
- mutation
67
- )
298
+ !record ||
299
+ typeof record.timestamp !== 'number' ||
300
+ !isFinite(record.timestamp) ||
301
+ typeof pendingFullSnapshotTimestamp !== 'number' ||
302
+ record.timestamp <= pendingFullSnapshotTimestamp
68
303
  ) {
69
- flushPendingMutations()
304
+ return
70
305
  }
71
- pendingMutationPayload = mergeMutationPayloads(
72
- pendingMutationPayload,
73
- mutation
306
+ pendingFullSnapshotTimestamp = record.timestamp
307
+ previousReplayTreeLastRecordTimestamp = Math.max(
308
+ typeof previousReplayTreeLastRecordTimestamp === 'number'
309
+ ? previousReplayTreeLastRecordTimestamp
310
+ : 0,
311
+ record.timestamp
74
312
  )
75
- scheduleMutationEmit()
313
+ if (
314
+ pendingFullSnapshotBaselineRecords &&
315
+ isStatefulDeferredRecord(record)
316
+ ) {
317
+ // The replacement baseline belongs after every event admitted against
318
+ // the previous replay tree. Stateful changes also invalidate the
319
+ // serialized DOM/CSSOM state; stateless events only need fresh immutable
320
+ // baseline record wrappers, rebuilt immediately before admission.
321
+ pendingFullSnapshotRestartRequested = true
322
+ }
76
323
  }
77
- function scheduleMutationEmit() {
78
- if (pendingMutationTimeout) {
79
- return
324
+
325
+ function queuePreviousReplayTreeRecord(record) {
326
+ var recordApproxBytes = estimateJsonValueBytes(
327
+ record,
328
+ MAX_DEFERRED_RECORD_APPROX_BYTES
329
+ )
330
+ if (recordApproxBytes > MAX_DEFERRED_RECORD_APPROX_BYTES) {
331
+ if (isStatefulDeferredRecord(record)) {
332
+ pendingFullSnapshotCanBeDiscarded = false
333
+ pendingFullSnapshotRestartRequested = true
334
+ return true
335
+ }
336
+ return false
80
337
  }
81
- pendingMutationTimeout = setTimeout(function () {
82
- pendingMutationTimeout = undefined
83
- flushPendingMutations()
84
- }, MUTATION_EMIT_DELAY_MS)
338
+ while (
339
+ previousReplayTreeRecords.length &&
340
+ (previousReplayTreeRecords.length >= MAX_DEFERRED_RECORDS ||
341
+ previousReplayTreeRecordsApproxBytes + recordApproxBytes >
342
+ MAX_DEFERRED_RECORD_APPROX_BYTES)
343
+ ) {
344
+ var removedEntry = previousReplayTreeRecords.shift()
345
+ previousReplayTreeRecordsApproxBytes -= removedEntry.$rApproxBytes
346
+ if (isStatefulDeferredRecord(removedEntry.$rRecord)) {
347
+ // A state gap makes restoring the old tail unsafe. The candidate
348
+ // baseline must complete and supersede it.
349
+ pendingFullSnapshotCanBeDiscarded = false
350
+ pendingFullSnapshotRestartRequested = true
351
+ }
352
+ }
353
+ previousReplayTreeRecords.push({
354
+ $rRecord: record,
355
+ $rApproxBytes: recordApproxBytes
356
+ })
357
+ previousReplayTreeRecordsApproxBytes += recordApproxBytes
358
+ updatePendingFullSnapshotTimestampFromRecord(record)
359
+ return true
85
360
  }
86
- function flushPendingMutations() {
87
- if (pendingMutationTimeout) {
88
- clearTimeout(pendingMutationTimeout)
89
- pendingMutationTimeout = undefined
361
+
362
+ function emitAgainstPreviousReplayTree(record) {
363
+ if (previousReplayTreeRecords.length) {
364
+ return queuePreviousReplayTreeRecord(record)
90
365
  }
91
- if (!pendingMutationPayload) {
92
- return
366
+ if (rawEmit(record) !== false) {
367
+ updatePendingFullSnapshotTimestampFromRecord(record)
368
+ return true
93
369
  }
94
- var mutationPayloads = splitPendingMutationPayloadForEmit(
95
- pendingMutationPayload
96
- )
97
- pendingMutationPayload = undefined
98
- updateReplayPerformanceStats(
99
- mutationPayloads.reduce(
100
- function (stats, mutationPayload) {
101
- stats.mutationCallbackCount += 1
102
- stats.mutationRecordCount += countMutationPayloadRecords(
103
- mutationPayload
104
- )
105
- stats.mutationAddCount += mutationPayload.adds.length
106
- stats.mutationRemoveCount += mutationPayload.removes.length
107
- stats.mutationTextCount += mutationPayload.texts.length
108
- stats.mutationAttributeCount += mutationPayload.attributes.length
109
- return stats
110
- },
111
- {
112
- mutationCallbackCount: 0,
113
- mutationRecordCount: 0,
114
- mutationAddCount: 0,
115
- mutationRemoveCount: 0,
116
- mutationTextCount: 0,
117
- mutationAttributeCount: 0
370
+ if (wasLastEmitBackpressured()) {
371
+ return queuePreviousReplayTreeRecord(record)
372
+ }
373
+ if (isStatefulDeferredRecord(record)) {
374
+ pendingFullSnapshotCanBeDiscarded = false
375
+ pendingFullSnapshotRestartRequested = true
376
+ return true
377
+ }
378
+ return false
379
+ }
380
+
381
+ function drainPreviousReplayTreeRecords() {
382
+ while (previousReplayTreeRecords.length) {
383
+ var entry = previousReplayTreeRecords[0]
384
+ if (rawEmit(entry.$rRecord) !== false) {
385
+ previousReplayTreeRecords.shift()
386
+ previousReplayTreeRecordsApproxBytes -= entry.$rApproxBytes
387
+ continue
388
+ }
389
+ if (wasLastEmitBackpressured()) {
390
+ return false
391
+ }
392
+ previousReplayTreeRecords.shift()
393
+ previousReplayTreeRecordsApproxBytes -= entry.$rApproxBytes
394
+ if (isStatefulDeferredRecord(entry.$rRecord)) {
395
+ pendingFullSnapshotCanBeDiscarded = false
396
+ pendingFullSnapshotRestartRequested = true
397
+ }
398
+ }
399
+ return true
400
+ }
401
+
402
+ function restorePreviousReplayTreeRecords() {
403
+ var records = previousReplayTreeRecords
404
+ clearPreviousReplayTreeRecords()
405
+ records.forEach(function (entry) {
406
+ deferNonDomRecord(entry.$rRecord)
407
+ })
408
+ flushDeferredRecords()
409
+ }
410
+
411
+ var emit = function (record) {
412
+ lastEmitWasLocallyBackpressured = false
413
+ if (
414
+ suppressRecordsUntilFullSnapshot &&
415
+ previousReplayTreeAdmissionActive &&
416
+ !isDomMutationRecord(record)
417
+ ) {
418
+ return emitAgainstPreviousReplayTree(record)
419
+ }
420
+ if (
421
+ suppressRecordsUntilFullSnapshot &&
422
+ isDomMutationRecord(record)
423
+ ) {
424
+ // The mutation activity callback already invalidated this mixed-time
425
+ // candidate. Retire the serialized payload locally and let the rebuilt
426
+ // FullSnapshot absorb it; reporting a rejection here would incorrectly
427
+ // classify an intentional suppression as an admission gap.
428
+ return true
429
+ }
430
+ if (
431
+ !suppressRecordsUntilFullSnapshot &&
432
+ !mutationPublicationBarrier &&
433
+ (!deferredRecords.length ||
434
+ (mutationAdmissionEmitInProgress &&
435
+ deferredRecords[0].$rMutationAdmissionBarrier &&
436
+ deferredRecords[0].$rMutationAdmissionBarrier
437
+ .$rPendingAdmission)) &&
438
+ deferredRecordAdmissionTimeout === undefined &&
439
+ (mutationAdmissionEmitInProgress ||
440
+ !pendingMutationAdmissionQueue.length)
441
+ ) {
442
+ if (rawEmit(record) !== false) {
443
+ return true
444
+ }
445
+ if (isDomMutationRecord(record)) {
446
+ return false
447
+ }
448
+ if (wasLastEmitBackpressured()) {
449
+ var wasDeferred = deferNonDomRecord(record)
450
+ if (wasDeferred) {
451
+ // A direct segment rejection has no DOM dependency to trigger its
452
+ // retry. Keep the exact record object (and any encoder-side cached
453
+ // serialization keyed by it) on the shared deferred drain.
454
+ scheduleDeferredRecordAdmissionRetry()
118
455
  }
456
+ return wasDeferred
457
+ }
458
+ handleDeferredRecordLoss(record)
459
+ return false
460
+ } else if (
461
+ !suppressRecordsUntilFullSnapshot &&
462
+ isDomMutationRecord(record)
463
+ ) {
464
+ // DOM publication membership is committed only after the segment layer
465
+ // accepts the record. Keep it in the mutation admission queue while
466
+ // post-baseline deferred records drain, so it cannot overtake them.
467
+ lastEmitWasLocallyBackpressured = true
468
+ return false
469
+ } else if (!isDomMutationRecord(record)) {
470
+ var mutationAdmissionBarrier =
471
+ mutationPublicationBarrier ||
472
+ (!suppressRecordsUntilFullSnapshot &&
473
+ pendingMutationAdmissionQueue.length
474
+ ? pendingMutationAdmissionQueue[
475
+ pendingMutationAdmissionQueue.length - 1
476
+ ]
477
+ : undefined)
478
+ return deferNonDomRecord(
479
+ record,
480
+ mutationAdmissionBarrier,
481
+ Boolean(mutationPublicationBarrier)
119
482
  )
120
- )
121
- mutationPayloads.forEach(function (mutationPayload) {
122
- lastDomMutationForDebug = cloneDomMutationDebugResult(mutationPayload)
123
- pushCanvasDebugHistoryEntry(
124
- domMutationHistoryForDebug,
125
- lastDomMutationForDebug
126
- )
127
- emit(
128
- assembleIncrementalSnapshot(IncrementalSource.Mutation, mutationPayload)
129
- )
130
- })
483
+ }
484
+ return false
131
485
  }
132
- var inputCb = function (s) {
133
- emit(assembleIncrementalSnapshot(IncrementalSource.Input, s))
486
+
487
+ var elementsScrollPositions = createElementsScrollPositions()
488
+ var replayPerformanceStats = __BUILD_ENV__REPLAY_DEBUG_ENABLED__
489
+ ? createReplayPerformanceStats()
490
+ : undefined
491
+ var pendingMutationPayload
492
+ var pendingMutationTimeout
493
+ var pendingMutationAdmissionQueue = []
494
+ var pendingMutationAdmissionApproxBytes = 0
495
+ var pendingMutationAdmissionTimeout
496
+ var pendingFullSnapshotTimeout
497
+ var pendingFullSnapshotTimestamp
498
+ var pendingFullSnapshotCanBeDiscarded = false
499
+ var pendingFullSnapshotRequiresTailDiscard = false
500
+ var pendingFullSnapshotTask
501
+ var pendingFullSnapshotMutationVersion
502
+ var pendingFullSnapshotStartedAt
503
+ var pendingFullSnapshotActiveDuration = 0
504
+ var pendingFullSnapshotRestartCount = 0
505
+ var pendingFullSnapshotRestartRequested = false
506
+ var pendingFullSnapshotSynchronousFallbackAttempted = false
507
+ var pendingFullSnapshotIsInitial = false
508
+ var pendingFullSnapshotBaselineRecords
509
+ var pendingFullSnapshotBaselineMutationVersion
510
+ var fullSnapshotWasPublished = false
511
+ var domMutationVersion = 0
512
+ var mutationActivityTargets = new Set()
513
+ var mutationActivityFlushScheduled = false
514
+ var fullSnapshotCanvasBaselineGeneration = 0
515
+ var publishedNodeParentByNode = new WeakMap()
516
+ var publicationTokenByNode = new WeakMap()
517
+ var pendingNodeParentByNode = new WeakMap()
518
+ var pendingPublicationTokenByNode = new WeakMap()
519
+ var refreshAndFlushPendingRootForNode = function () {}
520
+ var currentFullSnapshotPublicationToken = createPublicationToken()
521
+ var previousPublishedReplayTree
522
+
523
+ function getPublishedReplayTree() {
524
+ return {
525
+ $rPublishedNodeParentByNode: publishedNodeParentByNode,
526
+ $rPublicationTokenByNode: publicationTokenByNode,
527
+ $rPendingNodeParentByNode: pendingNodeParentByNode,
528
+ $rPendingPublicationTokenByNode: pendingPublicationTokenByNode,
529
+ $rCurrentFullSnapshotPublicationToken:
530
+ currentFullSnapshotPublicationToken
531
+ }
134
532
  }
135
533
 
136
- var shadowRootsController = initShadowRootsController(options.configuration, {
137
- mutationCb,
138
- inputCb
139
- })
140
- var lastAutoCanvasSnapshotResult
141
- var autoCanvasSnapshotDebugHistoryForDebug = []
142
- var lastCanvasMutationForDebug
143
- var canvasMutationHistoryForDebug = []
144
- var lastDomMutationForDebug
145
- var domMutationHistoryForDebug = []
146
- var shouldUseCanvasCommandCapture = shouldUseCommandCapture(
147
- options.configuration
148
- )
149
- var canvasObserver = (
150
- options.createCanvasObserver || createCanvasObserver
151
- )({
152
- configuration: options.configuration,
153
- emit: emit,
154
- onMutationDebug: function (result) {
155
- lastCanvasMutationForDebug = cloneCanvasMutationDebugResult(result)
156
- pushCanvasDebugHistoryEntry(
157
- canvasMutationHistoryForDebug,
158
- lastCanvasMutationForDebug
534
+ function restorePreviousPublishedReplayTree() {
535
+ if (!previousPublishedReplayTree) {
536
+ return false
537
+ }
538
+ publishedNodeParentByNode =
539
+ previousPublishedReplayTree.$rPublishedNodeParentByNode
540
+ publicationTokenByNode =
541
+ previousPublishedReplayTree.$rPublicationTokenByNode
542
+ pendingNodeParentByNode =
543
+ previousPublishedReplayTree.$rPendingNodeParentByNode
544
+ pendingPublicationTokenByNode =
545
+ previousPublishedReplayTree.$rPendingPublicationTokenByNode
546
+ currentFullSnapshotPublicationToken =
547
+ previousPublishedReplayTree.$rCurrentFullSnapshotPublicationToken
548
+ previousPublishedReplayTree = undefined
549
+ return true
550
+ }
551
+
552
+ function resetPublishedReplayTree() {
553
+ publishedNodeParentByNode = new WeakMap()
554
+ publicationTokenByNode = new WeakMap()
555
+ pendingNodeParentByNode = new WeakMap()
556
+ pendingPublicationTokenByNode = new WeakMap()
557
+ currentFullSnapshotPublicationToken = createPublicationToken()
558
+ }
559
+
560
+ function createPublicationToken() {
561
+ return {
562
+ $rPublished: false
563
+ }
564
+ }
565
+
566
+ function stageFullSnapshotNodePublication(
567
+ node,
568
+ parentNode,
569
+ publicationToken
570
+ ) {
571
+ publishedNodeParentByNode.set(node, parentNode)
572
+ publicationTokenByNode.set(node, publicationToken)
573
+ }
574
+
575
+ function stageMutationNodePublication(
576
+ node,
577
+ parentNode,
578
+ publicationToken
579
+ ) {
580
+ var previousPendingToken = pendingPublicationTokenByNode.get(node)
581
+ if (previousPendingToken && previousPendingToken.$rPublished) {
582
+ publishedNodeParentByNode.set(
583
+ node,
584
+ pendingNodeParentByNode.get(node)
159
585
  )
586
+ publicationTokenByNode.set(node, previousPendingToken)
160
587
  }
161
- })
162
- var startCanvasSnapshotLoop =
163
- options.startContinuousCanvasSnapshotLoop || startContinuousCanvasSnapshotLoop
164
- var canvasSnapshotLoop = shouldUseCanvasCommandCapture
165
- ? {
166
- stop: function () {},
167
- reset: function () {}
168
- }
169
- : startCanvasSnapshotLoop({
170
- configuration: options.configuration,
171
- getCanvases: function () {
172
- return getSerializedCanvasNodes()
173
- },
174
- getSerializedNodeId: function (canvas) {
175
- return getSerializedNodeId(canvas)
176
- },
177
- onDebug: function (result) {
178
- var keepSessionAliveTriggered = false
588
+ pendingNodeParentByNode.set(node, parentNode)
589
+ pendingPublicationTokenByNode.set(node, publicationToken)
590
+ if (
591
+ publicationToken &&
592
+ typeof HTMLCanvasElement !== 'undefined' &&
593
+ node instanceof HTMLCanvasElement
594
+ ) {
595
+ if (!publicationToken.$rCanvasNodes) {
596
+ publicationToken.$rCanvasNodes = new Set()
597
+ }
598
+ publicationToken.$rCanvasNodes.add(node)
599
+ }
600
+ }
601
+
602
+ function isNodePublished(node) {
603
+ if (!node) {
604
+ return false
605
+ }
606
+ var pendingPublicationToken =
607
+ pendingPublicationTokenByNode.get(node)
608
+ if (pendingPublicationToken) {
609
+ if (pendingPublicationToken.$rPublished) {
610
+ return true
611
+ }
612
+ if (!pendingPublicationToken.$rCanceled) {
613
+ return false
614
+ }
615
+ }
616
+ if (!publishedNodeParentByNode.has(node)) {
617
+ return false
618
+ }
619
+ var publicationToken = publicationTokenByNode.get(node)
620
+ return Boolean(publicationToken && publicationToken.$rPublished)
621
+ }
622
+
623
+ function wasNodePublishedBeforePendingMutation(node) {
624
+ var publicationToken = publicationTokenByNode.get(node)
625
+ return Boolean(
626
+ publishedNodeParentByNode.has(node) &&
627
+ publicationToken &&
628
+ publicationToken.$rPublished
629
+ )
630
+ }
631
+
632
+ function isNodeQueuedOrPublished(node) {
633
+ if (!node) {
634
+ return false
635
+ }
636
+ var pendingPublicationToken =
637
+ pendingPublicationTokenByNode.get(node)
638
+ if (pendingPublicationToken) {
179
639
  if (
180
- shouldKeepSessionAliveAfterAutoCanvasSnapshot(result) &&
181
- options.sessionManager &&
182
- options.sessionManager.keepSessionAlive
640
+ pendingPublicationToken.$rPublished ||
641
+ pendingPublicationToken.$rQueued
183
642
  ) {
184
- options.sessionManager.keepSessionAlive()
185
- keepSessionAliveTriggered = true
643
+ return true
644
+ }
645
+ if (!pendingPublicationToken.$rCanceled) {
646
+ return false
186
647
  }
187
- lastAutoCanvasSnapshotResult = cloneAutoCanvasSnapshotDebugResult(
188
- result,
189
- keepSessionAliveTriggered
190
- )
191
- pushCanvasDebugHistoryEntry(
192
- autoCanvasSnapshotDebugHistoryForDebug,
193
- lastAutoCanvasSnapshotResult
194
- )
195
- },
196
- snapshotCanvas: function (canvas) {
197
- return canvasObserver.snapshot(canvas, {
198
- trigger: 'auto',
199
- scheduler: 'continuous_snapshot'
200
- })
201
648
  }
202
- })
203
- var canvasCommandCapture = (
204
- options.startCanvasCommandCapture || startCanvasCommandCapture
205
- )({
206
- configuration: options.configuration,
207
- emit: emit,
208
- snapshotCanvas: function (canvas, snapshotOptions) {
209
- return canvasObserver.snapshot(canvas, snapshotOptions)
210
- },
211
- getCanvases: function () {
212
- return getSerializedCanvasNodes()
213
- },
214
- getSerializedNodeId: function (canvas) {
215
- return getSerializedNodeId(canvas)
216
- },
217
- onDebug: function (result) {
218
- var keepSessionAliveTriggered = false
649
+ var publicationToken = publicationTokenByNode.get(node)
650
+ return Boolean(
651
+ publicationToken &&
652
+ (publicationToken.$rPublished || publicationToken.$rQueued)
653
+ )
654
+ }
655
+
656
+ function getPublishedParent(node, includeQueued) {
657
+ var pendingPublicationToken =
658
+ pendingPublicationTokenByNode.get(node)
659
+ if (
660
+ pendingPublicationToken &&
661
+ (pendingPublicationToken.$rPublished ||
662
+ (includeQueued &&
663
+ pendingPublicationToken.$rQueued &&
664
+ !pendingPublicationToken.$rCanceled))
665
+ ) {
666
+ return pendingNodeParentByNode.get(node)
667
+ }
668
+ return publishedNodeParentByNode.get(node)
669
+ }
670
+
671
+ function isNodeInPublishedReplayTree(node, includeQueued) {
672
+ var current = node
673
+ var depth = 0
674
+ while (current) {
219
675
  if (
220
- shouldKeepSessionAliveAfterAutoCanvasSnapshot(result) &&
221
- options.sessionManager &&
222
- options.sessionManager.keepSessionAlive
676
+ depth >= MAX_SERIALIZED_NODE_ANCESTOR_DEPTH ||
677
+ (!publishedNodeParentByNode.has(current) &&
678
+ !pendingNodeParentByNode.has(current))
223
679
  ) {
224
- options.sessionManager.keepSessionAlive()
225
- keepSessionAliveTriggered = true
680
+ return false
226
681
  }
227
- lastAutoCanvasSnapshotResult = cloneAutoCanvasSnapshotDebugResult(
228
- result,
229
- keepSessionAliveTriggered
230
- )
231
- pushCanvasDebugHistoryEntry(
232
- autoCanvasSnapshotDebugHistoryForDebug,
233
- lastAutoCanvasSnapshotResult
234
- )
235
- },
236
- onMutationDebug: function (result) {
237
- lastCanvasMutationForDebug = cloneCanvasMutationDebugResult(result)
238
- pushCanvasDebugHistoryEntry(
239
- canvasMutationHistoryForDebug,
240
- lastCanvasMutationForDebug
241
- )
682
+ if (
683
+ !(includeQueued
684
+ ? isNodeQueuedOrPublished(current)
685
+ : isNodePublished(current))
686
+ ) {
687
+ return false
688
+ }
689
+ var publishedParent = getPublishedParent(current, includeQueued)
690
+ var currentParent
691
+ try {
692
+ currentParent = getParentNode(current)
693
+ } catch (_) {
694
+ return false
695
+ }
696
+ if (currentParent !== publishedParent) {
697
+ return false
698
+ }
699
+ current = currentParent
700
+ depth += 1
242
701
  }
243
- })
702
+ return Boolean(node)
703
+ }
244
704
 
245
- var takeFullSnapshot = function (timestamp, serializationContext) {
246
- if (typeof timestamp === 'undefined') {
247
- timestamp = timeStampNow()
705
+ function isNodeInPreviousPublishedReplayTree(node) {
706
+ if (!node || !previousPublishedReplayTree) {
707
+ return false
248
708
  }
249
- if (typeof serializationContext === 'undefined') {
250
- serializationContext = {
251
- status: SerializationContextStatus.INITIAL_FULL_SNAPSHOT,
252
- elementsScrollPositions: elementsScrollPositions,
253
- shadowRootsController: shadowRootsController
709
+ var previousParents =
710
+ previousPublishedReplayTree.$rPublishedNodeParentByNode
711
+ var previousTokens =
712
+ previousPublishedReplayTree.$rPublicationTokenByNode
713
+ var current = node
714
+ var depth = 0
715
+ while (current) {
716
+ if (
717
+ depth >= MAX_SERIALIZED_NODE_ANCESTOR_DEPTH ||
718
+ !previousParents.has(current)
719
+ ) {
720
+ return false
721
+ }
722
+ var publicationToken = previousTokens.get(current)
723
+ if (!publicationToken || !publicationToken.$rPublished) {
724
+ return false
725
+ }
726
+ var publishedParent = previousParents.get(current)
727
+ var currentParent
728
+ try {
729
+ currentParent = getParentNode(current)
730
+ } catch (_) {
731
+ return false
254
732
  }
733
+ if (currentParent !== publishedParent) {
734
+ return false
735
+ }
736
+ current = currentParent
737
+ depth += 1
255
738
  }
256
- var _viewportDimension = getViewportDimension()
257
- var width = _viewportDimension.width
258
- var height = _viewportDimension.height
259
- emit({
260
- data: {
261
- height: height,
262
- href: window.location.href,
263
- width: width
264
- },
265
- type: RecordType.Meta,
266
- timestamp: timestamp
267
- })
739
+ return true
740
+ }
268
741
 
269
- emit({
270
- data: {
271
- has_focus: document.hasFocus()
272
- },
273
- type: RecordType.Focus,
274
- timestamp: timestamp
275
- })
276
-
277
- emit({
278
- data: {
279
- node: serializeDocument(
280
- document,
281
- options.configuration,
282
- serializationContext
283
- ),
284
- initialOffset: {
285
- left: getScrollX(),
286
- top: getScrollY()
742
+ function publishMutationMembership(mutationPayload) {
743
+ var acceptedPublicationTokens = new Set()
744
+ var publicationTokens = mutationPayload.adds.map(function (add) {
745
+ var publicationToken = consumeMutationAddPublicationToken(add)
746
+ if (publicationToken) {
747
+ acceptedPublicationTokens.add(publicationToken)
748
+ }
749
+ return publicationToken
750
+ })
751
+ mutationPayload.removes.forEach(function (remove) {
752
+ var removedNode = consumeMutationRemoveSourceNode(remove)
753
+ if (removedNode) {
754
+ publishedNodeParentByNode.delete(removedNode)
755
+ publicationTokenByNode.delete(removedNode)
756
+ // A move is encoded as remove + add with the same serialized id.
757
+ // Preserve staged destination membership for any node serialized
758
+ // under an accepted add root, including moved descendants.
759
+ if (
760
+ !acceptedPublicationTokens.has(
761
+ pendingPublicationTokenByNode.get(removedNode)
762
+ )
763
+ ) {
764
+ pendingNodeParentByNode.delete(removedNode)
765
+ pendingPublicationTokenByNode.delete(removedNode)
287
766
  }
288
- },
289
- type: RecordType.FullSnapshot,
290
- timestamp: timestamp
767
+ }
768
+ })
769
+ publicationTokens.forEach(function (publicationToken) {
770
+ publishMutationAddPublicationToken(publicationToken)
771
+ if (
772
+ publicationToken &&
773
+ publicationToken.$rCanvasNodes &&
774
+ canvasCommandCapture &&
775
+ canvasCommandCapture.$rRetryPublishedCanvas
776
+ ) {
777
+ publicationToken.$rCanvasNodes.forEach(function (canvas) {
778
+ canvasCommandCapture.$rRetryPublishedCanvas(canvas)
779
+ })
780
+ }
781
+ if (publicationToken) {
782
+ publicationToken.$rCanvasNodes = undefined
783
+ }
291
784
  })
292
-
293
- if (window.visualViewport) {
294
- emit({
295
- data: getVisualViewport(),
296
- type: RecordType.VisualViewport,
297
- timestamp: timestamp
298
- })
299
- }
300
785
  }
301
786
 
302
- takeFullSnapshot()
303
- if (canvasCommandCapture.scanExistingCanvases) {
304
- canvasCommandCapture.scanExistingCanvases()
787
+ function discardMutationMembership(mutationPayload) {
788
+ mutationPayload.removes.forEach(function (remove) {
789
+ consumeMutationRemoveSourceNode(remove)
790
+ })
791
+ mutationPayload.adds.forEach(function (add) {
792
+ var publicationToken = consumeMutationAddPublicationToken(add)
793
+ if (publicationToken && !publicationToken.$rPublished) {
794
+ cancelMutationAddPublicationToken(publicationToken)
795
+ }
796
+ if (publicationToken) {
797
+ publicationToken.$rCanvasNodes = undefined
798
+ }
799
+ })
305
800
  }
306
- var _initObservers = initObservers({
307
- lifeCycle: options.lifeCycle,
308
- configuration: options.configuration,
309
- elementsScrollPositions: elementsScrollPositions,
310
- inputCb: inputCb,
311
- mediaInteractionCb: function (p) {
312
- emit(assembleIncrementalSnapshot(IncrementalSource.MediaInteraction, p))
313
- },
314
- mouseInteractionCb: function (mouseInteractionRecord) {
315
- emit(mouseInteractionRecord)
316
- },
317
- mousemoveCb: function (positions, source) {
318
- emit(assembleIncrementalSnapshot(source, { positions: positions }))
319
- },
320
- mutationCb: mutationCb,
321
- mutationPerfCb: updateReplayPerformanceStats,
322
- scrollCb: function (p) {
323
- emit(assembleIncrementalSnapshot(IncrementalSource.Scroll, p))
324
- },
325
- styleSheetCb: function (r) {
326
- emit(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule, r))
327
- },
328
- viewportResizeCb: function (d) {
329
- emit(assembleIncrementalSnapshot(IncrementalSource.ViewportResize, d))
330
- },
331
- frustrationCb: function (frustrationRecord) {
332
- emit(frustrationRecord)
333
- },
334
- focusCb: function (data) {
335
- emit({
336
- data: data,
337
- type: RecordType.Focus,
338
- timestamp: timeStampNow()
339
- })
340
- },
341
- visualViewportResizeCb: function (data) {
342
- emit({
343
- data: data,
344
- type: RecordType.VisualViewport,
345
- timestamp: timeStampNow()
801
+
802
+ function trackDomMutationActivity(target) {
803
+ if (
804
+ suppressRecordsUntilFullSnapshot &&
805
+ previousReplayTreeAdmissionActive
806
+ ) {
807
+ pendingFullSnapshotTimestamp = Math.max(
808
+ typeof pendingFullSnapshotTimestamp === 'number'
809
+ ? pendingFullSnapshotTimestamp
810
+ : 0,
811
+ timeStampNow()
812
+ )
813
+ }
814
+ if (
815
+ suppressRecordsUntilFullSnapshot &&
816
+ pendingFullSnapshotCanBeDiscarded
817
+ ) {
818
+ // DOM mutation payloads are serialized against the pending tree and
819
+ // cannot also be replayed safely against the previous tree. Promote the
820
+ // optional transaction so it cannot abandon after retiring that change.
821
+ pendingFullSnapshotCanBeDiscarded = false
822
+ pendingFullSnapshotRestartRequested = true
823
+ }
824
+ domMutationVersion += 1
825
+ if (
826
+ !target ||
827
+ mutationActivityFlushScheduled ||
828
+ recordStopping ||
829
+ recordStopped
830
+ ) {
831
+ if (target) {
832
+ mutationActivityTargets.add(target)
833
+ }
834
+ return
835
+ }
836
+ mutationActivityTargets.add(target)
837
+ mutationActivityFlushScheduled = true
838
+ setTimeout(function () {
839
+ mutationActivityFlushScheduled = false
840
+ var activeTargets = mutationActivityTargets
841
+ mutationActivityTargets = new Set()
842
+ if (
843
+ activeTargets.size > 1 &&
844
+ !recordStopping &&
845
+ !recordStopped &&
846
+ !suppressRecordsUntilFullSnapshot &&
847
+ !mutationSourceFlushInProgress
848
+ ) {
849
+ flushMutations()
850
+ }
851
+ }, MUTATION_EMIT_DELAY_MS)
852
+ }
853
+
854
+ function captureDynamicShadowRoot(shadowRoot, host) {
855
+ if (recordStopping || recordStopped) {
856
+ return
857
+ }
858
+ var hostIsConnected
859
+ try {
860
+ hostIsConnected = host.isConnected
861
+ } catch (_) {
862
+ return
863
+ }
864
+ if (!hostIsConnected) {
865
+ return
866
+ }
867
+
868
+ // attachShadow() itself does not enqueue a document MutationRecord. Mark
869
+ // the active full-snapshot transaction dirty so a root attached after its
870
+ // host was traversed cannot be omitted from the published baseline.
871
+ trackDomMutationActivity()
872
+ if (suppressRecordsUntilFullSnapshot) {
873
+ return
874
+ }
875
+
876
+ // An unpublished host will be serialized by its pending outer add, which
877
+ // naturally includes the new root. Refresh and synchronously drain the
878
+ // owning document/shadow mutation controller before returning from
879
+ // attachShadow(), so children appended immediately afterwards are
880
+ // observed behind a published host/root boundary.
881
+ if (!isNodeQueuedOrPublished(host)) {
882
+ var pendingHostFlushResult =
883
+ refreshAndFlushPendingRootForNode(host)
884
+ if (
885
+ typeof pendingHostFlushResult === 'undefined' &&
886
+ shadowRootsController.refreshAndFlushPendingRootForNode
887
+ ) {
888
+ pendingHostFlushResult =
889
+ shadowRootsController.refreshAndFlushPendingRootForNode(host)
890
+ }
891
+ if (pendingHostFlushResult === true) {
892
+ // The rebuilt host add contains the empty ShadowRoot inline and its
893
+ // publication token owns the provisional shadow observer. Commit or
894
+ // roll it back before application code can append the first child.
895
+ flushPendingMutations()
896
+ }
897
+ return
898
+ }
899
+
900
+ // A host add can still be waiting in the mutation emit buffer here.
901
+ // Resolve that structural dependency before creating the shadow-root add:
902
+ // if the host record is rejected synchronously, accepting a later shadow
903
+ // record would reference a parent id that the replay backend never saw.
904
+ flushPendingMutations()
905
+ if (!isNodeInPublishedReplayTree(host)) {
906
+ return
907
+ }
908
+
909
+ var hostPrivacyLevel = getNodePrivacyLevel(
910
+ host,
911
+ configuration.defaultPrivacyLevel
912
+ )
913
+ if (
914
+ hostPrivacyLevel === NodePrivacyLevel.HIDDEN ||
915
+ hostPrivacyLevel === NodePrivacyLevel.IGNORE
916
+ ) {
917
+ return
918
+ }
919
+
920
+ var publicationToken = createMutationAddPublicationToken(
921
+ shadowRootsController
922
+ )
923
+ var serializerTask = createMutationSerializerTask(shadowRoot, {
924
+ serializationContext: {
925
+ status: SerializationContextStatus.MUTATION,
926
+ shadowRootsController: shadowRootsController,
927
+ publicationToken: publicationToken
928
+ },
929
+ parentNodePrivacyLevel: hostPrivacyLevel,
930
+ configuration: configuration,
931
+ onSerializedNode: function (node, parentNode) {
932
+ stageMutationNodePublication(
933
+ node,
934
+ parentNode,
935
+ publicationToken
936
+ )
937
+ }
938
+ })
939
+ if (
940
+ !serializerTask ||
941
+ !serializerTask.advance(
942
+ getPerformanceTime() + FULL_SNAPSHOT_SERIALIZATION_SLICE_MS,
943
+ DYNAMIC_SHADOW_ROOT_SERIALIZATION_MAX_NODE_COUNT,
944
+ DYNAMIC_SHADOW_ROOT_SERIALIZATION_MAX_APPROX_BYTES
945
+ ) ||
946
+ serializerTask.isMaxNodeCountReached ||
947
+ serializerTask.isMaxApproxBytesReached ||
948
+ serializerTask.isMaxDepthReached ||
949
+ serializerTask.isMaxNodeComplexityReached
950
+ ) {
951
+ cancelMutationAddPublicationToken(publicationToken)
952
+ beginAdmissionGapRecovery('dynamic_shadow_root_serialization')
953
+ return
954
+ }
955
+
956
+ var add = {
957
+ parentId: getSerializedNodeId(host),
958
+ nextId: null,
959
+ node: serializerTask.serializedNode
960
+ }
961
+ publicationToken.$rQueued = true
962
+ registerMutationAddPublicationToken(add, publicationToken)
963
+ mutationCb({
964
+ adds: [add],
965
+ removes: [],
966
+ texts: [],
967
+ attributes: []
968
+ })
969
+ // attachShadow() returns control to the application immediately. Publish
970
+ // the empty root boundary first so synchronous children added by the
971
+ // caller can be observed without ever overtaking their parent root.
972
+ flushPendingMutations()
973
+ }
974
+
975
+ var mutationLocalDropTelemetryReported = false
976
+ var updateReplayPerformanceStats = function (delta) {
977
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
978
+ accumulateReplayPerformanceStats(replayPerformanceStats, delta)
979
+ } else if (!mutationLocalDropTelemetryReported) {
980
+ mutationLocalDropTelemetryReported = true
981
+ addTelemetryDebug('Session Replay record discarded.', {
982
+ reason: delta
983
+ })
984
+ }
985
+ }
986
+
987
+ var mutationSourceFlushInProgress = false
988
+ var mutationFlushDocumentPending = false
989
+ var mutationSourceFlushContinuationTimeout
990
+ var mutationCb = function (mutation) {
991
+ var mutationMeasurements = measureMutationPayload(mutation)
992
+ if (hasOversizedMutationEntry(mutationMeasurements)) {
993
+ if (hasStructuralMutationEntries(mutation)) {
994
+ // An oversized add/remove cannot be partitioned independently from
995
+ // structural work that may have arrived in another observer callback.
996
+ // A move is reported as remove + add, and emitting only the bounded
997
+ // half would make the player delete a node whose destination was
998
+ // never published. Discard the complete local recovery window and
999
+ // require a replacement baseline. Mandatory recovery also holds (and
1000
+ // eventually discards) the current segment, covering a structural
1001
+ // prefix that may already have been admitted before this callback.
1002
+ discardPendingMutationPayload()
1003
+ discardPendingMutationAdmissions()
1004
+ discardMutationMembership(mutation)
1005
+ beginAdmissionGapRecovery('oversized_structural_mutation')
1006
+ return
1007
+ }
1008
+ var mutationPartition = partitionMutationPayloadByEntrySize(
1009
+ mutation,
1010
+ mutationMeasurements
1011
+ )
1012
+ // Preserve safe work that was already waiting to be emitted, then replace
1013
+ // the dropped mutation with a new DOM baseline. Never merge an
1014
+ // indivisible oversized entry into the pending payload: doing so would
1015
+ // retain it in debug history and make the segment layer stringify it
1016
+ // before eventually rejecting it.
1017
+ flushPendingMutations()
1018
+ if (hasMutationEntries(mutationPartition.mutation)) {
1019
+ pendingMutationPayload = mergeMutationPayloads(
1020
+ undefined,
1021
+ mutationPartition.mutation,
1022
+ mutationPartition.measurements
1023
+ )
1024
+ flushPendingMutations()
1025
+ }
1026
+ requestFullSnapshotAfterMutationDrop({
1027
+ reason: 'oversized_non_structural_mutation'
1028
+ })
1029
+ return
1030
+ }
1031
+ if (
1032
+ !mutationSourceFlushInProgress &&
1033
+ pendingMutationPayload &&
1034
+ shouldFlushPendingMutationPayloadBeforeMerge(
1035
+ pendingMutationPayload,
1036
+ mutation,
1037
+ mutationMeasurements.approxBytes,
1038
+ pendingPublicationTokenByNode,
1039
+ pendingNodeParentByNode,
1040
+ wasNodePublishedBeforePendingMutation
1041
+ )
1042
+ ) {
1043
+ flushPendingMutations()
1044
+ }
1045
+ pendingMutationPayload = mergeMutationPayloads(
1046
+ pendingMutationPayload,
1047
+ mutation,
1048
+ mutationMeasurements
1049
+ )
1050
+ scheduleMutationEmit()
1051
+ }
1052
+ function scheduleMutationEmit() {
1053
+ if (pendingMutationTimeout) {
1054
+ return
1055
+ }
1056
+ pendingMutationTimeout = setTimeout(function () {
1057
+ pendingMutationTimeout = undefined
1058
+ if (mutationFlushDocumentPending) {
1059
+ scheduleMutationSourceFlushContinuation()
1060
+ return
1061
+ }
1062
+ flushPendingMutations()
1063
+ }, MUTATION_EMIT_DELAY_MS)
1064
+ }
1065
+
1066
+ function wasLastEmitBackpressured() {
1067
+ return Boolean(
1068
+ lastEmitWasLocallyBackpressured ||
1069
+ (options.$rWasLastEmitBackpressured &&
1070
+ options.$rWasLastEmitBackpressured())
1071
+ )
1072
+ }
1073
+
1074
+ function scheduleMutationAdmissionRetry() {
1075
+ scheduleMutationAdmissionDrain(MUTATION_ADMISSION_RETRY_DELAY_MS)
1076
+ }
1077
+
1078
+ function scheduleMutationAdmissionContinuation() {
1079
+ scheduleMutationAdmissionDrain(0)
1080
+ }
1081
+
1082
+ function scheduleMutationAdmissionDrain(delay) {
1083
+ if (
1084
+ pendingMutationAdmissionTimeout !== undefined ||
1085
+ !pendingMutationAdmissionQueue.length ||
1086
+ recordStopping ||
1087
+ recordStopped
1088
+ ) {
1089
+ return
1090
+ }
1091
+ pendingMutationAdmissionTimeout = setTimeout(function () {
1092
+ pendingMutationAdmissionTimeout = undefined
1093
+ drainPendingMutationAdmissions()
1094
+ }, delay)
1095
+ }
1096
+
1097
+ function discardPendingMutationAdmissions() {
1098
+ if (pendingMutationAdmissionTimeout !== undefined) {
1099
+ clearTimeout(pendingMutationAdmissionTimeout)
1100
+ pendingMutationAdmissionTimeout = undefined
1101
+ }
1102
+ pendingMutationAdmissionQueue.forEach(function (entry) {
1103
+ entry.$rPendingAdmission = false
1104
+ discardMutationMembership(entry[0])
1105
+ })
1106
+ pendingMutationAdmissionQueue = []
1107
+ pendingMutationAdmissionApproxBytes = 0
1108
+ }
1109
+
1110
+ function isPureAddMutationPayload(mutationPayload) {
1111
+ return Boolean(
1112
+ mutationPayload &&
1113
+ mutationPayload.adds.length &&
1114
+ !mutationPayload.removes.length &&
1115
+ !mutationPayload.texts.length &&
1116
+ !mutationPayload.attributes.length
1117
+ )
1118
+ }
1119
+
1120
+ function tryMergePendingPureAddMutationAdmission(entry) {
1121
+ var previousEntry =
1122
+ pendingMutationAdmissionQueue[
1123
+ pendingMutationAdmissionQueue.length - 1
1124
+ ]
1125
+ var mutationPayload = entry[0]
1126
+ if (
1127
+ !previousEntry ||
1128
+ previousEntry[3] ||
1129
+ previousEntry.$rReferencedByDeferredRecord ||
1130
+ !isPureAddMutationPayload(previousEntry[0]) ||
1131
+ !isPureAddMutationPayload(mutationPayload) ||
1132
+ previousEntry[1] + entry[1] > MAX_MUTATION_EMIT_APPROX_BYTES ||
1133
+ pendingMutationAdmissionApproxBytes + entry[1] >
1134
+ MAX_PENDING_MUTATION_ADMISSION_APPROX_BYTES
1135
+ ) {
1136
+ return false
1137
+ }
1138
+
1139
+ // The previous record has been assembled but never offered to the
1140
+ // segment encoder, so its mutation arrays have not been serialized or
1141
+ // cached yet. Keep one exact admission boundary for adjacent independent
1142
+ // adds while retaining insertion order and every publication token.
1143
+ // Never mutate an attempted entry: a rejected encoder admission can cache
1144
+ // its serialized bytes for the exact-object retry contract.
1145
+ mutationPayload.adds.forEach(function (addMutation) {
1146
+ previousEntry[0].adds.push(addMutation)
1147
+ })
1148
+ previousEntry[1] += entry[1]
1149
+ pendingMutationAdmissionApproxBytes += entry[1]
1150
+ return true
1151
+ }
1152
+
1153
+ function enqueueMutationEntriesForAdmission(mutationEntries) {
1154
+ if (!mutationEntries.length) {
1155
+ return
1156
+ }
1157
+ if (
1158
+ suppressRecordsUntilFullSnapshot ||
1159
+ recordStopped
1160
+ ) {
1161
+ mutationEntries.forEach(function (entry) {
1162
+ discardMutationMembership(entry[0])
1163
+ })
1164
+ return
1165
+ }
1166
+ for (var entryIndex = 0; entryIndex < mutationEntries.length; entryIndex += 1) {
1167
+ var entry = mutationEntries[entryIndex]
1168
+ if (tryMergePendingPureAddMutationAdmission(entry)) {
1169
+ continue
1170
+ }
1171
+ if (
1172
+ pendingMutationAdmissionQueue.length + 1 >
1173
+ MAX_PENDING_MUTATION_ADMISSION_PAYLOADS ||
1174
+ pendingMutationAdmissionApproxBytes + entry[1] >
1175
+ MAX_PENDING_MUTATION_ADMISSION_APPROX_BYTES
1176
+ ) {
1177
+ var rejectedTail = mutationEntries.slice(entryIndex)
1178
+ rejectedTail.forEach(function (rejectedEntry) {
1179
+ discardMutationMembership(rejectedEntry[0])
1180
+ })
1181
+ discardPendingMutationAdmissions()
1182
+ beginAdmissionGapRecovery('mutation_admission_queue_overflow')
1183
+ return
1184
+ }
1185
+ entry[2] = assembleIncrementalSnapshot(
1186
+ IncrementalSource.Mutation,
1187
+ entry[0]
1188
+ )
1189
+ entry.$rPendingAdmission = true
1190
+ pendingMutationAdmissionQueue.push(entry)
1191
+ pendingMutationAdmissionApproxBytes += entry[1]
1192
+ }
1193
+ // Assemble the complete callback batch before attempting admission. A
1194
+ // per-entry drain would reset the slice budget for every push and could
1195
+ // synchronously consume the full pending-raw window.
1196
+ if (pendingMutationAdmissionTimeout === undefined) {
1197
+ drainPendingMutationAdmissions()
1198
+ }
1199
+ }
1200
+
1201
+ function drainPendingMutationAdmissions() {
1202
+ if (pendingMutationAdmissionTimeout !== undefined) {
1203
+ clearTimeout(pendingMutationAdmissionTimeout)
1204
+ pendingMutationAdmissionTimeout = undefined
1205
+ }
1206
+ if (suppressRecordsUntilFullSnapshot) {
1207
+ if (pendingFullSnapshotBaselineRecords) {
1208
+ // Serialization is complete and the exact baseline transaction is
1209
+ // only waiting for encoder capacity. Keep later DOM records ordered
1210
+ // behind it; once the same baseline objects are admitted they can
1211
+ // drain normally instead of forcing a re-serialization loop.
1212
+ return false
1213
+ }
1214
+ // The replacement baseline supersedes every queued mutation. Retrying a
1215
+ // formerly backpressured record through emit() while suppression is
1216
+ // active would look like a permanent rejection and recursively start a
1217
+ // second full-snapshot transaction before the first task exists.
1218
+ discardPendingMutationAdmissions()
1219
+ return false
1220
+ }
1221
+ if (
1222
+ recordStopped ||
1223
+ !pendingMutationAdmissionQueue.length
1224
+ ) {
1225
+ return false
1226
+ }
1227
+ var drainStartedAt = getPerformanceTime()
1228
+ var drainedApproxBytes = 0
1229
+ while (pendingMutationAdmissionQueue.length) {
1230
+ var entry = pendingMutationAdmissionQueue[0]
1231
+ var mutationPayload = entry[0]
1232
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
1233
+ lastDomMutationForDebug = createDomMutationDebugSummary(
1234
+ mutationPayload
1235
+ )
1236
+ pushCanvasDebugHistoryEntry(
1237
+ domMutationHistoryForDebug,
1238
+ lastDomMutationForDebug,
1239
+ DOM_MUTATION_DEBUG_HISTORY_LIMIT
1240
+ )
1241
+ }
1242
+ entry[3] = true
1243
+ var wasAdmitted
1244
+ mutationAdmissionEmitInProgress = true
1245
+ try {
1246
+ wasAdmitted = emit(entry[2])
1247
+ } finally {
1248
+ mutationAdmissionEmitInProgress = false
1249
+ }
1250
+ if (wasAdmitted) {
1251
+ pendingMutationAdmissionQueue.shift()
1252
+ entry.$rPendingAdmission = false
1253
+ pendingMutationAdmissionApproxBytes -= entry[1]
1254
+ var previousMutationPublicationBarrier =
1255
+ mutationPublicationBarrier
1256
+ mutationPublicationBarrier = entry
1257
+ try {
1258
+ publishMutationMembership(mutationPayload)
1259
+ } finally {
1260
+ mutationPublicationBarrier =
1261
+ previousMutationPublicationBarrier
1262
+ }
1263
+ drainedApproxBytes += entry[1]
1264
+ var mutationDrainState = {
1265
+ $rStartedAt: drainStartedAt,
1266
+ $rApproxBytes: drainedApproxBytes
1267
+ }
1268
+ var deferredBarrierWasDrained = flushDeferredRecords(
1269
+ entry,
1270
+ mutationDrainState
1271
+ )
1272
+ drainedApproxBytes = mutationDrainState.$rApproxBytes
1273
+ if (suppressRecordsUntilFullSnapshot || recordStopped) {
1274
+ return false
1275
+ }
1276
+ if (!deferredBarrierWasDrained) {
1277
+ // The dependent records use the same time/byte slice and retry
1278
+ // scheduler. Mutation admission resumes only after this exact
1279
+ // structural barrier has drained.
1280
+ return true
1281
+ }
1282
+ if (
1283
+ pendingMutationAdmissionQueue.length &&
1284
+ (drainedApproxBytes >=
1285
+ MUTATION_ADMISSION_DRAIN_SLICE_APPROX_BYTES ||
1286
+ getPerformanceTime() - drainStartedAt >=
1287
+ MUTATION_ADMISSION_DRAIN_SLICE_MS)
1288
+ ) {
1289
+ scheduleMutationAdmissionContinuation()
1290
+ return true
1291
+ }
1292
+ continue
1293
+ }
1294
+ if (wasLastEmitBackpressured()) {
1295
+ scheduleMutationAdmissionRetry()
1296
+ return
1297
+ }
1298
+ // The rejected payload was never admitted. Discard it and every later
1299
+ // payload so no dependent parent/next id can overtake the gap. A generic
1300
+ // structural rejection keeps the conservative baseline recovery; only
1301
+ // transient encoder backpressure is retried in place.
1302
+ discardPendingMutationAdmissions()
1303
+ beginAdmissionGapRecovery('mutation_admission_rejected')
1304
+ return false
1305
+ }
1306
+ return true
1307
+ }
1308
+
1309
+ function flushPendingMutations() {
1310
+ if (pendingMutationTimeout) {
1311
+ clearTimeout(pendingMutationTimeout)
1312
+ pendingMutationTimeout = undefined
1313
+ }
1314
+ if (!pendingMutationPayload) {
1315
+ drainPendingMutationAdmissions()
1316
+ return
1317
+ }
1318
+ var mutationPayloadToFlush = pendingMutationPayload
1319
+ var splitResult = splitPendingMutationPayloadForEmit(
1320
+ mutationPayloadToFlush,
1321
+ pendingPublicationTokenByNode,
1322
+ wasNodePublishedBeforePendingMutation
1323
+ )
1324
+ pendingMutationPayload = undefined
1325
+ var mutationEntries = splitResult.mutationEntries
1326
+ if (!mutationEntries.length) {
1327
+ discardMutationMembership(
1328
+ materializeMutationPayload(mutationPayloadToFlush)
1329
+ )
1330
+ }
1331
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
1332
+ updateReplayPerformanceStats(
1333
+ mutationEntries.reduce(
1334
+ function (stats, mutationEntry) {
1335
+ var mutationPayload = mutationEntry[0]
1336
+ stats.mutationCallbackCount += 1
1337
+ stats.mutationRecordCount += countMutationPayloadRecords(
1338
+ mutationPayload
1339
+ )
1340
+ stats.mutationAddCount += mutationPayload.adds.length
1341
+ stats.mutationRemoveCount += mutationPayload.removes.length
1342
+ stats.mutationTextCount += mutationPayload.texts.length
1343
+ stats.mutationAttributeCount += mutationPayload.attributes.length
1344
+ return stats
1345
+ },
1346
+ {
1347
+ mutationCallbackCount: 0,
1348
+ mutationRecordCount: 0,
1349
+ mutationAddCount: 0,
1350
+ mutationRemoveCount: 0,
1351
+ mutationTextCount: 0,
1352
+ mutationAttributeCount: 0
1353
+ }
1354
+ )
1355
+ )
1356
+ }
1357
+ enqueueMutationEntriesForAdmission(mutationEntries)
1358
+ if (splitResult.hasOversizedEntry) {
1359
+ requestFullSnapshotAfterMutationDrop({
1360
+ reason: 'split_oversized_mutation_entry'
1361
+ })
1362
+ }
1363
+ }
1364
+ var inputCb = function (s) {
1365
+ emit(assembleIncrementalSnapshot(IncrementalSource.Input, s))
1366
+ }
1367
+
1368
+ var mutationResourceBudget = createMutationResourceBudget()
1369
+ var shadowRootsController
1370
+ try {
1371
+ shadowRootsController = initShadowRootsController(configuration, {
1372
+ mutationCb,
1373
+ mutationPerfCb: updateReplayPerformanceStats,
1374
+ mutationOverflowCb: requestFullSnapshotAfterMutationDrop,
1375
+ mutationActivityCb: trackDomMutationActivity,
1376
+ inputCb,
1377
+ isNodeIgnored: isObservedNodeIgnored,
1378
+ isInputNodeIgnored: isNodeIgnoredForObserver,
1379
+ isNodePublished: isNodeQueuedOrPublished,
1380
+ mutationNodeSerializationCb: stageMutationNodePublication,
1381
+ mutationResourceBudget: mutationResourceBudget,
1382
+ shadowRootCreatedCb: captureDynamicShadowRoot
1383
+ })
1384
+ } catch (error) {
1385
+ return abortRecorderInitialization(
1386
+ 'recorder_initialization_error',
1387
+ error
1388
+ )
1389
+ }
1390
+ registerInitializationCleanup(shadowRootsController.stop)
1391
+
1392
+ function isNodeIgnored(node, includeQueued) {
1393
+ try {
1394
+ return !isNodeInPublishedReplayTree(node, includeQueued)
1395
+ } catch (_) {
1396
+ // Publication membership is part of the replay baseline contract. If it
1397
+ // cannot be established, fail closed instead of emitting a stale id.
1398
+ return true
1399
+ }
1400
+ }
1401
+
1402
+ function isObservedNodeIgnored(node, includeQueued) {
1403
+ var ignored = isNodeIgnored(node, includeQueued)
1404
+ if (
1405
+ ignored &&
1406
+ (pendingFullSnapshotTask || pendingFullSnapshotBaselineRecords) &&
1407
+ publishedNodeParentByNode.has(node)
1408
+ ) {
1409
+ // Input, media, scroll and CSSOM state are not DOM mutations. If an
1410
+ // observer ignores one after the node was serialized, rebuild the
1411
+ // mixed-time baseline so the state change is represented by the next
1412
+ // attempt. This
1413
+ // also covers an exact baseline waiting for encoder capacity: the
1414
+ // unpublished tree cannot accept an incremental state record there.
1415
+ pendingFullSnapshotRestartRequested = true
1416
+ }
1417
+ return ignored
1418
+ }
1419
+
1420
+ function isNodeIgnoredForObserver(node, mutationAssembly) {
1421
+ if (mutationAssembly) {
1422
+ return isObservedNodeIgnored(node, true)
1423
+ }
1424
+
1425
+ if (
1426
+ captureRecordsAgainstPreviousReplayTree &&
1427
+ !mutationSourceFlushInProgress
1428
+ ) {
1429
+ // Native DOM records queued earlier in the same task must be observed
1430
+ // before admitting this state record against the previous replay tail.
1431
+ // The activity callback promotes an optional baseline when necessary.
1432
+ capturePendingMutationActivityForPreviousReplayTree(false)
1433
+ }
1434
+
1435
+ var ignored = isObservedNodeIgnored(node, true)
1436
+ var pendingPublicationToken =
1437
+ pendingPublicationTokenByNode.get(node)
1438
+ if (
1439
+ pendingPublicationToken &&
1440
+ !pendingPublicationToken.$rPublished &&
1441
+ !pendingPublicationToken.$rCanceled
1442
+ ) {
1443
+ if (!pendingPublicationToken.$rQueued) {
1444
+ // A time-sliced add serializer may already have walked this node while
1445
+ // its root is not publishable yet. Rebuild that root from current DOM
1446
+ // state so input/CSSOM changes between slices are not omitted.
1447
+ flushMutationRootForNode(node)
1448
+ } else if (pendingMutationPayload) {
1449
+ // The add is complete but still waiting in the 16 ms mutation emit
1450
+ // buffer. Move it into admission before the dependent state callback;
1451
+ // the state will then emit after a successful add or bind its barrier.
1452
+ flushPendingMutations()
1453
+ }
1454
+ ignored = isObservedNodeIgnored(node, true)
1455
+ }
1456
+ if (
1457
+ ignored &&
1458
+ captureRecordsAgainstPreviousReplayTree &&
1459
+ isNodeInPreviousPublishedReplayTree(node)
1460
+ ) {
1461
+ // The candidate tree is unpublished, but this node still belongs to the
1462
+ // previous replay tail. Let the shared admission path publish its state
1463
+ // before the replacement baseline (or queue it on encoder backpressure).
1464
+ return false
1465
+ }
1466
+ return ignored
1467
+ }
1468
+
1469
+ function isNodeIgnoredForStatelessObserver(node) {
1470
+ if (
1471
+ captureRecordsAgainstPreviousReplayTree &&
1472
+ !mutationSourceFlushInProgress
1473
+ ) {
1474
+ capturePendingMutationActivityForPreviousReplayTree(false)
1475
+ }
1476
+ var ignored = isNodeIgnored(node)
1477
+ if (
1478
+ ignored &&
1479
+ captureRecordsAgainstPreviousReplayTree &&
1480
+ isNodeInPreviousPublishedReplayTree(node)
1481
+ ) {
1482
+ return false
1483
+ }
1484
+ return ignored
1485
+ }
1486
+
1487
+ function getActiveSerializedNodeId(node) {
1488
+ if (isNodeIgnored(node)) {
1489
+ return undefined
1490
+ }
1491
+ return getSerializedNodeId(node)
1492
+ }
1493
+
1494
+ function filterActiveSerializedCanvases(canvases) {
1495
+ return canvases.filter(function (canvas) {
1496
+ return !isNodeIgnored(canvas)
1497
+ })
1498
+ }
1499
+
1500
+ function getActiveSerializedCanvases(maxScanCount) {
1501
+ return filterActiveSerializedCanvases(
1502
+ getSerializedCanvasNodes(maxScanCount)
1503
+ )
1504
+ }
1505
+
1506
+ var lastAutoCanvasSnapshotResult
1507
+ var autoCanvasSnapshotDebugHistoryForDebug =
1508
+ __BUILD_ENV__REPLAY_DEBUG_ENABLED__ ? [] : undefined
1509
+ var lastCanvasMutationForDebug
1510
+ var canvasMutationHistoryForDebug =
1511
+ __BUILD_ENV__REPLAY_DEBUG_ENABLED__ ? [] : undefined
1512
+ var lastDomMutationForDebug
1513
+ var domMutationHistoryForDebug =
1514
+ __BUILD_ENV__REPLAY_DEBUG_ENABLED__ ? [] : undefined
1515
+ function handleAutoCanvasSnapshotDebug(result) {
1516
+ var keepSessionAliveTriggered = false
1517
+ if (
1518
+ shouldKeepSessionAliveAfterAutoCanvasSnapshot(result) &&
1519
+ options.sessionManager &&
1520
+ options.sessionManager.keepSessionAlive
1521
+ ) {
1522
+ options.sessionManager.keepSessionAlive()
1523
+ keepSessionAliveTriggered = true
1524
+ }
1525
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
1526
+ lastAutoCanvasSnapshotResult = cloneAutoCanvasSnapshotDebugResult(
1527
+ result,
1528
+ keepSessionAliveTriggered
1529
+ )
1530
+ pushCanvasDebugHistoryEntry(
1531
+ autoCanvasSnapshotDebugHistoryForDebug,
1532
+ lastAutoCanvasSnapshotResult
1533
+ )
1534
+ }
1535
+ }
1536
+ function handleCanvasMutationDebug(result) {
1537
+ lastCanvasMutationForDebug = cloneCanvasMutationDebugResult(result)
1538
+ pushCanvasDebugHistoryEntry(
1539
+ canvasMutationHistoryForDebug,
1540
+ lastCanvasMutationForDebug
1541
+ )
1542
+ }
1543
+ var shouldUseCanvasCommandCapture = shouldUseCommandCapture(
1544
+ configuration
1545
+ )
1546
+ var baseCanvasEncodeBridge
1547
+ var webGLReplayRuntime
1548
+ var canvasEncodeBridge
1549
+ try {
1550
+ var createCanvasEncodeBridgeImpl =
1551
+ __BUILD_ENV__REPLAY_DEBUG_ENABLED__
1552
+ ? options.createCanvasEncodeBridge || createCanvasEncodeBridge
1553
+ : createCanvasEncodeBridge
1554
+ var createSessionReplayWebGLRuntimeImpl =
1555
+ __BUILD_ENV__REPLAY_DEBUG_ENABLED__
1556
+ ? options.createSessionReplayWebGLRuntime ||
1557
+ createSessionReplayWebGLRuntime
1558
+ : createSessionReplayWebGLRuntime
1559
+ baseCanvasEncodeBridge = createCanvasEncodeBridgeImpl(
1560
+ configuration
1561
+ )
1562
+ webGLReplayRuntime = createSessionReplayWebGLRuntimeImpl(
1563
+ configuration,
1564
+ baseCanvasEncodeBridge,
1565
+ reportWebGLReplayFailure
1566
+ )
1567
+ canvasEncodeBridge = webGLReplayRuntime[0] || baseCanvasEncodeBridge
1568
+ } catch (error) {
1569
+ if (baseCanvasEncodeBridge && baseCanvasEncodeBridge.stop) {
1570
+ baseCanvasEncodeBridge.stop()
1571
+ }
1572
+ return abortRecorderInitialization(
1573
+ 'recorder_initialization_error',
1574
+ error
1575
+ )
1576
+ }
1577
+ registerInitializationCleanup(canvasEncodeBridge.stop)
1578
+
1579
+ var canvasObserver
1580
+ try {
1581
+ var createCanvasObserverImpl = __BUILD_ENV__REPLAY_DEBUG_ENABLED__
1582
+ ? options.createCanvasObserver || createCanvasObserver
1583
+ : createCanvasObserver
1584
+ canvasObserver = createCanvasObserverImpl({
1585
+ configuration: configuration,
1586
+ emit: emit,
1587
+ encodeBridge: canvasEncodeBridge,
1588
+ isNodeActive: function (node) {
1589
+ return !isNodeIgnored(node)
1590
+ },
1591
+ flushMutations: function (canvas) {
1592
+ return flushMutationRootForNode(canvas)
1593
+ },
1594
+ onMutationDebug: __BUILD_ENV__REPLAY_DEBUG_ENABLED__
1595
+ ? handleCanvasMutationDebug
1596
+ : undefined
1597
+ })
1598
+ } catch (error) {
1599
+ return abortRecorderInitialization(
1600
+ 'recorder_initialization_error',
1601
+ error
1602
+ )
1603
+ }
1604
+ registerInitializationCleanup(canvasObserver.stop)
1605
+ var startCanvasSnapshotLoop = __BUILD_ENV__REPLAY_DEBUG_ENABLED__
1606
+ ? options.startContinuousCanvasSnapshotLoop ||
1607
+ startContinuousCanvasSnapshotLoop
1608
+ : startContinuousCanvasSnapshotLoop
1609
+ var canvasSnapshotLoop
1610
+ try {
1611
+ canvasSnapshotLoop = shouldUseCanvasCommandCapture
1612
+ ? {
1613
+ stop: function () {},
1614
+ reset: function () {}
1615
+ }
1616
+ : startCanvasSnapshotLoop({
1617
+ configuration: configuration,
1618
+ getCanvases: function (maxScanCount) {
1619
+ return getActiveSerializedCanvases(maxScanCount).filter(
1620
+ function (canvas) {
1621
+ return !isDrawDrivenWebGLCanvas(canvas)
1622
+ }
1623
+ )
1624
+ },
1625
+ getSerializedNodeId: function (canvas) {
1626
+ return getActiveSerializedNodeId(canvas)
1627
+ },
1628
+ onDebug: handleAutoCanvasSnapshotDebug,
1629
+ snapshotCanvas: function (canvas) {
1630
+ return snapshotCanvasIfActive(canvas, {
1631
+ trigger: 'auto',
1632
+ scheduler: 'continuous_snapshot'
1633
+ })
1634
+ }
1635
+ })
1636
+ } catch (error) {
1637
+ return abortRecorderInitialization(
1638
+ 'recorder_initialization_error',
1639
+ error
1640
+ )
1641
+ }
1642
+ registerInitializationCleanup(function () {
1643
+ stopCanvasSnapshots(canvasSnapshotLoop)
1644
+ })
1645
+
1646
+ var canvasCommandCapture
1647
+ try {
1648
+ var startCanvasCommandCaptureImpl =
1649
+ __BUILD_ENV__REPLAY_DEBUG_ENABLED__
1650
+ ? options.startCanvasCommandCapture || startCanvasCommandCapture
1651
+ : startCanvasCommandCapture
1652
+ canvasCommandCapture = startCanvasCommandCaptureImpl({
1653
+ configuration: configuration,
1654
+ emit: emit,
1655
+ snapshotCanvas: function (canvas, snapshotOptions) {
1656
+ return snapshotCanvasIfActive(canvas, snapshotOptions)
1657
+ },
1658
+ getCanvases: function (maxScanCount) {
1659
+ return getActiveSerializedCanvases(maxScanCount)
1660
+ },
1661
+ getSerializedNodeId: function (canvas) {
1662
+ return getActiveSerializedNodeId(canvas)
1663
+ },
1664
+ onDebug: handleAutoCanvasSnapshotDebug,
1665
+ onMutationDebug: __BUILD_ENV__REPLAY_DEBUG_ENABLED__
1666
+ ? handleCanvasMutationDebug
1667
+ : undefined,
1668
+ flushMutations: function (canvas) {
1669
+ return flushMutationRootForNode(canvas)
1670
+ },
1671
+ startPaused: true
1672
+ })
1673
+ } catch (error) {
1674
+ return abortRecorderInitialization(
1675
+ 'recorder_initialization_error',
1676
+ error
1677
+ )
1678
+ }
1679
+ var canvasWebGLSnapshotObserver = createNoopObserver()
1680
+ try {
1681
+ var startCanvasWebGLSnapshotObserver =
1682
+ (__BUILD_ENV__REPLAY_DEBUG_ENABLED__ &&
1683
+ options.startCanvasWebGLSnapshotObserver) ||
1684
+ webGLReplayRuntime[1]
1685
+ if (startCanvasWebGLSnapshotObserver) {
1686
+ canvasWebGLSnapshotObserver =
1687
+ startCanvasWebGLSnapshotObserver(
1688
+ function (canvas, snapshotOptions) {
1689
+ return snapshotCanvasIfActive(canvas, snapshotOptions)
1690
+ },
1691
+ function (canvas) {
1692
+ return getActiveSerializedNodeId(canvas)
1693
+ },
1694
+ handleAutoCanvasSnapshotDebug
1695
+ ) || createNoopObserver()
1696
+ }
1697
+ } catch (error) {
1698
+ addTelemetryDebug('Session Replay WebGL observer failed.', {
1699
+ error: String(error)
1700
+ })
1701
+ canvasWebGLSnapshotObserver = createNoopObserver()
1702
+ }
1703
+ registerInitializationCleanup(canvasWebGLSnapshotObserver.stop)
1704
+ // The optional WebGL plugin installs its bootstrap getContext wrapper from
1705
+ // plugin.onInit(), before command capture wraps the same prototype. Always
1706
+ // unwind command capture first so the WebGL observer can still recognize
1707
+ // and restore its own wrapper. Keep initialization rollback in the same
1708
+ // order (cleanup tasks run in reverse registration order).
1709
+ registerInitializationCleanup(canvasCommandCapture.stop)
1710
+
1711
+ function isDrawDrivenWebGLCanvas(canvas) {
1712
+ if (isWebGLReplayCanvas(canvas)) {
1713
+ return true
1714
+ }
1715
+ try {
1716
+ return !!canvasWebGLSnapshotObserver.isWebGLCanvas(canvas)
1717
+ } catch (_) {
1718
+ // A failing optional plugin must not block the ordinary 2D baseline.
1719
+ return false
1720
+ }
1721
+ }
1722
+
1723
+ function snapshotCanvasIfActive(canvas, snapshotOptions) {
1724
+ if (isNodeIgnored(canvas)) {
1725
+ return Promise.resolve({
1726
+ ok: false,
1727
+ reason: 'not_serialized'
1728
+ })
1729
+ }
1730
+ var isCommandBaselineSnapshot =
1731
+ snapshotOptions &&
1732
+ (snapshotOptions.scheduler === 'full_snapshot_baseline' ||
1733
+ (snapshotOptions.scheduler === 'command_capture' &&
1734
+ snapshotOptions.force === true))
1735
+ var snapshotConsistencyToken =
1736
+ shouldUseCanvasCommandCapture &&
1737
+ canvasCommandCapture &&
1738
+ canvasCommandCapture.createCanvasSnapshotBaselineToken
1739
+ ? canvasCommandCapture.createCanvasSnapshotBaselineToken(canvas)
1740
+ : undefined
1741
+ var baselineToken = isCommandBaselineSnapshot
1742
+ ? snapshotConsistencyToken
1743
+ : undefined
1744
+ var effectiveSnapshotOptions = snapshotOptions
1745
+ if (
1746
+ snapshotConsistencyToken &&
1747
+ canvasCommandCapture &&
1748
+ canvasCommandCapture.$rIsSnapshotBaselineCurrent
1749
+ ) {
1750
+ var originalIsCancelled =
1751
+ effectiveSnapshotOptions &&
1752
+ effectiveSnapshotOptions.$rIsCancelled
1753
+ effectiveSnapshotOptions = assign({}, effectiveSnapshotOptions, {
1754
+ $rIsCancelled: function () {
1755
+ if (typeof originalIsCancelled === 'function') {
1756
+ try {
1757
+ if (originalIsCancelled()) {
1758
+ return true
1759
+ }
1760
+ } catch (_) {
1761
+ return true
1762
+ }
1763
+ }
1764
+ try {
1765
+ return !canvasCommandCapture.$rIsSnapshotBaselineCurrent(
1766
+ canvas,
1767
+ snapshotConsistencyToken
1768
+ )
1769
+ } catch (_) {
1770
+ return true
1771
+ }
1772
+ }
1773
+ })
1774
+ }
1775
+ return Promise.resolve(
1776
+ canvasObserver.snapshot(canvas, effectiveSnapshotOptions)
1777
+ ).then(function (result) {
1778
+ if (
1779
+ result &&
1780
+ result.ok === true &&
1781
+ baselineToken &&
1782
+ canvasCommandCapture &&
1783
+ canvasCommandCapture.markCanvasSnapshotBaseline
1784
+ ) {
1785
+ canvasCommandCapture.markCanvasSnapshotBaseline(
1786
+ canvas,
1787
+ baselineToken,
1788
+ effectiveSnapshotOptions.reason ||
1789
+ effectiveSnapshotOptions.scheduler
1790
+ )
1791
+ }
1792
+ return result
1793
+ })
1794
+ }
1795
+
1796
+ function createFullSnapshotSerializerTask(serializationContext) {
1797
+ var publicationToken = currentFullSnapshotPublicationToken
1798
+ var createSerializerTask =
1799
+ (__BUILD_ENV__REPLAY_DEBUG_ENABLED__ &&
1800
+ options.$rCreateFullSnapshotSerializerTask) ||
1801
+ createMutationSerializerTask
1802
+ return createSerializerTask(document, {
1803
+ serializationContext: serializationContext,
1804
+ parentNodePrivacyLevel: configuration.defaultPrivacyLevel,
1805
+ configuration: configuration,
1806
+ onSerializedNode: function (node, parentNode) {
1807
+ stageFullSnapshotNodePublication(
1808
+ node,
1809
+ parentNode,
1810
+ publicationToken
1811
+ )
1812
+ }
1813
+ })
1814
+ }
1815
+
1816
+ function advanceFullSnapshotSerializerTask(
1817
+ serializerTask,
1818
+ deadline
1819
+ ) {
1820
+ var maxNodeCount = Math.min(
1821
+ serializerTask.processedNodeCount + SERIALIZATION_MAX_NODE_COUNT,
1822
+ FULL_SNAPSHOT_SERIALIZATION_MAX_NODE_COUNT
1823
+ )
1824
+ var maxApproxBytes = Math.min(
1825
+ serializerTask.approxBytes + SERIALIZATION_MAX_APPROX_BYTES,
1826
+ FULL_SNAPSHOT_SERIALIZATION_MAX_APPROX_BYTES
1827
+ )
1828
+ var completed = serializerTask.advance(
1829
+ deadline,
1830
+ maxNodeCount,
1831
+ maxApproxBytes
1832
+ )
1833
+ return {
1834
+ completed: completed,
1835
+ isWatermarkReached:
1836
+ !completed &&
1837
+ (serializerTask.isMaxDepthReached ||
1838
+ serializerTask.isMaxNodeComplexityReached ||
1839
+ (serializerTask.isMaxNodeCountReached &&
1840
+ maxNodeCount >= FULL_SNAPSHOT_SERIALIZATION_MAX_NODE_COUNT) ||
1841
+ (serializerTask.isMaxApproxBytesReached &&
1842
+ maxApproxBytes >=
1843
+ FULL_SNAPSHOT_SERIALIZATION_MAX_APPROX_BYTES))
1844
+ }
1845
+ }
1846
+
1847
+ function createFullSnapshotBaselineRecords(timestamp, serializedDocument) {
1848
+ var _viewportDimension = getViewportDimension()
1849
+ var width = _viewportDimension.width
1850
+ var height = _viewportDimension.height
1851
+ return [
1852
+ {
1853
+ data: {
1854
+ height: height,
1855
+ href: window.location.href,
1856
+ width: width
1857
+ },
1858
+ type: RecordType.Meta,
1859
+ timestamp: timestamp
1860
+ },
1861
+ {
1862
+ data: {
1863
+ has_focus: document.hasFocus()
1864
+ },
1865
+ type: RecordType.Focus,
1866
+ timestamp: timestamp
1867
+ },
1868
+ {
1869
+ data: {
1870
+ node: serializedDocument,
1871
+ initialOffset: {
1872
+ left: getScrollX(),
1873
+ top: getScrollY()
1874
+ }
1875
+ },
1876
+ type: RecordType.FullSnapshot,
1877
+ timestamp: timestamp
1878
+ }
1879
+ ]
1880
+ }
1881
+
1882
+ function emitFullSnapshot(baselineRecords, startedAt) {
1883
+ // Baseline admission bypasses emit(). Do not inherit a local DOM-barrier
1884
+ // result from an earlier record: only the segment/encoder result for this
1885
+ // exact baseline may classify its rejection as transient backpressure.
1886
+ lastEmitWasLocallyBackpressured = false
1887
+ var timestamp = baselineRecords[0].timestamp
1888
+ var fullSnapshotAccepted
1889
+ if (rawEmitBaseline) {
1890
+ fullSnapshotAccepted = rawEmitBaseline(baselineRecords) !== false
1891
+ } else {
1892
+ fullSnapshotAccepted =
1893
+ rawEmit(baselineRecords[0]) !== false &&
1894
+ rawEmit(baselineRecords[1]) !== false &&
1895
+ rawEmit(baselineRecords[2]) !== false
1896
+ }
1897
+ if (!fullSnapshotAccepted) {
1898
+ return false
1899
+ }
1900
+ fullSnapshotWasPublished = true
1901
+ currentFullSnapshotPublicationToken.$rPublished = true
1902
+
1903
+ if (window.visualViewport) {
1904
+ rawEmit({
1905
+ data: getVisualViewport(),
1906
+ type: RecordType.VisualViewport,
1907
+ timestamp: timestamp
1908
+ })
1909
+ }
1910
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
1911
+ updateReplayPerformanceStats({
1912
+ fullSnapshotCount: 1,
1913
+ fullSnapshotDuration: getPerformanceTime() - startedAt
1914
+ })
1915
+ }
1916
+ return true
1917
+ }
1918
+
1919
+ function invalidateFullSnapshotCanvasBaseline() {
1920
+ fullSnapshotCanvasBaselineGeneration += 1
1921
+ }
1922
+
1923
+ function scanExistingCommandCaptureCanvases() {
1924
+ try {
1925
+ if (canvasCommandCapture.scanExistingCanvases) {
1926
+ canvasCommandCapture.scanExistingCanvases()
1927
+ }
1928
+ } catch (error) {
1929
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
1930
+ addTelemetryDebug('Session Replay canvas baseline scan failed.', {
1931
+ error: String(error)
1932
+ })
1933
+ }
1934
+ }
1935
+ }
1936
+
1937
+ function takeFullSnapshotCanvasBaseline() {
1938
+ if (
1939
+ !configuration.replayCanvasEnabled ||
1940
+ configuration.replayCanvasMode !== 'auto'
1941
+ ) {
1942
+ scanExistingCommandCaptureCanvases()
1943
+ return
1944
+ }
1945
+
1946
+ var baselineGeneration = fullSnapshotCanvasBaselineGeneration + 1
1947
+ fullSnapshotCanvasBaselineGeneration = baselineGeneration
1948
+ var baselineStartedAt = getPerformanceTime()
1949
+ // The registry is already bounded and contains only canvases assigned an id
1950
+ // by the successful full snapshot. Do not inspect or create a target
1951
+ // context here. Static 2D/unknown canvases get a bitmap baseline, while a
1952
+ // known WebGL canvas must wait for its next real draw: staging it from this
1953
+ // asynchronous baseline task is unsafe with preserveDrawingBuffer=false.
1954
+ var canvases
1955
+ try {
1956
+ canvases = filterActiveSerializedCanvases(
1957
+ getSerializedCanvasNodesSnapshot(
1958
+ MAX_FULL_SNAPSHOT_CANVAS_BASELINE_COUNT
1959
+ )
1960
+ ).filter(function (canvas) {
1961
+ return !isDrawDrivenWebGLCanvas(canvas)
1962
+ })
1963
+ } catch (error) {
1964
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
1965
+ addTelemetryDebug('Session Replay canvas baseline lookup failed.', {
1966
+ error: String(error)
1967
+ })
1968
+ }
1969
+ scanExistingCommandCaptureCanvases()
1970
+ return
1971
+ }
1972
+ var canvasIndex = 0
1973
+
1974
+ function runNextCanvasBaseline() {
1975
+ if (
1976
+ recordStopping ||
1977
+ recordStopped ||
1978
+ baselineGeneration !== fullSnapshotCanvasBaselineGeneration
1979
+ ) {
1980
+ return Promise.resolve()
1981
+ }
1982
+ if (canvasIndex >= canvases.length) {
1983
+ scanExistingCommandCaptureCanvases()
1984
+ return Promise.resolve()
1985
+ }
1986
+
1987
+ var canvas = canvases[canvasIndex]
1988
+ canvasIndex += 1
1989
+ var remainingBaselineTime =
1990
+ FULL_SNAPSHOT_CANVAS_BASELINE_TOTAL_TIMEOUT_MS -
1991
+ (getPerformanceTime() - baselineStartedAt)
1992
+ if (remainingBaselineTime <= 0) {
1993
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
1994
+ addTelemetryDebug('Session Replay canvas baseline budget exhausted.', {
1995
+ canvasCount: canvases.length,
1996
+ completedCanvasCount: canvasIndex - 1
1997
+ })
1998
+ }
1999
+ scanExistingCommandCaptureCanvases()
2000
+ return Promise.resolve()
2001
+ }
2002
+ var canvasBaselineCancelled = false
2003
+ var snapshotResult
2004
+ try {
2005
+ snapshotResult = snapshotCanvasIfActive(canvas, {
2006
+ trigger: 'auto',
2007
+ scheduler: 'full_snapshot_baseline',
2008
+ $rIsCancelled: function () {
2009
+ return (
2010
+ canvasBaselineCancelled ||
2011
+ recordStopping ||
2012
+ recordStopped ||
2013
+ baselineGeneration !== fullSnapshotCanvasBaselineGeneration
2014
+ )
2015
+ }
2016
+ })
2017
+ } catch (_) {
2018
+ snapshotResult = undefined
2019
+ }
2020
+ var canvasBaselineTimeoutId
2021
+ var canvasBaselineTimeout = new Promise(function (resolve) {
2022
+ canvasBaselineTimeoutId = setTimeout(function () {
2023
+ canvasBaselineTimeoutId = undefined
2024
+ canvasBaselineCancelled = true
2025
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
2026
+ addTelemetryDebug('Session Replay canvas baseline timed out.', {
2027
+ canvasIndex: canvasIndex,
2028
+ canvasCount: canvases.length
2029
+ })
2030
+ }
2031
+ resolve()
2032
+ }, Math.min(
2033
+ FULL_SNAPSHOT_CANVAS_BASELINE_ITEM_TIMEOUT_MS,
2034
+ remainingBaselineTime
2035
+ ))
2036
+ })
2037
+ return Promise.race([
2038
+ Promise.resolve(snapshotResult).catch(function () {}),
2039
+ canvasBaselineTimeout
2040
+ ]).then(function () {
2041
+ if (canvasBaselineTimeoutId !== undefined) {
2042
+ clearTimeout(canvasBaselineTimeoutId)
2043
+ }
2044
+ return runNextCanvasBaseline()
2045
+ })
2046
+ }
2047
+
2048
+ // Invoke the first item synchronously so the baseline gets the first
2049
+ // encode slot after the full snapshot. Remaining canvases are strictly
2050
+ // serial and failures never turn a valid DOM full snapshot into a failure.
2051
+ runNextCanvasBaseline()
2052
+ }
2053
+
2054
+ var takeInitialFullSnapshot = function (timestamp, serializationContext) {
2055
+ var fullSnapshotStartedAt = getPerformanceTime()
2056
+ if (typeof timestamp === 'undefined') {
2057
+ timestamp = timeStampNow()
2058
+ }
2059
+ if (typeof serializationContext === 'undefined') {
2060
+ serializationContext = {
2061
+ status: SerializationContextStatus.INITIAL_FULL_SNAPSHOT,
2062
+ elementsScrollPositions: elementsScrollPositions,
2063
+ shadowRootsController: shadowRootsController
2064
+ }
2065
+ }
2066
+ var serializerTask = createFullSnapshotSerializerTask(
2067
+ serializationContext
2068
+ )
2069
+ if (!serializerTask) {
2070
+ return {
2071
+ status: 'failed',
2072
+ reason: 'initial_full_snapshot_serialization_error'
2073
+ }
2074
+ }
2075
+ var advanceResult = advanceFullSnapshotSerializerTask(
2076
+ serializerTask,
2077
+ getPerformanceTime() + INITIAL_FULL_SNAPSHOT_SERIALIZATION_SLICE_MS
2078
+ )
2079
+ if (advanceResult.isWatermarkReached) {
2080
+ return {
2081
+ status: 'failed',
2082
+ reason: 'initial_full_snapshot_serialization_watermark'
2083
+ }
2084
+ }
2085
+ if (!advanceResult.completed) {
2086
+ return {
2087
+ status: 'pending',
2088
+ timestamp: timestamp
2089
+ }
2090
+ }
2091
+ var baselineRecords = createFullSnapshotBaselineRecords(
2092
+ timestamp,
2093
+ serializerTask.serializedNode
2094
+ )
2095
+ if (emitFullSnapshot(baselineRecords, fullSnapshotStartedAt)) {
2096
+ return { status: 'completed' }
2097
+ }
2098
+ if (wasLastEmitBackpressured()) {
2099
+ pendingFullSnapshotTimestamp = timestamp
2100
+ pendingFullSnapshotStartedAt = fullSnapshotStartedAt
2101
+ pendingFullSnapshotIsInitial = true
2102
+ pendingFullSnapshotBaselineRecords = baselineRecords
2103
+ pendingFullSnapshotBaselineMutationVersion = domMutationVersion
2104
+ suppressRecordsUntilFullSnapshot = true
2105
+ return { status: 'admission_pending', timestamp: timestamp }
2106
+ }
2107
+ return {
2108
+ status: 'failed',
2109
+ reason: 'initial_full_snapshot_admission_rejected'
2110
+ }
2111
+ }
2112
+
2113
+ var initialFullSnapshotResult
2114
+ try {
2115
+ initialFullSnapshotResult = takeInitialFullSnapshot()
2116
+ } catch (error) {
2117
+ return abortRecorderInitialization(
2118
+ 'recorder_initialization_error',
2119
+ error
2120
+ )
2121
+ }
2122
+ if (initialFullSnapshotResult.status === 'completed') {
2123
+ takeFullSnapshotCanvasBaseline()
2124
+ } else if (initialFullSnapshotResult.status === 'failed') {
2125
+ return abortRecorderInitialization(
2126
+ initialFullSnapshotResult.reason
2127
+ )
2128
+ } else if (initialFullSnapshotResult.status === 'pending') {
2129
+ // The first short attempt ran before MutationObservers existed. Restart
2130
+ // from a clean tree after observers are attached, so changes made between
2131
+ // slices cannot produce a mixed-time initial baseline.
2132
+ resetPublishedReplayTree()
2133
+ }
2134
+ var _initObservers
2135
+ try {
2136
+ var initObserversImpl = __BUILD_ENV__REPLAY_DEBUG_ENABLED__
2137
+ ? options.initObservers || initObservers
2138
+ : initObservers
2139
+ _initObservers = initObserversImpl({
2140
+ lifeCycle: options.lifeCycle,
2141
+ configuration: configuration,
2142
+ elementsScrollPositions: elementsScrollPositions,
2143
+ inputCb: inputCb,
2144
+ mediaInteractionCb: function (p) {
2145
+ emit(
2146
+ assembleIncrementalSnapshot(IncrementalSource.MediaInteraction, p)
2147
+ )
2148
+ },
2149
+ mouseInteractionCb: function (mouseInteractionRecord) {
2150
+ emit(mouseInteractionRecord)
2151
+ },
2152
+ mousemoveCb: function (positions, source) {
2153
+ emit(assembleIncrementalSnapshot(source, { positions: positions }))
2154
+ },
2155
+ mutationCb: mutationCb,
2156
+ mutationPerfCb: updateReplayPerformanceStats,
2157
+ mutationOverflowCb: requestFullSnapshotAfterMutationDrop,
2158
+ mutationActivityCb: trackDomMutationActivity,
2159
+ mutationNodeSerializationCb: stageMutationNodePublication,
2160
+ mutationResourceBudget: mutationResourceBudget,
2161
+ isNodeIgnored: isNodeIgnoredForObserver,
2162
+ isNodeIgnoredForStatelessObserver:
2163
+ isNodeIgnoredForStatelessObserver,
2164
+ isNodePublished: isNodeQueuedOrPublished,
2165
+ scrollCb: function (p) {
2166
+ emit(assembleIncrementalSnapshot(IncrementalSource.Scroll, p))
2167
+ },
2168
+ styleSheetCb: function (r) {
2169
+ // The shared state-record admission path distinguishes transient
2170
+ // backpressure from a permanent CSSOM gap and starts exactly one
2171
+ // replacement baseline for the latter.
2172
+ emit(
2173
+ assembleIncrementalSnapshot(
2174
+ IncrementalSource.StyleSheetRule,
2175
+ r
2176
+ )
2177
+ )
2178
+ },
2179
+ viewportResizeCb: function (d) {
2180
+ emit(
2181
+ assembleIncrementalSnapshot(IncrementalSource.ViewportResize, d)
2182
+ )
2183
+ },
2184
+ frustrationCb: function (frustrationRecord) {
2185
+ emit(frustrationRecord)
2186
+ },
2187
+ focusCb: function (data) {
2188
+ emit({
2189
+ data: data,
2190
+ type: RecordType.Focus,
2191
+ timestamp: timeStampNow()
2192
+ })
2193
+ },
2194
+ visualViewportResizeCb: function (data) {
2195
+ emit({
2196
+ data: data,
2197
+ type: RecordType.VisualViewport,
2198
+ timestamp: timeStampNow()
2199
+ })
2200
+ },
2201
+ shadowRootsController: shadowRootsController
2202
+ })
2203
+ } catch (error) {
2204
+ return abortRecorderInitialization(
2205
+ 'recorder_initialization_error',
2206
+ error
2207
+ )
2208
+ }
2209
+ registerInitializationCleanup(_initObservers.stop)
2210
+ refreshAndFlushPendingRootForNode =
2211
+ _initObservers.refreshAndFlushPendingRootForNode ||
2212
+ function () {}
2213
+ var stopObservers = _initObservers.stop
2214
+ var flushMutationsFromObservers = _initObservers.flush
2215
+ var resetMutationsFromObservers = _initObservers.reset || function () {}
2216
+ initializationCleanupTasks = []
2217
+ if (
2218
+ initialFullSnapshotResult.status === 'pending' &&
2219
+ !beginInitialFullSnapshot(initialFullSnapshotResult.timestamp)
2220
+ ) {
2221
+ return createInactiveRecorder()
2222
+ }
2223
+ if (initialFullSnapshotResult.status === 'admission_pending') {
2224
+ schedulePendingFullSnapshotSlice(MUTATION_ADMISSION_RETRY_DELAY_MS)
2225
+ }
2226
+
2227
+ function requestFullSnapshotAfterMutationDrop(overflow) {
2228
+ if (recordStopping || recordStopped) {
2229
+ return
2230
+ }
2231
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
2232
+ replayPerformanceStats.mutationDropRecoveryCount += 1
2233
+ replayPerformanceStats.mutationDropRecoveryLastReason =
2234
+ overflow && overflow.reason
2235
+ ? overflow.reason
2236
+ : 'unknown'
2237
+ }
2238
+ // Any dropped mutation makes the live DOM diverge from the last uploaded
2239
+ // baseline, even when the missing record only contains text or attributes.
2240
+ // The replacement snapshot must therefore complete. If it cannot fit the
2241
+ // bounded serializer/segment budgets, stop and discard the held tail
2242
+ // instead of restoring a tree that is known to be stale.
2243
+ flushPendingMutations()
2244
+ // Keep a safely admitted prefix, but retire the complete pre-transaction
2245
+ // deferred tail. Even an unbound Scroll/Canvas record can roll state back
2246
+ // if it is replayed after the replacement baseline. Only records produced
2247
+ // after the mandatory transaction starts may follow that baseline.
2248
+ discardPendingMutationPayload()
2249
+ discardPendingMutationAdmissions()
2250
+ clearDeferredRecords()
2251
+ scheduleMandatoryFullSnapshotAfterMutationDrop()
2252
+ }
2253
+
2254
+ function beginAdmissionGapRecovery(reason) {
2255
+ if (recordStopping || recordStopped) {
2256
+ return
2257
+ }
2258
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
2259
+ replayPerformanceStats.admissionGapRecoveryCount += 1
2260
+ replayPerformanceStats.admissionGapRecoveryLastReason =
2261
+ reason || 'unknown'
2262
+ }
2263
+ // A deferred CSSOM/Canvas state rejection can leave later DOM admissions
2264
+ // queued. Never pre-flush after that gap: the replacement baseline must
2265
+ // supersede the complete local admission window before any tail escapes.
2266
+ discardPendingMutationPayload()
2267
+ discardPendingMutationAdmissions()
2268
+ clearDeferredRecords()
2269
+ scheduleMandatoryFullSnapshotAfterMutationDrop()
2270
+ }
2271
+
2272
+ function scheduleMandatoryFullSnapshotAfterMutationDrop() {
2273
+ scheduleSubsequentFullSnapshot(
2274
+ timeStampNow(),
2275
+ false,
2276
+ true
2277
+ )
2278
+ }
2279
+ function flushMutations(forceBoundaryDrain) {
2280
+ var boundaryDeadline = forceBoundaryDrain
2281
+ ? getPerformanceTime() +
2282
+ MUTATION_SOURCE_BOUNDARY_FLUSH_BUDGET_MS
2283
+ : undefined
2284
+ mutationSourceFlushInProgress = true
2285
+ try {
2286
+ var shadowFlushResult = true
2287
+ if (!mutationFlushDocumentPending) {
2288
+ do {
2289
+ shadowFlushResult = shadowRootsController.flush()
2290
+ } while (
2291
+ shadowFlushResult === 'pending' &&
2292
+ forceBoundaryDrain &&
2293
+ getPerformanceTime() < boundaryDeadline
2294
+ )
2295
+ }
2296
+ if (shadowFlushResult === 'pending') {
2297
+ scheduleMutationSourceFlushContinuation()
2298
+ return 'pending'
2299
+ }
2300
+ if (shadowFlushResult === false) {
2301
+ resetMutationsFromObservers()
2302
+ discardPendingMutationPayload()
2303
+ return false
2304
+ }
2305
+ mutationFlushDocumentPending = true
2306
+ var documentFlushResult
2307
+ do {
2308
+ documentFlushResult = flushMutationsFromObservers()
2309
+ } while (
2310
+ documentFlushResult === 'pending' &&
2311
+ forceBoundaryDrain &&
2312
+ getPerformanceTime() < boundaryDeadline
2313
+ )
2314
+ if (documentFlushResult === 'pending') {
2315
+ scheduleMutationSourceFlushContinuation()
2316
+ return 'pending'
2317
+ }
2318
+ if (documentFlushResult === false) {
2319
+ mutationFlushDocumentPending = false
2320
+ resetMutationsFromObservers()
2321
+ if (shadowRootsController.reset) {
2322
+ shadowRootsController.reset()
2323
+ }
2324
+ discardPendingMutationPayload()
2325
+ return false
2326
+ }
2327
+ } finally {
2328
+ mutationSourceFlushInProgress = false
2329
+ }
2330
+ mutationFlushDocumentPending = false
2331
+ flushPendingMutations()
2332
+ return true
2333
+ }
2334
+
2335
+ function capturePendingMutationActivityForPreviousReplayTree(
2336
+ includeShadowRoots
2337
+ ) {
2338
+ if (
2339
+ !captureRecordsAgainstPreviousReplayTree ||
2340
+ mutationSourceFlushInProgress
2341
+ ) {
2342
+ return
2343
+ }
2344
+ var resetShadowMutationsForBaseline = includeShadowRoots
2345
+ ? shadowRootsController.$rResetPendingMutationsForBaseline
2346
+ : undefined
2347
+ if (resetShadowMutationsForBaseline) {
2348
+ var shadowResetResult = resetShadowMutationsForBaseline()
2349
+ if (shadowResetResult !== true) {
2350
+ // Do not synchronously walk an arbitrary number of roots from an input
2351
+ // handler. An incomplete reset means the optional candidate is no
2352
+ // longer safe to abandon; the rebuilt baseline will absorb the live
2353
+ // DOM.
2354
+ pendingFullSnapshotCanBeDiscarded = false
2355
+ pendingFullSnapshotRestartRequested = true
2356
+ pendingFullSnapshotTimestamp = Math.max(
2357
+ typeof pendingFullSnapshotTimestamp === 'number'
2358
+ ? pendingFullSnapshotTimestamp
2359
+ : 0,
2360
+ timeStampNow()
2361
+ )
2362
+ }
2363
+ }
2364
+ resetMutationsFromObservers()
2365
+ discardPendingMutationPayload()
2366
+ }
2367
+
2368
+ function scheduleMutationSourceFlushContinuation() {
2369
+ if (
2370
+ mutationSourceFlushContinuationTimeout !== undefined ||
2371
+ recordStopping ||
2372
+ recordStopped
2373
+ ) {
2374
+ return
2375
+ }
2376
+ mutationSourceFlushContinuationTimeout = setTimeout(function () {
2377
+ mutationSourceFlushContinuationTimeout = undefined
2378
+ flushMutations()
2379
+ }, 0)
2380
+ }
2381
+
2382
+ function cancelMutationSourceFlushContinuation() {
2383
+ if (mutationSourceFlushContinuationTimeout !== undefined) {
2384
+ clearTimeout(mutationSourceFlushContinuationTimeout)
2385
+ mutationSourceFlushContinuationTimeout = undefined
2386
+ }
2387
+ mutationFlushDocumentPending = false
2388
+ }
2389
+
2390
+ function flushMutationRootForNode(node) {
2391
+ if (!node || !flushMutationsFromObservers) {
2392
+ return
2393
+ }
2394
+ mutationSourceFlushInProgress = true
2395
+ var flushResult
2396
+ try {
2397
+ flushResult = refreshAndFlushPendingRootForNode(node)
2398
+ if (
2399
+ typeof flushResult === 'undefined' &&
2400
+ shadowRootsController.refreshAndFlushPendingRootForNode
2401
+ ) {
2402
+ flushResult =
2403
+ shadowRootsController.refreshAndFlushPendingRootForNode(node)
2404
+ }
2405
+ } finally {
2406
+ mutationSourceFlushInProgress = false
2407
+ }
2408
+ if (flushResult === false) {
2409
+ return false
2410
+ }
2411
+ flushPendingMutations()
2412
+ return (
2413
+ !pendingMutationAdmissionQueue.length &&
2414
+ !suppressRecordsUntilFullSnapshot &&
2415
+ !recordStopped
2416
+ )
2417
+ }
2418
+
2419
+ function discardPendingMutationPayload() {
2420
+ if (pendingMutationTimeout) {
2421
+ clearTimeout(pendingMutationTimeout)
2422
+ pendingMutationTimeout = undefined
2423
+ }
2424
+ if (pendingMutationPayload) {
2425
+ discardMutationMembership(
2426
+ materializeMutationPayload(pendingMutationPayload)
2427
+ )
2428
+ }
2429
+ pendingMutationPayload = undefined
2430
+ }
2431
+
2432
+ function prepareMutationBaseline(preserveShadowRootObservers) {
2433
+ // A full snapshot supersedes mutation work that has not been emitted yet.
2434
+ // Do not force-drain time-sliced serializers immediately before traversing
2435
+ // the complete document.
2436
+ cancelMutationSourceFlushContinuation()
2437
+ flushPendingMutations()
2438
+ discardPendingMutationAdmissions()
2439
+ resetMutationsFromObservers()
2440
+ if (
2441
+ !preserveShadowRootObservers &&
2442
+ shadowRootsController.reset
2443
+ ) {
2444
+ shadowRootsController.reset()
2445
+ }
2446
+ mutationResourceBudget.reset()
2447
+ discardPendingMutationPayload()
2448
+ resetPublishedReplayTree()
2449
+ }
2450
+
2451
+ function prepareForViewChange() {
2452
+ // View boundaries retire every event ordered against the old replay tree.
2453
+ // Internal baseline retries preserve records captured during serialization,
2454
+ // so keep this clearing behavior on the public view transition only.
2455
+ // Give a paged raw/shadow transaction one final bounded drain before the
2456
+ // old tree is retired. If it is still pending, prepareMutationBaseline()
2457
+ // drops the complete uncommitted transaction; VIEW_CREATED then publishes
2458
+ // the replacement baseline instead of exposing a half-applied move.
2459
+ var flushResult = flushMutations(true)
2460
+ if (flushResult === 'pending') {
2461
+ addTelemetryDebug(
2462
+ 'Session Replay dropped a pending mutation transaction at a view boundary.',
2463
+ { reason: 'view_boundary_mutation_tail_pending' }
2464
+ )
2465
+ }
2466
+ clearDeferredRecords()
2467
+ prepareMutationBaseline()
2468
+ return flushResult
2469
+ }
2470
+
2471
+ function resetCanvasRecordingBaseline() {
2472
+ invalidateFullSnapshotCanvasBaseline()
2473
+ if (canvasObserver.reset) {
2474
+ canvasObserver.reset()
2475
+ }
2476
+ if (canvasWebGLSnapshotObserver.reset) {
2477
+ canvasWebGLSnapshotObserver.reset()
2478
+ }
2479
+ if (canvasCommandCapture.reset) {
2480
+ canvasCommandCapture.reset()
2481
+ }
2482
+ resetCanvasSnapshots(canvasSnapshotLoop)
2483
+ }
2484
+
2485
+ function prepareForFullSnapshot() {
2486
+ // While the previous replay tail remains valid, keep its ShadowRoot
2487
+ // observers alive until the candidate baseline commits or abandons. This
2488
+ // closes the same-task window where a shadow mutation could otherwise
2489
+ // happen after begin() but before the serializer re-registers the root.
2490
+ prepareMutationBaseline(
2491
+ captureRecordsAgainstPreviousReplayTree &&
2492
+ pendingFullSnapshotCanBeDiscarded
2493
+ )
2494
+ resetCanvasRecordingBaseline()
2495
+ }
2496
+
2497
+ function clearPendingFullSnapshotTimeout() {
2498
+ if (pendingFullSnapshotTimeout !== undefined) {
2499
+ clearTimeout(pendingFullSnapshotTimeout)
2500
+ pendingFullSnapshotTimeout = undefined
2501
+ }
2502
+ }
2503
+
2504
+ function cancelScheduledFullSnapshot() {
2505
+ clearPendingFullSnapshotTimeout()
2506
+ pendingFullSnapshotTimestamp = undefined
2507
+ pendingFullSnapshotCanBeDiscarded = false
2508
+ pendingFullSnapshotRequiresTailDiscard = false
2509
+ pendingFullSnapshotTask = undefined
2510
+ pendingFullSnapshotMutationVersion = undefined
2511
+ pendingFullSnapshotStartedAt = undefined
2512
+ pendingFullSnapshotActiveDuration = 0
2513
+ pendingFullSnapshotRestartCount = 0
2514
+ pendingFullSnapshotRestartRequested = false
2515
+ pendingFullSnapshotSynchronousFallbackAttempted = false
2516
+ pendingFullSnapshotIsInitial = false
2517
+ pendingFullSnapshotBaselineRecords = undefined
2518
+ pendingFullSnapshotBaselineMutationVersion = undefined
2519
+ }
2520
+
2521
+ function clearDeferredRecords() {
2522
+ if (deferredRecordAdmissionTimeout !== undefined) {
2523
+ clearTimeout(deferredRecordAdmissionTimeout)
2524
+ deferredRecordAdmissionTimeout = undefined
2525
+ }
2526
+ deferredRecords = []
2527
+ deferredRecordsApproxBytes = 0
2528
+ }
2529
+
2530
+ function isDeferredRecordAfterFullSnapshot(entry, timestamp) {
2531
+ return Boolean(
2532
+ entry &&
2533
+ entry.$rRecord &&
2534
+ typeof entry.$rRecord.timestamp === 'number' &&
2535
+ entry.$rRecord.timestamp > timestamp
2536
+ )
2537
+ }
2538
+
2539
+ function flushAndRetireDeferredRecordsBeforeFullSnapshot(timestamp) {
2540
+ if (deferredRecordAdmissionTimeout !== undefined) {
2541
+ clearTimeout(deferredRecordAdmissionTimeout)
2542
+ deferredRecordAdmissionTimeout = undefined
2543
+ }
2544
+ if (!deferredRecords.length) {
2545
+ return false
2546
+ }
2547
+ var drainStartedAt = getPerformanceTime()
2548
+ var drainedApproxBytes = 0
2549
+ while (deferredRecords.length) {
2550
+ var entry = deferredRecords[0]
2551
+ if (isDeferredRecordAfterFullSnapshot(entry, timestamp)) {
2552
+ break
2553
+ }
2554
+ if (
2555
+ entry.$rMutationAdmissionBarrier &&
2556
+ entry.$rMutationAdmissionBarrier.$rPendingAdmission
2557
+ ) {
2558
+ break
2559
+ }
2560
+ if (rawEmit(entry.$rRecord) === false) {
2561
+ break
2562
+ }
2563
+ deferredRecords.shift()
2564
+ deferredRecordsApproxBytes -= entry.$rApproxBytes
2565
+ drainedApproxBytes += entry.$rApproxBytes
2566
+ if (
2567
+ drainedApproxBytes >=
2568
+ MUTATION_ADMISSION_DRAIN_SLICE_APPROX_BYTES ||
2569
+ getPerformanceTime() - drainStartedAt >=
2570
+ MUTATION_ADMISSION_DRAIN_SLICE_MS
2571
+ ) {
2572
+ break
2573
+ }
2574
+ }
2575
+ // A replacement baseline supersedes only records at or before its own
2576
+ // timestamp. Preserve a future-dated suffix captured inside the current
2577
+ // transaction so it can follow the replacement baseline. The bounded
2578
+ // prefix attempt avoids adding an unbounded encode loop to this boundary.
2579
+ var retainedDeferredRecords = []
2580
+ var retainedDeferredRecordsApproxBytes = 0
2581
+ var retiredStatefulRecord = false
2582
+ deferredRecords.forEach(function (entry) {
2583
+ if (isDeferredRecordAfterFullSnapshot(entry, timestamp)) {
2584
+ retainedDeferredRecords.push(entry)
2585
+ retainedDeferredRecordsApproxBytes += entry.$rApproxBytes
2586
+ } else if (isStatefulDeferredRecord(entry.$rRecord)) {
2587
+ retiredStatefulRecord = true
2588
+ }
2589
+ })
2590
+ deferredRecords = retainedDeferredRecords
2591
+ deferredRecordsApproxBytes = retainedDeferredRecordsApproxBytes
2592
+ return retiredStatefulRecord
2593
+ }
2594
+
2595
+ function handleDeferredRecordLoss(record) {
2596
+ if (!isStatefulDeferredRecord(record)) {
2597
+ return
2598
+ }
2599
+ if (pendingFullSnapshotTask) {
2600
+ beginAdmissionGapRecovery('deferred_stateful_record_loss')
2601
+ return
2602
+ }
2603
+ beginAdmissionGapRecovery('deferred_stateful_record_loss')
2604
+ }
2605
+
2606
+ function scheduleDeferredRecordAdmissionRetry() {
2607
+ scheduleDeferredRecordAdmissionDrain(
2608
+ MUTATION_ADMISSION_RETRY_DELAY_MS
2609
+ )
2610
+ }
2611
+
2612
+ function scheduleDeferredRecordAdmissionContinuation() {
2613
+ scheduleDeferredRecordAdmissionDrain(0)
2614
+ }
2615
+
2616
+ function scheduleDeferredRecordAdmissionDrain(delay) {
2617
+ if (
2618
+ deferredRecordAdmissionTimeout !== undefined ||
2619
+ !deferredRecords.length ||
2620
+ recordStopping ||
2621
+ recordStopped
2622
+ ) {
2623
+ return
2624
+ }
2625
+ deferredRecordAdmissionTimeout = setTimeout(function () {
2626
+ deferredRecordAdmissionTimeout = undefined
2627
+ var mutationAdmissionBarrier = deferredRecords.length
2628
+ ? deferredRecords[0].$rMutationAdmissionBarrier
2629
+ : undefined
2630
+ var barrierWasDrained = flushDeferredRecords(
2631
+ mutationAdmissionBarrier
2632
+ )
2633
+ if (barrierWasDrained) {
2634
+ scheduleMutationAdmissionContinuation()
2635
+ }
2636
+ }, delay)
2637
+ }
2638
+
2639
+ function flushDeferredRecords(mutationAdmissionBarrier, drainState) {
2640
+ if (
2641
+ suppressRecordsUntilFullSnapshot ||
2642
+ recordStopped
2643
+ ) {
2644
+ return false
2645
+ }
2646
+ if (deferredRecordAdmissionTimeout !== undefined) {
2647
+ clearTimeout(deferredRecordAdmissionTimeout)
2648
+ deferredRecordAdmissionTimeout = undefined
2649
+ }
2650
+ drainState = drainState || {
2651
+ $rStartedAt: getPerformanceTime(),
2652
+ $rApproxBytes: 0
2653
+ }
2654
+ while (deferredRecords.length) {
2655
+ var entry = deferredRecords[0]
2656
+ if (
2657
+ entry.$rMutationAdmissionBarrier &&
2658
+ (entry.$rMutationAdmissionBarrier.$rPendingAdmission ||
2659
+ (mutationAdmissionBarrier &&
2660
+ entry.$rMutationAdmissionBarrier !==
2661
+ mutationAdmissionBarrier))
2662
+ ) {
2663
+ // A global/no-barrier drain may consume its unbound prefix, but a
2664
+ // state record for a still-pending DOM add must wait for mutation
2665
+ // admission. A concrete barrier drain likewise stops at the next
2666
+ // structural boundary.
2667
+ return true
2668
+ }
2669
+ if (rawEmit(entry.$rRecord) !== false) {
2670
+ deferredRecords.shift()
2671
+ deferredRecordsApproxBytes -= entry.$rApproxBytes
2672
+ drainState.$rApproxBytes += entry.$rApproxBytes
2673
+ if (
2674
+ deferredRecords.length &&
2675
+ (!mutationAdmissionBarrier ||
2676
+ !deferredRecords[0].$rMutationAdmissionBarrier ||
2677
+ deferredRecords[0].$rMutationAdmissionBarrier ===
2678
+ mutationAdmissionBarrier) &&
2679
+ (drainState.$rApproxBytes >=
2680
+ MUTATION_ADMISSION_DRAIN_SLICE_APPROX_BYTES ||
2681
+ getPerformanceTime() - drainState.$rStartedAt >=
2682
+ MUTATION_ADMISSION_DRAIN_SLICE_MS)
2683
+ ) {
2684
+ scheduleDeferredRecordAdmissionContinuation()
2685
+ return false
2686
+ }
2687
+ continue
2688
+ }
2689
+ if (
2690
+ options.$rWasLastEmitBackpressured &&
2691
+ options.$rWasLastEmitBackpressured()
2692
+ ) {
2693
+ scheduleDeferredRecordAdmissionRetry()
2694
+ return false
2695
+ }
2696
+ deferredRecords.shift()
2697
+ deferredRecordsApproxBytes -= entry.$rApproxBytes
2698
+ if (isStatefulDeferredRecord(entry.$rRecord)) {
2699
+ // Canvas commands and CSSOM rule indexes form ordered state chains.
2700
+ // A permanent gap cannot be skipped; supersede the remainder with a
2701
+ // fresh mandatory baseline instead.
2702
+ beginAdmissionGapRecovery('deferred_stateful_record_rejected')
2703
+ return false
2704
+ }
2705
+ }
2706
+ return true
2707
+ }
2708
+
2709
+ function restoreRecordingAfterAbandonedFullSnapshot(
2710
+ beforeShadowRootRollback
2711
+ ) {
2712
+ restorePreviousPublishedReplayTree()
2713
+ suppressRecordsUntilFullSnapshot = false
2714
+ if (beforeShadowRootRollback) {
2715
+ beforeShadowRootRollback()
2716
+ }
2717
+ if (shadowRootsController.$rRollbackRecovery) {
2718
+ shadowRootsController.$rRollbackRecovery()
2719
+ }
2720
+ // Bitmap snapshots produced while the replacement baseline was being
2721
+ // serialized were deferred and are discarded on abandon. The shared
2722
+ // Canvas observer may already have advanced its frame signature/data URL
2723
+ // baseline, so reset every scheduler before rescanning; otherwise the
2724
+ // unchanged frame would never be emitted after recording resumes.
2725
+ resetCanvasRecordingBaseline()
2726
+ scanExistingCommandCaptureCanvases()
2727
+ }
2728
+
2729
+ function beginInitialFullSnapshot(timestamp) {
2730
+ if (recordStopping || recordStopped) {
2731
+ return false
2732
+ }
2733
+ cancelScheduledFullSnapshot()
2734
+ pendingFullSnapshotTimestamp = timestamp
2735
+ pendingFullSnapshotStartedAt = getPerformanceTime()
2736
+ pendingFullSnapshotActiveDuration = 0
2737
+ pendingFullSnapshotRestartCount = 0
2738
+ pendingFullSnapshotRestartRequested = false
2739
+ pendingFullSnapshotIsInitial = true
2740
+ suppressRecordsUntilFullSnapshot = true
2741
+ try {
2742
+ prepareForFullSnapshot()
2743
+ createPendingFullSnapshotTask()
2744
+ } catch (error) {
2745
+ return handleFullSnapshotException(
2746
+ 'full_snapshot_initialization_error',
2747
+ error
2748
+ )
2749
+ }
2750
+ schedulePendingFullSnapshotSlice()
2751
+ return true
2752
+ }
2753
+
2754
+ function beginSubsequentFullSnapshot(
2755
+ timestamp,
2756
+ canBeDiscarded,
2757
+ requiresTailDiscard
2758
+ ) {
2759
+ if (recordStopping || recordStopped) {
2760
+ return false
2761
+ }
2762
+ var replacesPendingFullSnapshot =
2763
+ pendingFullSnapshotTimestamp !== undefined
2764
+ var previousTransactionTimestamp = pendingFullSnapshotTimestamp
2765
+ var fullSnapshotTimestamp =
2766
+ typeof timestamp === 'undefined' ? timeStampNow() : timestamp
2767
+ if (
2768
+ replacesPendingFullSnapshot &&
2769
+ typeof previousTransactionTimestamp === 'number'
2770
+ ) {
2771
+ fullSnapshotTimestamp = Math.max(
2772
+ fullSnapshotTimestamp,
2773
+ previousTransactionTimestamp
2774
+ )
2775
+ }
2776
+ if (typeof previousReplayTreeLastRecordTimestamp === 'number') {
2777
+ fullSnapshotTimestamp = Math.max(
2778
+ fullSnapshotTimestamp,
2779
+ previousReplayTreeLastRecordTimestamp
2780
+ )
2781
+ }
2782
+ var retiredStatefulRecord =
2783
+ flushAndRetireDeferredRecordsBeforeFullSnapshot(
2784
+ fullSnapshotTimestamp
2785
+ )
2786
+ cancelScheduledFullSnapshot()
2787
+ pendingFullSnapshotTimestamp = fullSnapshotTimestamp
2788
+ pendingFullSnapshotCanBeDiscarded =
2789
+ Boolean(canBeDiscarded) && !retiredStatefulRecord
2790
+ pendingFullSnapshotRequiresTailDiscard = Boolean(
2791
+ requiresTailDiscard
2792
+ )
2793
+ if (
2794
+ pendingFullSnapshotRequiresTailDiscard &&
2795
+ options.$rOnMandatoryFullSnapshotStarted
2796
+ ) {
2797
+ options.$rOnMandatoryFullSnapshotStarted()
2798
+ }
2799
+ pendingFullSnapshotStartedAt = getPerformanceTime()
2800
+ pendingFullSnapshotActiveDuration = 0
2801
+ pendingFullSnapshotRestartCount = 0
2802
+ pendingFullSnapshotRestartRequested = false
2803
+ pendingFullSnapshotIsInitial = !fullSnapshotWasPublished
2804
+ if (
2805
+ !replacesPendingFullSnapshot ||
2806
+ pendingFullSnapshotRequiresTailDiscard
2807
+ ) {
2808
+ resetPreviousReplayTreeRecords()
2809
+ }
2810
+ captureRecordsAgainstPreviousReplayTree =
2811
+ !pendingFullSnapshotIsInitial &&
2812
+ !pendingFullSnapshotRequiresTailDiscard
2813
+ previousReplayTreeAdmissionActive =
2814
+ captureRecordsAgainstPreviousReplayTree
2815
+ suppressRecordsUntilFullSnapshot = true
2816
+ if (!previousPublishedReplayTree) {
2817
+ previousPublishedReplayTree = getPublishedReplayTree()
2818
+ }
2819
+ try {
2820
+ if (
2821
+ !pendingFullSnapshotIsInitial &&
2822
+ shadowRootsController.$rBeginRecovery
2823
+ ) {
2824
+ shadowRootsController.$rBeginRecovery()
2825
+ }
2826
+ prepareForFullSnapshot()
2827
+ createPendingFullSnapshotTask()
2828
+ } catch (error) {
2829
+ return handleFullSnapshotException(
2830
+ 'full_snapshot_initialization_error',
2831
+ error
2832
+ )
2833
+ }
2834
+ return true
2835
+ }
2836
+
2837
+ function createPendingFullSnapshotTask() {
2838
+ if (pendingFullSnapshotIsInitial) {
2839
+ elementsScrollPositions.reset()
2840
+ }
2841
+ pendingFullSnapshotTask = createFullSnapshotSerializerTask({
2842
+ shadowRootsController: shadowRootsController,
2843
+ status: pendingFullSnapshotIsInitial
2844
+ ? SerializationContextStatus.INITIAL_FULL_SNAPSHOT
2845
+ : SerializationContextStatus.SUBSEQUENT_FULL_SNAPSHOT,
2846
+ elementsScrollPositions: elementsScrollPositions
2847
+ })
2848
+ if (!pendingFullSnapshotTask) {
2849
+ throw new Error('Full snapshot unavailable.')
2850
+ }
2851
+ pendingFullSnapshotMutationVersion = domMutationVersion
2852
+ }
2853
+
2854
+ function schedulePendingFullSnapshotSlice(delay) {
2855
+ if (
2856
+ recordStopping ||
2857
+ recordStopped ||
2858
+ pendingFullSnapshotTimeout !== undefined ||
2859
+ pendingFullSnapshotTimestamp === undefined
2860
+ ) {
2861
+ return
2862
+ }
2863
+ delay = delay || 0
2864
+ pendingFullSnapshotTimeout = setTimeout(function () {
2865
+ pendingFullSnapshotTimeout = undefined
2866
+ if (failPendingFullSnapshotOnTimeout()) {
2867
+ return
2868
+ }
2869
+ if (pendingFullSnapshotBaselineRecords) {
2870
+ runPendingFullSnapshotSliceSafely(true)
2871
+ return
2872
+ }
2873
+ if (!pendingFullSnapshotTask) {
2874
+ var completeSynchronously = false
2875
+ if (
2876
+ pendingFullSnapshotMutationVersion !== domMutationVersion
2877
+ ) {
2878
+ pendingFullSnapshotMutationVersion = domMutationVersion
2879
+ if (
2880
+ pendingFullSnapshotSynchronousFallbackAttempted ||
2881
+ getPerformanceTime() - pendingFullSnapshotStartedAt <
2882
+ FULL_SNAPSHOT_MAX_TOTAL_DURATION_MS
2883
+ ) {
2884
+ schedulePendingFullSnapshotSlice(delay)
2885
+ return
2886
+ }
2887
+ pendingFullSnapshotSynchronousFallbackAttempted = true
2888
+ completeSynchronously = true
2889
+ }
2890
+ try {
2891
+ prepareForFullSnapshot()
2892
+ clearDeferredRecords()
2893
+ createPendingFullSnapshotTask()
2894
+ } catch (error) {
2895
+ return handleFullSnapshotException(
2896
+ 'full_snapshot_initialization_error',
2897
+ error
2898
+ )
2899
+ }
2900
+ if (completeSynchronously) {
2901
+ var synchronousStartedAt = getPerformanceTime()
2902
+ var synchronousDeadline =
2903
+ synchronousStartedAt +
2904
+ FULL_SNAPSHOT_SYNCHRONOUS_FINALIZATION_BUDGET_MS
2905
+ var synchronousMaxSliceCount = Math.ceil(
2906
+ FULL_SNAPSHOT_SYNCHRONOUS_FINALIZATION_BUDGET_MS /
2907
+ FULL_SNAPSHOT_SERIALIZATION_SLICE_MS
2908
+ )
2909
+ var synchronousSliceCount = 0
2910
+ while (pendingFullSnapshotTask) {
2911
+ if (
2912
+ synchronousSliceCount >= synchronousMaxSliceCount ||
2913
+ getPerformanceTime() >= synchronousDeadline
2914
+ ) {
2915
+ deferPendingFullSnapshotUntilQuiet()
2916
+ return
2917
+ }
2918
+ synchronousSliceCount += 1
2919
+ if (
2920
+ runPendingFullSnapshotSliceSafely(
2921
+ false,
2922
+ synchronousDeadline
2923
+ )
2924
+ ) {
2925
+ return
2926
+ }
2927
+ if (pendingFullSnapshotBaselineRecords) {
2928
+ schedulePendingFullSnapshotSlice(
2929
+ MUTATION_ADMISSION_RETRY_DELAY_MS
2930
+ )
2931
+ return
2932
+ }
2933
+ }
2934
+ return
2935
+ }
2936
+ }
2937
+ runPendingFullSnapshotSliceSafely(true)
2938
+ }, delay)
2939
+ }
2940
+
2941
+ function deferPendingFullSnapshotUntilQuiet() {
2942
+ pendingFullSnapshotTask = undefined
2943
+ pendingFullSnapshotRestartRequested = false
2944
+ try {
2945
+ prepareForFullSnapshot()
2946
+ clearDeferredRecords()
2947
+ pendingFullSnapshotMutationVersion = domMutationVersion
2948
+ } catch (error) {
2949
+ return handleFullSnapshotException(
2950
+ 'full_snapshot_initialization_error',
2951
+ error
2952
+ )
2953
+ }
2954
+ schedulePendingFullSnapshotSlice(
2955
+ FULL_SNAPSHOT_MUTATION_QUIET_DELAY_MS
2956
+ )
2957
+ }
2958
+
2959
+ function restartPendingFullSnapshot(allowScheduling) {
2960
+ pendingFullSnapshotRestartCount += 1
2961
+ pendingFullSnapshotRestartRequested = false
2962
+ if (failPendingFullSnapshotOnTimeout()) {
2963
+ return
2964
+ }
2965
+ if (
2966
+ pendingFullSnapshotRestartCount > FULL_SNAPSHOT_MAX_RESTART_COUNT
2967
+ ) {
2968
+ if (
2969
+ !pendingFullSnapshotCanBeDiscarded &&
2970
+ allowScheduling
2971
+ ) {
2972
+ // Keep one bounded transaction alive while a large dashboard mutates.
2973
+ // A single timer waits for a quiet window; no serializer task or
2974
+ // deferred tail grows while churn continues.
2975
+ deferPendingFullSnapshotUntilQuiet()
2976
+ return
2977
+ }
2978
+ failOrAbandonFullSnapshot(
2979
+ 'full_snapshot_changed_during_serialization'
2980
+ )
2981
+ return
2982
+ }
2983
+ // Records produced while serializing a discarded attempt may reference
2984
+ // nodes (including canvases) that are not part of the replacement
2985
+ // baseline. Never carry them across the generation boundary.
2986
+ try {
2987
+ clearDeferredRecords()
2988
+ prepareMutationBaseline()
2989
+ resetCanvasRecordingBaseline()
2990
+ createPendingFullSnapshotTask()
2991
+ } catch (error) {
2992
+ return handleFullSnapshotException(
2993
+ 'full_snapshot_initialization_error',
2994
+ error
2995
+ )
2996
+ }
2997
+ if (allowScheduling) {
2998
+ schedulePendingFullSnapshotSlice()
2999
+ }
3000
+ }
3001
+
3002
+ function runPendingFullSnapshotSlice(
3003
+ allowScheduling,
3004
+ serializationDeadline
3005
+ ) {
3006
+ if (pendingFullSnapshotBaselineRecords) {
3007
+ return tryPendingFullSnapshotAdmission(allowScheduling)
3008
+ }
3009
+ if (!pendingFullSnapshotTask || recordStopped) {
3010
+ return false
3011
+ }
3012
+ if (failPendingFullSnapshotOnTimeout()) {
3013
+ return false
3014
+ }
3015
+ if (
3016
+ pendingFullSnapshotRestartRequested ||
3017
+ pendingFullSnapshotMutationVersion !== domMutationVersion
3018
+ ) {
3019
+ restartPendingFullSnapshot(allowScheduling)
3020
+ return false
3021
+ }
3022
+
3023
+ var sliceStartedAt = getPerformanceTime()
3024
+ var sliceDeadline =
3025
+ sliceStartedAt + FULL_SNAPSHOT_SERIALIZATION_SLICE_MS
3026
+ if (
3027
+ typeof serializationDeadline === 'number' &&
3028
+ isFinite(serializationDeadline)
3029
+ ) {
3030
+ sliceDeadline = Math.min(sliceDeadline, serializationDeadline)
3031
+ }
3032
+ var advanceResult = advanceFullSnapshotSerializerTask(
3033
+ pendingFullSnapshotTask,
3034
+ sliceDeadline
3035
+ )
3036
+ pendingFullSnapshotActiveDuration += Math.max(
3037
+ getPerformanceTime() - sliceStartedAt,
3038
+ 0
3039
+ )
3040
+ if (failPendingFullSnapshotOnTimeout()) {
3041
+ return false
3042
+ }
3043
+ if (advanceResult.isWatermarkReached) {
3044
+ failOrAbandonFullSnapshot('full_snapshot_serialization_watermark')
3045
+ return false
3046
+ }
3047
+ if (!advanceResult.completed) {
3048
+ if (allowScheduling) {
3049
+ schedulePendingFullSnapshotSlice()
3050
+ }
3051
+ return false
3052
+ }
3053
+
3054
+ // Capture native records that have not reached their observer callback yet.
3055
+ // Shadow observers are reset in bounded pages: reset() performs
3056
+ // takeRecords() and reports activity without serializing a mutation tail
3057
+ // that this replacement baseline will supersede.
3058
+ var resetShadowMutationsForBaseline =
3059
+ shadowRootsController.$rResetPendingMutationsForBaseline
3060
+ if (resetShadowMutationsForBaseline) {
3061
+ var shadowResetResult = resetShadowMutationsForBaseline()
3062
+ if (shadowResetResult === 'pending') {
3063
+ if (allowScheduling) {
3064
+ schedulePendingFullSnapshotSlice()
3065
+ }
3066
+ return false
3067
+ }
3068
+ if (shadowResetResult === false) {
3069
+ restartPendingFullSnapshot(allowScheduling)
3070
+ return false
3071
+ }
3072
+ }
3073
+ resetMutationsFromObservers()
3074
+ // Shadow-root observers created while the snapshot was serialized already
3075
+ // belong to the new generation. Mutations between slices have delivered an
3076
+ // activity callback and will restart the snapshot; retiring this generation
3077
+ // here would leave the emitted baseline without active shadow observers.
3078
+ discardPendingMutationPayload()
3079
+ if (pendingFullSnapshotMutationVersion !== domMutationVersion) {
3080
+ restartPendingFullSnapshot(allowScheduling)
3081
+ return false
3082
+ }
3083
+
3084
+ var serializedDocument = pendingFullSnapshotTask.serializedNode
3085
+ pendingFullSnapshotBaselineRecords = createFullSnapshotBaselineRecords(
3086
+ pendingFullSnapshotTimestamp,
3087
+ serializedDocument
3088
+ )
3089
+ pendingFullSnapshotBaselineMutationVersion =
3090
+ pendingFullSnapshotMutationVersion
3091
+ return tryPendingFullSnapshotAdmission(allowScheduling)
3092
+ }
3093
+
3094
+ function tryPendingFullSnapshotAdmission(allowScheduling) {
3095
+ if (
3096
+ !pendingFullSnapshotBaselineRecords ||
3097
+ recordStopped
3098
+ ) {
3099
+ return false
3100
+ }
3101
+ if (failPendingFullSnapshotOnTimeout()) {
3102
+ return false
3103
+ }
3104
+ if (!drainPreviousReplayTreeRecords()) {
3105
+ if (allowScheduling) {
3106
+ schedulePendingFullSnapshotSlice(
3107
+ MUTATION_ADMISSION_RETRY_DELAY_MS
3108
+ )
3109
+ }
3110
+ return false
3111
+ }
3112
+ if (failPendingFullSnapshotOnTimeout()) {
3113
+ return false
3114
+ }
3115
+ if (
3116
+ pendingFullSnapshotRestartRequested ||
3117
+ pendingFullSnapshotBaselineMutationVersion !== domMutationVersion
3118
+ ) {
3119
+ pendingFullSnapshotBaselineRecords = undefined
3120
+ pendingFullSnapshotBaselineMutationVersion = undefined
3121
+ discardPendingMutationPayload()
3122
+ discardPendingMutationAdmissions()
3123
+ prepareForFullSnapshot()
3124
+ createPendingFullSnapshotTask()
3125
+ pendingFullSnapshotRestartRequested = false
3126
+ if (allowScheduling) {
3127
+ schedulePendingFullSnapshotSlice()
3128
+ }
3129
+ return false
3130
+ }
3131
+ if (
3132
+ pendingFullSnapshotBaselineRecords[0].timestamp !==
3133
+ pendingFullSnapshotTimestamp
3134
+ ) {
3135
+ pendingFullSnapshotBaselineRecords =
3136
+ createFullSnapshotBaselineRecords(
3137
+ pendingFullSnapshotTimestamp,
3138
+ pendingFullSnapshotBaselineRecords[2].data.node
3139
+ )
3140
+ }
3141
+ var baselineRecords = pendingFullSnapshotBaselineRecords
3142
+ var startedAt = pendingFullSnapshotStartedAt
3143
+ var wasInitialFullSnapshot = pendingFullSnapshotIsInitial
3144
+ // Release the completed serializer and its timer while preserving the
3145
+ // exact baseline transaction for a possible backpressure retry.
3146
+ pendingFullSnapshotTask = undefined
3147
+ clearPendingFullSnapshotTimeout()
3148
+ if (!emitFullSnapshot(baselineRecords, startedAt)) {
3149
+ if (wasLastEmitBackpressured()) {
3150
+ if (allowScheduling) {
3151
+ schedulePendingFullSnapshotSlice(
3152
+ MUTATION_ADMISSION_RETRY_DELAY_MS
3153
+ )
3154
+ }
3155
+ return false
3156
+ }
3157
+ pendingFullSnapshotBaselineRecords = undefined
3158
+ pendingFullSnapshotBaselineMutationVersion = undefined
3159
+ failOrAbandonFullSnapshot('full_snapshot_admission_rejected')
3160
+ return false
3161
+ }
3162
+ pendingFullSnapshotBaselineRecords = undefined
3163
+ pendingFullSnapshotBaselineMutationVersion = undefined
3164
+ cancelScheduledFullSnapshot()
3165
+ if (
3166
+ !wasInitialFullSnapshot &&
3167
+ shadowRootsController.$rCommitRecovery
3168
+ ) {
3169
+ shadowRootsController.$rCommitRecovery()
3170
+ }
3171
+ previousPublishedReplayTree = undefined
3172
+ suppressRecordsUntilFullSnapshot = false
3173
+ drainPendingMutationAdmissions()
3174
+ resetPreviousReplayTreeRecords()
3175
+ previousReplayTreeAdmissionActive = false
3176
+ captureRecordsAgainstPreviousReplayTree = false
3177
+ flushDeferredRecords()
3178
+ if (!suppressRecordsUntilFullSnapshot && !recordStopped) {
3179
+ takeFullSnapshotCanvasBaseline()
3180
+ }
3181
+ return true
3182
+ }
3183
+
3184
+ function handleFullSnapshotException(reason, error) {
3185
+ addTelemetryDebug('Session Replay full snapshot failed.', {
3186
+ reason: reason,
3187
+ error: String(error)
3188
+ })
3189
+ failOrAbandonFullSnapshot(reason)
3190
+ return false
3191
+ }
3192
+
3193
+ function failPendingFullSnapshotOnTimeout() {
3194
+ if (
3195
+ pendingFullSnapshotTimestamp === undefined ||
3196
+ (pendingFullSnapshotActiveDuration <=
3197
+ FULL_SNAPSHOT_MAX_TOTAL_DURATION_MS &&
3198
+ getPerformanceTime() - pendingFullSnapshotStartedAt <=
3199
+ FULL_SNAPSHOT_MAX_WALL_DURATION_MS)
3200
+ ) {
3201
+ return false
3202
+ }
3203
+ failOrAbandonFullSnapshot('full_snapshot_serialization_timeout')
3204
+ return true
3205
+ }
3206
+
3207
+ function runPendingFullSnapshotSliceSafely(
3208
+ allowScheduling,
3209
+ serializationDeadline
3210
+ ) {
3211
+ try {
3212
+ return runPendingFullSnapshotSlice(
3213
+ allowScheduling,
3214
+ serializationDeadline
3215
+ )
3216
+ } catch (error) {
3217
+ return handleFullSnapshotException(
3218
+ 'full_snapshot_serialization_error',
3219
+ error
3220
+ )
3221
+ }
3222
+ }
3223
+
3224
+ function abandonPendingFullSnapshot(skipRecoveryRestore) {
3225
+ var shouldDiscardTail =
3226
+ pendingFullSnapshotRequiresTailDiscard
3227
+ var restoreError
3228
+ cancelScheduledFullSnapshot()
3229
+ clearDeferredRecords()
3230
+ try {
3231
+ if (skipRecoveryRestore) {
3232
+ // Teardown immediately retires every observer and Canvas scheduler.
3233
+ // Rebuilding up to 64 ShadowRoot observers and rescanning canvases here
3234
+ // would add pure main-thread work to stop() only to destroy it again.
3235
+ previousPublishedReplayTree = undefined
3236
+ suppressRecordsUntilFullSnapshot = false
3237
+ } else {
3238
+ restoreRecordingAfterAbandonedFullSnapshot(function () {
3239
+ restorePreviousReplayTreeRecords()
3240
+ // The native observer callback may not have run yet in this JavaScript
3241
+ // turn. Now that the old publication tree is active again, serialize
3242
+ // the bounded main/shadow mutation tail before retiring recovery
3243
+ // observers, instead of silently dropping it.
3244
+ flushMutations(true)
3245
+ })
3246
+ }
3247
+ } catch (error) {
3248
+ restoreError = error
3249
+ } finally {
3250
+ if (skipRecoveryRestore) {
3251
+ resetPreviousReplayTreeRecords()
3252
+ } else {
3253
+ previousReplayTreeLastRecordTimestamp = undefined
3254
+ }
3255
+ previousReplayTreeAdmissionActive = false
3256
+ captureRecordsAgainstPreviousReplayTree = false
3257
+ if (
3258
+ shouldDiscardTail &&
3259
+ options.$rOnMandatoryFullSnapshotAbandoned
3260
+ ) {
3261
+ options.$rOnMandatoryFullSnapshotAbandoned()
3262
+ }
3263
+ }
3264
+ if (restoreError) {
3265
+ return handleFullSnapshotException(
3266
+ 'full_snapshot_abandon_restore_error',
3267
+ restoreError
3268
+ )
3269
+ }
3270
+ return true
3271
+ }
3272
+
3273
+ function failOrAbandonFullSnapshot(reason) {
3274
+ if (pendingFullSnapshotCanBeDiscarded) {
3275
+ return abandonPendingFullSnapshot()
3276
+ }
3277
+ return failFullSnapshot(reason)
3278
+ }
3279
+
3280
+ function failFullSnapshot(reason) {
3281
+ var failureReason = pendingFullSnapshotIsInitial
3282
+ ? 'initial_' + reason
3283
+ : reason
3284
+ var shouldDiscardTail =
3285
+ pendingFullSnapshotRequiresTailDiscard
3286
+ cancelScheduledFullSnapshot()
3287
+ clearDeferredRecords()
3288
+ resetPreviousReplayTreeRecords()
3289
+ previousReplayTreeAdmissionActive = false
3290
+ captureRecordsAgainstPreviousReplayTree = false
3291
+ previousPublishedReplayTree = undefined
3292
+ if (
3293
+ shouldDiscardTail &&
3294
+ options.$rOnMandatoryFullSnapshotAbandoned
3295
+ ) {
3296
+ options.$rOnMandatoryFullSnapshotAbandoned()
3297
+ }
3298
+ stopRecording(undefined, true)
3299
+ if (options.onFullSnapshotFailure) {
3300
+ options.onFullSnapshotFailure(failureReason)
3301
+ }
3302
+ }
3303
+
3304
+ function takeSubsequentFullSnapshot(timestamp, canBeDiscarded) {
3305
+ // A public, best-effort snapshot must never replace an in-flight recovery
3306
+ // transaction. The recovery may already have retired stateful records or
3307
+ // the previous replay chain, so downgrading it would make abandon unsafe.
3308
+ if (
3309
+ canBeDiscarded &&
3310
+ pendingFullSnapshotTimestamp !== undefined
3311
+ ) {
3312
+ return
3313
+ }
3314
+ var shouldRunAfterRestart = Boolean(pendingFullSnapshotTask)
3315
+ scheduleSubsequentFullSnapshot(
3316
+ timestamp,
3317
+ Boolean(canBeDiscarded)
3318
+ )
3319
+ runPendingFullSnapshotSliceSafely(true)
3320
+ if (shouldRunAfterRestart && pendingFullSnapshotTask) {
3321
+ runPendingFullSnapshotSliceSafely(true)
3322
+ }
3323
+ }
3324
+
3325
+ function flushScheduledFullSnapshot(
3326
+ skipRecoveryRestore,
3327
+ supersedeForView
3328
+ ) {
3329
+ if (
3330
+ supersedeForView &&
3331
+ pendingFullSnapshotTimestamp !== undefined
3332
+ ) {
3333
+ // The next view starts its own baseline transaction. Discard every held
3334
+ // tail from the old view before ViewEnd is emitted.
3335
+ abandonPendingFullSnapshot(true)
3336
+ return true
3337
+ }
3338
+ if (
3339
+ pendingFullSnapshotCanBeDiscarded &&
3340
+ captureRecordsAgainstPreviousReplayTree
3341
+ ) {
3342
+ // Detect native main/shadow mutations that have not reached their async
3343
+ // callbacks before deciding that an optional candidate may abandon.
3344
+ capturePendingMutationActivityForPreviousReplayTree(true)
3345
+ }
3346
+ if (failPendingFullSnapshotOnTimeout()) {
3347
+ return true
3348
+ }
3349
+ if (pendingFullSnapshotBaselineRecords) {
3350
+ // Serialization already completed. Retry the exact baseline transaction
3351
+ // instead of treating the intentionally empty serializer task as an
3352
+ // incomplete snapshot. On unload this hook is invoked again after the
3353
+ // encoder is synchronously drained, so the same objects get one more
3354
+ // admission opportunity before teardown.
3355
+ if (runPendingFullSnapshotSliceSafely(false)) {
3356
+ return true
3357
+ }
3358
+ if (!pendingFullSnapshotBaselineRecords) {
3359
+ return true
3360
+ }
3361
+ if (
3362
+ skipRecoveryRestore ||
3363
+ pendingFullSnapshotCanBeDiscarded
3364
+ ) {
3365
+ abandonPendingFullSnapshot(skipRecoveryRestore)
3366
+ } else {
3367
+ schedulePendingFullSnapshotSlice(
3368
+ MUTATION_ADMISSION_RETRY_DELAY_MS
3369
+ )
3370
+ }
3371
+ return true
3372
+ }
3373
+ if (!pendingFullSnapshotTask) {
3374
+ if (pendingFullSnapshotTimestamp === undefined) {
3375
+ return false
3376
+ }
3377
+ if (
3378
+ skipRecoveryRestore ||
3379
+ pendingFullSnapshotCanBeDiscarded
3380
+ ) {
3381
+ abandonPendingFullSnapshot(skipRecoveryRestore)
3382
+ } else {
3383
+ failFullSnapshot('full_snapshot_incomplete_at_flush')
3384
+ }
3385
+ return true
3386
+ }
3387
+ if (pendingFullSnapshotCanBeDiscarded) {
3388
+ abandonPendingFullSnapshot(skipRecoveryRestore)
3389
+ return true
3390
+ }
3391
+ clearPendingFullSnapshotTimeout()
3392
+ if (
3393
+ pendingFullSnapshotRestartRequested ||
3394
+ pendingFullSnapshotMutationVersion !== domMutationVersion
3395
+ ) {
3396
+ restartPendingFullSnapshot(false)
3397
+ if (!pendingFullSnapshotTask || recordStopped) {
3398
+ return true
3399
+ }
3400
+ }
3401
+ var completed = runPendingFullSnapshotSliceSafely(false)
3402
+ // Teardown and view-boundary flushes must remain one bounded slice. A
3403
+ // synchronous loop here could spend the full one-second recovery budget
3404
+ // on the main thread and turn stop() into a long task.
3405
+ if (!completed && pendingFullSnapshotTask) {
3406
+ if (pendingFullSnapshotCanBeDiscarded) {
3407
+ abandonPendingFullSnapshot(skipRecoveryRestore)
3408
+ } else {
3409
+ failFullSnapshot('full_snapshot_incomplete_at_flush')
3410
+ }
3411
+ }
3412
+ return true
3413
+ }
3414
+
3415
+ function scheduleSubsequentFullSnapshot(
3416
+ timestamp,
3417
+ canBeDiscarded,
3418
+ requiresTailDiscard
3419
+ ) {
3420
+ if (pendingFullSnapshotTimestamp !== undefined) {
3421
+ // Any request arriving while a replacement baseline is being built must
3422
+ // reuse the same bounded transaction. Re-running begin() would reset its
3423
+ // restart/time budget and let sustained mutation churn spin forever.
3424
+ var nextFullSnapshotTimestamp =
3425
+ typeof timestamp === 'undefined' ? timeStampNow() : timestamp
3426
+ pendingFullSnapshotTimestamp = Math.max(
3427
+ pendingFullSnapshotTimestamp,
3428
+ nextFullSnapshotTimestamp,
3429
+ previousReplayTreeLastRecordTimestamp || 0
3430
+ )
3431
+ if (!canBeDiscarded) {
3432
+ pendingFullSnapshotCanBeDiscarded = false
3433
+ }
3434
+ if (
3435
+ requiresTailDiscard &&
3436
+ !pendingFullSnapshotRequiresTailDiscard
3437
+ ) {
3438
+ pendingFullSnapshotRequiresTailDiscard = true
3439
+ pendingFullSnapshotCanBeDiscarded = false
3440
+ previousReplayTreeAdmissionActive = false
3441
+ captureRecordsAgainstPreviousReplayTree = false
3442
+ resetPreviousReplayTreeRecords()
3443
+ if (options.$rOnMandatoryFullSnapshotStarted) {
3444
+ options.$rOnMandatoryFullSnapshotStarted()
3445
+ }
3446
+ }
3447
+ if (pendingFullSnapshotTask) {
3448
+ pendingFullSnapshotRestartRequested = true
3449
+ }
3450
+ schedulePendingFullSnapshotSlice(
3451
+ pendingFullSnapshotTask
3452
+ ? 0
3453
+ : FULL_SNAPSHOT_MUTATION_QUIET_DELAY_MS
3454
+ )
3455
+ return
3456
+ }
3457
+ if (
3458
+ beginSubsequentFullSnapshot(
3459
+ timestamp,
3460
+ canBeDiscarded,
3461
+ requiresTailDiscard
3462
+ )
3463
+ ) {
3464
+ schedulePendingFullSnapshotSlice()
3465
+ }
3466
+ }
3467
+
3468
+ function stopRecording(_flushReason, skipPendingFlush) {
3469
+ if (recordStopping || recordStopped) {
3470
+ return
3471
+ }
3472
+ // Keep the final bounded mutation drain, but prevent an overflow found by
3473
+ // that drain from starting a replacement full snapshot that teardown would
3474
+ // immediately discard.
3475
+ recordStopping = true
3476
+ var firstCleanupError
3477
+ try {
3478
+ if (pendingFullSnapshotIsInitial) {
3479
+ // An initial snapshot has no published tail to finalize. Teardown must
3480
+ // cancel its timer/task instead of forcing another slice or reporting
3481
+ // a failure for an intentional stop.
3482
+ cancelScheduledFullSnapshot()
3483
+ } else if (!skipPendingFlush && !flushScheduledFullSnapshot(true)) {
3484
+ // Capture small records still queued by native MutationObservers.
3485
+ // Oversized subtree serialization is discarded once its synchronous
3486
+ // budget is exhausted.
3487
+ var finalMutationFlushResult = flushMutations(true)
3488
+ if (finalMutationFlushResult === 'pending') {
3489
+ // Chunked callbacks are published only when their final chunk closes,
3490
+ // so teardown drops the whole tail and leaves the replay at its last
3491
+ // consistent state. Never report the bounded drain as successful.
3492
+ addTelemetryDebug(
3493
+ 'Session Replay dropped a pending mutation transaction during teardown.',
3494
+ { reason: 'stop_mutation_tail_pending' }
3495
+ )
3496
+ }
3497
+ }
3498
+ } catch (error) {
3499
+ firstCleanupError = error
3500
+ }
3501
+ recordStopped = true
3502
+ ;[
3503
+ discardPendingMutationAdmissions,
3504
+ cancelMutationSourceFlushContinuation,
3505
+ cancelScheduledFullSnapshot,
3506
+ invalidateFullSnapshotCanvasBaseline,
3507
+ function () {
3508
+ suppressRecordsUntilFullSnapshot = false
3509
+ previousReplayTreeAdmissionActive = false
3510
+ captureRecordsAgainstPreviousReplayTree = false
3511
+ },
3512
+ clearDeferredRecords,
3513
+ clearPreviousReplayTreeRecords,
3514
+ shadowRootsController.stop,
3515
+ canvasCommandCapture.stop,
3516
+ canvasWebGLSnapshotObserver.stop,
3517
+ canvasObserver.stop,
3518
+ function () {
3519
+ stopCanvasSnapshots(canvasSnapshotLoop)
3520
+ },
3521
+ stopObservers,
3522
+ stopSerializedCanvasTracking
3523
+ ].forEach(function (cleanupTask) {
3524
+ try {
3525
+ cleanupTask()
3526
+ } catch (error) {
3527
+ if (!firstCleanupError) {
3528
+ firstCleanupError = error
3529
+ }
3530
+ }
3531
+ })
3532
+ if (firstCleanupError) {
3533
+ addTelemetryDebug('Session Replay recorder cleanup failed.', {
3534
+ reason: _flushReason,
3535
+ error: String(firstCleanupError)
346
3536
  })
347
- },
348
- shadowRootsController: shadowRootsController
349
- })
350
- var stopObservers = _initObservers.stop
351
- var flushMutationsFromObservers = _initObservers.flush
352
- var resetMutationsFromObservers = _initObservers.reset || function () {}
353
- function flushMutations() {
354
- shadowRootsController.flush()
355
- flushMutationsFromObservers()
356
- flushPendingMutations()
3537
+ }
357
3538
  }
358
3539
 
359
- return {
360
- stop: function () {
361
- flushPendingMutations()
362
- shadowRootsController.stop()
363
- canvasCommandCapture.stop()
364
- canvasObserver.stop()
365
- stopCanvasSnapshots(canvasSnapshotLoop)
366
- stopObservers()
3540
+ var recorder = {
3541
+ stop: stopRecording,
3542
+ $rFlushCanvasCommands: function () {
3543
+ // A previous boundary pass may have preserved the exact Canvas record
3544
+ // after transient segment/encoder backpressure. Retry that object before
3545
+ // creating a newer command batch so unload's second writable pass keeps
3546
+ // command ordering and can use the segment serialization cache.
3547
+ try {
3548
+ flushDeferredRecords()
3549
+ } catch (_) {}
3550
+ try {
3551
+ if (canvasCommandCapture.flush) {
3552
+ canvasCommandCapture.flush()
3553
+ }
3554
+ } catch (_) {}
367
3555
  },
368
3556
  snapshotCanvas: function (canvas, snapshotOptions) {
369
- return canvasObserver.snapshot(
3557
+ return snapshotCanvasIfActive(
370
3558
  canvas,
371
3559
  assign({ trigger: 'manual' }, snapshotOptions)
372
3560
  )
373
3561
  },
374
3562
  getSerializedNodeIdForDebug: function (node) {
375
- return getSerializedNodeId(node)
376
- },
377
- getLastAutoCanvasSnapshotResultForDebug: function () {
378
- return cloneAutoCanvasSnapshotDebugResult(lastAutoCanvasSnapshotResult)
379
- },
380
- getAutoCanvasSnapshotDebugHistoryForDebug: function () {
381
- return autoCanvasSnapshotDebugHistoryForDebug.map(
382
- cloneAutoCanvasSnapshotDebugResult
383
- )
384
- },
385
- getLastCanvasMutationForDebug: function () {
386
- return cloneCanvasMutationDebugResult(lastCanvasMutationForDebug)
387
- },
388
- getCanvasMutationHistoryForDebug: function () {
389
- return canvasMutationHistoryForDebug.map(cloneCanvasMutationDebugResult)
390
- },
391
- getLastDomMutationForDebug: function () {
392
- return cloneDomMutationDebugResult(lastDomMutationForDebug)
393
- },
394
- getDomMutationHistoryForDebug: function () {
395
- return domMutationHistoryForDebug.map(cloneDomMutationDebugResult)
396
- },
397
- getReplayPerformanceForDebug: function () {
398
- return cloneReplayPerformanceStats(replayPerformanceStats)
399
- },
400
- takeSubsequentFullSnapshot: function (timestamp) {
401
- flushMutations()
402
- resetMutationsFromObservers()
403
- if (canvasObserver.reset) {
404
- canvasObserver.reset()
405
- }
406
- if (canvasCommandCapture.reset) {
407
- canvasCommandCapture.reset()
408
- }
409
- resetCanvasSnapshots(canvasSnapshotLoop)
410
- takeFullSnapshot(timestamp, {
411
- shadowRootsController: shadowRootsController,
412
- status: SerializationContextStatus.SUBSEQUENT_FULL_SNAPSHOT,
413
- elementsScrollPositions: elementsScrollPositions
414
- })
415
- if (canvasCommandCapture.scanExistingCanvases) {
416
- canvasCommandCapture.scanExistingCanvases()
417
- }
3563
+ return getActiveSerializedNodeId(node)
418
3564
  },
3565
+ takeSubsequentFullSnapshot: takeSubsequentFullSnapshot,
3566
+ flushScheduledFullSnapshot: flushScheduledFullSnapshot,
3567
+ scheduleSubsequentFullSnapshot: scheduleSubsequentFullSnapshot,
3568
+ prepareForViewChange: prepareForViewChange,
419
3569
  flushMutations: flushMutations,
420
3570
  shadowRootsController: shadowRootsController
421
3571
  }
3572
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
3573
+ assign(recorder, {
3574
+ getLastAutoCanvasSnapshotResultForDebug: function () {
3575
+ return cloneAutoCanvasSnapshotDebugResult(lastAutoCanvasSnapshotResult)
3576
+ },
3577
+ getAutoCanvasSnapshotDebugHistoryForDebug: function () {
3578
+ return autoCanvasSnapshotDebugHistoryForDebug.map(
3579
+ cloneAutoCanvasSnapshotDebugResult
3580
+ )
3581
+ },
3582
+ getLastCanvasMutationForDebug: function () {
3583
+ return cloneCanvasMutationDebugResult(lastCanvasMutationForDebug)
3584
+ },
3585
+ getCanvasMutationHistoryForDebug: function () {
3586
+ return canvasMutationHistoryForDebug.map(
3587
+ cloneCanvasMutationDebugResult
3588
+ )
3589
+ },
3590
+ getLastDomMutationForDebug: function () {
3591
+ return cloneDomMutationDebugResult(lastDomMutationForDebug)
3592
+ },
3593
+ getDomMutationHistoryForDebug: function () {
3594
+ return domMutationHistoryForDebug.map(cloneDomMutationDebugResult)
3595
+ },
3596
+ getReplayPerformanceForDebug: function () {
3597
+ return cloneReplayPerformanceStats(replayPerformanceStats)
3598
+ }
3599
+ })
3600
+ }
3601
+ return recorder
3602
+ }
3603
+
3604
+ function createInactiveRecorder() {
3605
+ var noop = function () {}
3606
+ var recorder = {
3607
+ stop: noop,
3608
+ $rFlushCanvasCommands: noop,
3609
+ snapshotCanvas: noop,
3610
+ getSerializedNodeIdForDebug: noop,
3611
+ takeSubsequentFullSnapshot: noop,
3612
+ flushScheduledFullSnapshot: function () {
3613
+ return false
3614
+ },
3615
+ scheduleSubsequentFullSnapshot: noop,
3616
+ prepareForViewChange: noop,
3617
+ flushMutations: noop
3618
+ }
3619
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__) {
3620
+ assign(recorder, {
3621
+ getLastAutoCanvasSnapshotResultForDebug: noop,
3622
+ getAutoCanvasSnapshotDebugHistoryForDebug: function () {
3623
+ return []
3624
+ },
3625
+ getLastCanvasMutationForDebug: noop,
3626
+ getCanvasMutationHistoryForDebug: function () {
3627
+ return []
3628
+ },
3629
+ getLastDomMutationForDebug: noop,
3630
+ getDomMutationHistoryForDebug: function () {
3631
+ return []
3632
+ },
3633
+ getReplayPerformanceForDebug: noop
3634
+ })
3635
+ }
3636
+ return recorder
422
3637
  }
423
3638
 
424
3639
  function materializeMutationPayload(pendingMutationPayload) {
@@ -451,38 +3666,38 @@ function createEmptyMutationPayload() {
451
3666
  }
452
3667
  }
453
3668
 
454
- function mergeMutationPayloads(target, source) {
3669
+ function mergeMutationPayloads(target, source, measurements) {
455
3670
  var merged = target || createEmptyMutationPayload()
456
- mergeAddMutations(merged, source.adds)
457
- mergeRemoveMutations(merged, source.removes)
458
- mergeTextMutations(merged, source.texts)
459
- mergeAttributeMutations(merged, source.attributes)
3671
+ mergeAddMutations(merged, source.adds, measurements.adds)
3672
+ mergeRemoveMutations(merged, source.removes, measurements.removes)
3673
+ mergeTextMutations(merged, source.texts, measurements.texts)
3674
+ mergeAttributeMutations(merged, source.attributes, measurements.attributes)
460
3675
  updateMutationPayloadApproxBytes(merged)
461
3676
  return merged
462
3677
  }
463
3678
 
464
- function mergeAddMutations(merged, sourceAdds) {
3679
+ function mergeAddMutations(merged, sourceAdds, sourceMeasurements) {
465
3680
  if (!sourceAdds.length) {
466
3681
  return
467
3682
  }
468
3683
 
469
- sourceAdds.forEach(function (add) {
470
- var addApproxBytes = estimateMutationEntryBytes(add)
3684
+ sourceAdds.forEach(function (add, index) {
3685
+ var addApproxBytes = sourceMeasurements[index]
471
3686
  merged.adds.push(add)
472
3687
  merged.addApproxBytes.push(addApproxBytes)
473
3688
  merged.addsApproxBytes += addApproxBytes
474
3689
  })
475
3690
  }
476
3691
 
477
- function mergeRemoveMutations(merged, sourceRemoves) {
3692
+ function mergeRemoveMutations(merged, sourceRemoves, sourceMeasurements) {
478
3693
  if (!sourceRemoves.length) {
479
3694
  return
480
3695
  }
481
- sourceRemoves.forEach(function (remove) {
3696
+ sourceRemoves.forEach(function (remove, index) {
482
3697
  var key = getRemoveMutationKey(remove)
483
3698
  if (!merged.removesByKey.has(key)) {
484
3699
  merged.removes.push(remove)
485
- var removeApproxBytes = estimateMutationEntryBytes(remove)
3700
+ var removeApproxBytes = sourceMeasurements[index]
486
3701
  merged.removeApproxBytesByKey.set(key, removeApproxBytes)
487
3702
  merged.removesApproxBytes += removeApproxBytes
488
3703
  }
@@ -490,35 +3705,35 @@ function mergeRemoveMutations(merged, sourceRemoves) {
490
3705
  })
491
3706
  }
492
3707
 
493
- function mergeTextMutations(merged, sourceTexts) {
3708
+ function mergeTextMutations(merged, sourceTexts, sourceMeasurements) {
494
3709
  if (!sourceTexts.length) {
495
3710
  return
496
3711
  }
497
- sourceTexts.forEach(function (textMutation) {
3712
+ sourceTexts.forEach(function (textMutation, index) {
498
3713
  var existingTextMutation = merged.textsById.get(textMutation.id)
499
3714
  if (existingTextMutation) {
500
3715
  merged.textsApproxBytes -=
501
3716
  merged.textApproxBytesById.get(textMutation.id) || 0
502
3717
  existingTextMutation.value = textMutation.value
503
- var nextTextApproxBytes = estimateMutationEntryBytes(existingTextMutation)
3718
+ var nextTextApproxBytes = sourceMeasurements[index]
504
3719
  merged.textApproxBytesById.set(textMutation.id, nextTextApproxBytes)
505
3720
  merged.textsApproxBytes += nextTextApproxBytes
506
3721
  return
507
3722
  }
508
3723
  merged.texts.push(textMutation)
509
3724
  merged.textsById.set(textMutation.id, textMutation)
510
- var textApproxBytes = estimateMutationEntryBytes(textMutation)
3725
+ var textApproxBytes = sourceMeasurements[index]
511
3726
  merged.textApproxBytesById.set(textMutation.id, textApproxBytes)
512
3727
  merged.textsApproxBytes += textApproxBytes
513
3728
  })
514
3729
  }
515
3730
 
516
- function mergeAttributeMutations(merged, sourceAttributes) {
3731
+ function mergeAttributeMutations(merged, sourceAttributes, sourceMeasurements) {
517
3732
  if (!sourceAttributes.length) {
518
3733
  return
519
3734
  }
520
3735
 
521
- sourceAttributes.forEach(function (attributeMutation) {
3736
+ sourceAttributes.forEach(function (attributeMutation, index) {
522
3737
  var existingAttributeMutation = merged.attributesById.get(attributeMutation.id)
523
3738
  if (!existingAttributeMutation) {
524
3739
  var nextAttributeMutation = {
@@ -527,7 +3742,7 @@ function mergeAttributeMutations(merged, sourceAttributes) {
527
3742
  }
528
3743
  merged.attributes.push(nextAttributeMutation)
529
3744
  merged.attributesById.set(attributeMutation.id, nextAttributeMutation)
530
- var attributeApproxBytes = estimateMutationEntryBytes(nextAttributeMutation)
3745
+ var attributeApproxBytes = sourceMeasurements[index]
531
3746
  merged.attributeApproxBytesById.set(
532
3747
  attributeMutation.id,
533
3748
  attributeApproxBytes
@@ -556,68 +3771,495 @@ function getRemoveMutationKey(remove) {
556
3771
  return remove.parentId + ':' + remove.id
557
3772
  }
558
3773
 
559
- function shouldFlushPendingMutationPayloadBeforeMerge(target, source) {
3774
+ function shouldFlushPendingMutationPayloadBeforeMerge(
3775
+ target,
3776
+ source,
3777
+ sourceApproxBytes,
3778
+ pendingPublicationTokenByNode,
3779
+ pendingNodeParentByNode,
3780
+ wasNodePublishedBeforePendingMutation
3781
+ ) {
3782
+ // Structural arrays do not encode the order in which separate callbacks
3783
+ // happened. Keep callback boundaries around adds/removes so a short-lived
3784
+ // add cannot be replayed after its later remove. The exception is a move
3785
+ // reported by different document/ShadowRoot observers: its add and remove
3786
+ // share one private publication token and must reach the player atomically.
3787
+ if (
3788
+ hasStructuralMutationEntries(target) ||
3789
+ hasStructuralMutationEntries(source)
3790
+ ) {
3791
+ return !hasCrossCallbackMoveDependency(
3792
+ target,
3793
+ source,
3794
+ pendingPublicationTokenByNode,
3795
+ pendingNodeParentByNode,
3796
+ wasNodePublishedBeforePendingMutation
3797
+ )
3798
+ }
560
3799
  return (
561
- target.approxBytes + estimateMutationPayloadBytes(source) >
3800
+ target.approxBytes + sourceApproxBytes >
562
3801
  MAX_MUTATION_EMIT_APPROX_BYTES
563
3802
  )
564
3803
  }
565
3804
 
566
- function splitPendingMutationPayloadForEmit(pendingMutationPayload) {
567
- var mutation = materializeMutationPayload(pendingMutationPayload)
3805
+ function hasStructuralMutationEntries(mutation) {
3806
+ return mutation.adds.length > 0 || mutation.removes.length > 0
3807
+ }
3808
+
3809
+ function hasCrossCallbackMoveDependency(
3810
+ first,
3811
+ second,
3812
+ pendingPublicationTokenByNode,
3813
+ pendingNodeParentByNode,
3814
+ wasNodePublishedBeforePendingMutation
3815
+ ) {
3816
+ return (
3817
+ hasRemoveToAddDependency(
3818
+ first.removes,
3819
+ second.adds,
3820
+ second.removes,
3821
+ pendingPublicationTokenByNode,
3822
+ pendingNodeParentByNode,
3823
+ wasNodePublishedBeforePendingMutation
3824
+ ) ||
3825
+ hasRemoveToAddDependency(
3826
+ second.removes,
3827
+ first.adds,
3828
+ first.removes,
3829
+ pendingPublicationTokenByNode,
3830
+ pendingNodeParentByNode,
3831
+ wasNodePublishedBeforePendingMutation
3832
+ )
3833
+ )
3834
+ }
3835
+
3836
+ function hasRemoveToAddDependency(
3837
+ removes,
3838
+ adds,
3839
+ removesAlreadyPairedWithAdds,
3840
+ pendingPublicationTokenByNode,
3841
+ pendingNodeParentByNode,
3842
+ wasNodePublishedBeforePendingMutation
3843
+ ) {
3844
+ if (!removes.length || !adds.length) {
3845
+ return false
3846
+ }
3847
+ var addPublicationTokens = new Set()
3848
+ adds.forEach(function (add) {
3849
+ var publicationToken = getMutationAddPublicationToken(add)
3850
+ if (publicationToken) {
3851
+ addPublicationTokens.add(publicationToken)
3852
+ }
3853
+ })
3854
+ // A later remove is a new transition when the same node (or an ancestor in
3855
+ // the staged add tree) was already paired with this add. Keep sibling removes
3856
+ // eligible: one add token can contain nodes moved from several observers.
3857
+ var pairedRemovedNodesByPublicationToken = new Map()
3858
+ removesAlreadyPairedWithAdds.forEach(function (remove) {
3859
+ var removedNode = getMutationRemoveSourceNode(remove)
3860
+ if (
3861
+ removedNode &&
3862
+ wasNodePublishedBeforePendingMutation(removedNode)
3863
+ ) {
3864
+ var publicationToken =
3865
+ pendingPublicationTokenByNode.get(removedNode)
3866
+ if (addPublicationTokens.has(publicationToken)) {
3867
+ var pairedRemovedNodes =
3868
+ pairedRemovedNodesByPublicationToken.get(publicationToken)
3869
+ if (!pairedRemovedNodes) {
3870
+ pairedRemovedNodes = new Set()
3871
+ pairedRemovedNodesByPublicationToken.set(
3872
+ publicationToken,
3873
+ pairedRemovedNodes
3874
+ )
3875
+ }
3876
+ pairedRemovedNodes.add(removedNode)
3877
+ }
3878
+ }
3879
+ })
3880
+ return removes.some(function (remove) {
3881
+ var removedNode = getMutationRemoveSourceNode(remove)
3882
+ var publicationToken =
3883
+ removedNode && pendingPublicationTokenByNode.get(removedNode)
3884
+ return Boolean(
3885
+ removedNode &&
3886
+ wasNodePublishedBeforePendingMutation(removedNode) &&
3887
+ addPublicationTokens.has(publicationToken) &&
3888
+ !isNodeCoveredByPairedRemove(
3889
+ removedNode,
3890
+ pairedRemovedNodesByPublicationToken.get(publicationToken),
3891
+ pendingNodeParentByNode
3892
+ )
3893
+ )
3894
+ })
3895
+ }
3896
+
3897
+ function isNodeCoveredByPairedRemove(
3898
+ node,
3899
+ pairedRemovedNodes,
3900
+ pendingNodeParentByNode
3901
+ ) {
3902
+ if (!pairedRemovedNodes) {
3903
+ return false
3904
+ }
3905
+ var current = node
3906
+ var depth = 0
3907
+ while (current && depth < MAX_SERIALIZED_NODE_ANCESTOR_DEPTH) {
3908
+ if (pairedRemovedNodes.has(current)) {
3909
+ return true
3910
+ }
3911
+ current = pendingNodeParentByNode.get(current)
3912
+ depth += 1
3913
+ }
3914
+ return false
3915
+ }
3916
+
3917
+ function splitPendingMutationPayloadForEmit(
3918
+ pendingMutationPayload,
3919
+ pendingPublicationTokenByNode,
3920
+ wasNodePublishedBeforePendingMutation
3921
+ ) {
3922
+ if (pendingMutationPayload.approxBytes <= MAX_MUTATION_EMIT_APPROX_BYTES) {
3923
+ return {
3924
+ mutationEntries: [
3925
+ [
3926
+ materializeMutationPayload(pendingMutationPayload),
3927
+ pendingMutationPayload.approxBytes
3928
+ ]
3929
+ ],
3930
+ hasOversizedEntry: false
3931
+ }
3932
+ }
3933
+
3934
+ var mutationEntries = []
3935
+ var currentMutation = createEmptyMutation()
3936
+ var currentMutationBytes = BASE_MUTATION_PAYLOAD_APPROX_BYTES
3937
+ var currentStructuralKind
3938
+ var hasOversizedEntry = false
3939
+ var structuralComponents = createStructuralMutationComponents(
3940
+ pendingMutationPayload,
3941
+ pendingPublicationTokenByNode,
3942
+ wasNodePublishedBeforePendingMutation
3943
+ )
568
3944
  if (
569
- !mutation.adds.length ||
570
- pendingMutationPayload.approxBytes <= MAX_MUTATION_EMIT_APPROX_BYTES
3945
+ !structuralComponents ||
3946
+ structuralComponents.some(function (component) {
3947
+ return (
3948
+ BASE_MUTATION_PAYLOAD_APPROX_BYTES + component.approxBytes >
3949
+ MAX_MUTATION_EMIT_APPROX_BYTES
3950
+ )
3951
+ })
571
3952
  ) {
572
- return [mutation]
3953
+ return {
3954
+ mutationEntries: [],
3955
+ hasOversizedEntry: true
3956
+ }
3957
+ }
3958
+
3959
+ function pushCurrentMutation() {
3960
+ if (!hasMutationEntries(currentMutation)) {
3961
+ return
3962
+ }
3963
+ mutationEntries.push([currentMutation, currentMutationBytes])
3964
+ currentMutation = createEmptyMutation()
3965
+ currentMutationBytes = BASE_MUTATION_PAYLOAD_APPROX_BYTES
3966
+ currentStructuralKind = undefined
3967
+ }
3968
+
3969
+ function appendEntry(type, entry, entryBytes) {
3970
+ if (
3971
+ BASE_MUTATION_PAYLOAD_APPROX_BYTES + entryBytes >
3972
+ MAX_MUTATION_EMIT_APPROX_BYTES
3973
+ ) {
3974
+ hasOversizedEntry = true
3975
+ return
3976
+ }
3977
+ if (
3978
+ hasMutationEntries(currentMutation) &&
3979
+ currentMutationBytes + entryBytes > MAX_MUTATION_EMIT_APPROX_BYTES
3980
+ ) {
3981
+ pushCurrentMutation()
3982
+ }
3983
+ currentMutation[type].push(entry)
3984
+ currentMutationBytes += entryBytes
3985
+ }
3986
+
3987
+ structuralComponents.forEach(function (component) {
3988
+ var componentStructuralKind = component.removes.length
3989
+ ? 'dependent'
3990
+ : 'add'
3991
+ if (
3992
+ hasMutationEntries(currentMutation) &&
3993
+ (currentStructuralKind !== componentStructuralKind ||
3994
+ currentMutationBytes + component.approxBytes >
3995
+ MAX_MUTATION_EMIT_APPROX_BYTES)
3996
+ ) {
3997
+ pushCurrentMutation()
3998
+ }
3999
+ component.adds.forEach(function (addEntry) {
4000
+ currentMutation.adds.push(addEntry.entry)
4001
+ })
4002
+ component.removes.forEach(function (removeEntry) {
4003
+ currentMutation.removes.push(removeEntry.entry)
4004
+ })
4005
+ currentMutationBytes += component.approxBytes
4006
+ currentStructuralKind = componentStructuralKind
4007
+ })
4008
+ pushCurrentMutation()
4009
+ pendingMutationPayload.texts.forEach(function (textMutation) {
4010
+ appendEntry(
4011
+ 'texts',
4012
+ textMutation,
4013
+ pendingMutationPayload.textApproxBytesById.get(textMutation.id) ||
4014
+ estimateMutationEntryBytes(textMutation)
4015
+ )
4016
+ })
4017
+ pendingMutationPayload.attributes.forEach(function (attributeMutation) {
4018
+ appendEntry(
4019
+ 'attributes',
4020
+ attributeMutation,
4021
+ pendingMutationPayload.attributeApproxBytesById.get(
4022
+ attributeMutation.id
4023
+ ) || estimateMutationEntryBytes(attributeMutation)
4024
+ )
4025
+ })
4026
+ pushCurrentMutation()
4027
+
4028
+ return {
4029
+ mutationEntries: mutationEntries,
4030
+ hasOversizedEntry: hasOversizedEntry
4031
+ }
4032
+ }
4033
+
4034
+ function createStructuralMutationComponents(
4035
+ pendingMutationPayload,
4036
+ pendingPublicationTokenByNode,
4037
+ wasNodePublishedBeforePendingMutation
4038
+ ) {
4039
+ var structuralEntries = []
4040
+ var entriesByParentId = new Map()
4041
+ var addEntryIndexByPublicationToken = new Map()
4042
+
4043
+ function appendStructuralEntry(type, entry, approxBytes) {
4044
+ var entryIndex = structuralEntries.length
4045
+ var structuralEntry = {
4046
+ type: type,
4047
+ entry: entry,
4048
+ approxBytes: approxBytes,
4049
+ parent: entryIndex
4050
+ }
4051
+ structuralEntries.push(structuralEntry)
4052
+ var parentEntries = entriesByParentId.get(entry.parentId)
4053
+ if (!parentEntries) {
4054
+ parentEntries = {
4055
+ adds: [],
4056
+ removes: []
4057
+ }
4058
+ entriesByParentId.set(entry.parentId, parentEntries)
4059
+ }
4060
+ parentEntries[type].push(entryIndex)
4061
+ if (type === 'adds') {
4062
+ var publicationToken = getMutationAddPublicationToken(entry)
4063
+ if (publicationToken) {
4064
+ addEntryIndexByPublicationToken.set(publicationToken, entryIndex)
4065
+ }
4066
+ }
4067
+ }
4068
+
4069
+ pendingMutationPayload.adds.forEach(function (add, index) {
4070
+ appendStructuralEntry(
4071
+ 'adds',
4072
+ add,
4073
+ pendingMutationPayload.addApproxBytes[index]
4074
+ )
4075
+ })
4076
+ pendingMutationPayload.removes.forEach(function (remove) {
4077
+ appendStructuralEntry(
4078
+ 'removes',
4079
+ remove,
4080
+ pendingMutationPayload.removeApproxBytesByKey.get(
4081
+ getRemoveMutationKey(remove)
4082
+ ) || estimateMutationEntryBytes(remove)
4083
+ )
4084
+ })
4085
+
4086
+ function findRoot(entryIndex) {
4087
+ var structuralEntry = structuralEntries[entryIndex]
4088
+ while (structuralEntry.parent !== entryIndex) {
4089
+ structuralEntry.parent =
4090
+ structuralEntries[structuralEntry.parent].parent
4091
+ entryIndex = structuralEntry.parent
4092
+ structuralEntry = structuralEntries[entryIndex]
4093
+ }
4094
+ return entryIndex
4095
+ }
4096
+
4097
+ function connectEntries(firstEntryIndex, secondEntryIndex) {
4098
+ var firstRoot = findRoot(firstEntryIndex)
4099
+ var secondRoot = findRoot(secondEntryIndex)
4100
+ if (firstRoot !== secondRoot) {
4101
+ structuralEntries[secondRoot].parent = firstRoot
4102
+ }
573
4103
  }
574
4104
 
575
- var addOnlyPayloads = []
576
- var currentAdds = []
577
- var currentAddsBytes = BASE_MUTATION_PAYLOAD_APPROX_BYTES
4105
+ // A remove and its replacement additions must be replayed together. Keep
4106
+ // this dependency scoped to the mutated parent instead of turning every
4107
+ // replacement in the pending window into one global transaction.
4108
+ entriesByParentId.forEach(function (parentEntries) {
4109
+ if (!parentEntries.adds.length || !parentEntries.removes.length) {
4110
+ return
4111
+ }
4112
+ var firstEntryIndex = parentEntries.adds[0]
4113
+ parentEntries.adds.slice(1).forEach(function (entryIndex) {
4114
+ connectEntries(firstEntryIndex, entryIndex)
4115
+ })
4116
+ parentEntries.removes.forEach(function (entryIndex) {
4117
+ connectEntries(firstEntryIndex, entryIndex)
4118
+ })
4119
+ })
578
4120
 
579
- mutation.adds.forEach(function (add, index) {
580
- var addBytes = pendingMutationPayload.addApproxBytes[index]
4121
+ // A published move can cross document and ShadowRoot observers. The source
4122
+ // node carries the destination add's private publication token, which is the
4123
+ // causal edge joining the source and destination parent components.
4124
+ structuralEntries.forEach(function (structuralEntry, entryIndex) {
4125
+ if (structuralEntry.type !== 'removes') {
4126
+ return
4127
+ }
4128
+ var removedNode = getMutationRemoveSourceNode(structuralEntry.entry)
581
4129
  if (
582
- currentAdds.length &&
583
- currentAddsBytes + addBytes > MAX_MUTATION_EMIT_APPROX_BYTES
4130
+ !removedNode ||
4131
+ !wasNodePublishedBeforePendingMutation(removedNode)
584
4132
  ) {
585
- addOnlyPayloads.push({
586
- adds: currentAdds,
4133
+ return
4134
+ }
4135
+ var addEntryIndex = addEntryIndexByPublicationToken.get(
4136
+ pendingPublicationTokenByNode.get(removedNode)
4137
+ )
4138
+ if (typeof addEntryIndex === 'number') {
4139
+ connectEntries(entryIndex, addEntryIndex)
4140
+ }
4141
+ })
4142
+
4143
+ var componentsByRoot = new Map()
4144
+ structuralEntries.forEach(function (structuralEntry, entryIndex) {
4145
+ var root = findRoot(entryIndex)
4146
+ var component = componentsByRoot.get(root)
4147
+ if (!component) {
4148
+ component = {
4149
+ adds: [],
587
4150
  removes: [],
588
- texts: [],
589
- attributes: []
590
- })
591
- currentAdds = []
592
- currentAddsBytes = BASE_MUTATION_PAYLOAD_APPROX_BYTES
4151
+ approxBytes: 0,
4152
+ sequence: entryIndex,
4153
+ dependencies: new Set()
4154
+ }
4155
+ componentsByRoot.set(root, component)
593
4156
  }
594
- currentAdds.push(add)
595
- currentAddsBytes += addBytes
4157
+ component[structuralEntry.type].push(structuralEntry)
4158
+ component.approxBytes += structuralEntry.approxBytes
4159
+ component.sequence = Math.min(component.sequence, entryIndex)
596
4160
  })
597
4161
 
598
- if (currentAdds.length) {
599
- addOnlyPayloads.push({
600
- adds: currentAdds,
601
- removes: [],
602
- texts: [],
603
- attributes: []
4162
+ var components = Array.from(componentsByRoot.values())
4163
+ var addComponentByNodeId = new Map()
4164
+ components.forEach(function (component) {
4165
+ component.adds.forEach(function (addEntry) {
4166
+ addComponentByNodeId.set(addEntry.entry.node.id, component)
4167
+ })
4168
+ })
4169
+ components.forEach(function (component) {
4170
+ component.adds.forEach(function (addEntry) {
4171
+ var dependencyNodeIds = [
4172
+ addEntry.entry.parentId,
4173
+ addEntry.entry.nextId
4174
+ ]
4175
+ dependencyNodeIds.forEach(function (dependencyNodeId) {
4176
+ var dependencyComponent =
4177
+ addComponentByNodeId.get(dependencyNodeId)
4178
+ if (
4179
+ dependencyComponent &&
4180
+ dependencyComponent !== component
4181
+ ) {
4182
+ component.dependencies.add(dependencyComponent)
4183
+ }
4184
+ })
604
4185
  })
4186
+ })
4187
+
4188
+ // Mutation serialization orders sibling roots so an add's nextId is already
4189
+ // published. Preserve that ordering across split payloads, including when a
4190
+ // replacement or move has joined entries that were originally separate.
4191
+ components.sort(function (first, second) {
4192
+ return first.sequence - second.sequence
4193
+ })
4194
+ var orderedComponents = []
4195
+ var visitedComponents = new Set()
4196
+ var visitingComponents = new Set()
4197
+ var hasDependencyCycle = false
4198
+ function visitComponent(component) {
4199
+ if (visitedComponents.has(component)) {
4200
+ return
4201
+ }
4202
+ if (visitingComponents.has(component)) {
4203
+ hasDependencyCycle = true
4204
+ return
4205
+ }
4206
+ visitingComponents.add(component)
4207
+ Array.from(component.dependencies)
4208
+ .sort(function (first, second) {
4209
+ return first.sequence - second.sequence
4210
+ })
4211
+ .forEach(visitComponent)
4212
+ visitingComponents.delete(component)
4213
+ visitedComponents.add(component)
4214
+ orderedComponents.push(component)
605
4215
  }
4216
+ components.forEach(visitComponent)
4217
+ return hasDependencyCycle ? undefined : orderedComponents
4218
+ }
606
4219
 
607
- if (
608
- mutation.removes.length ||
609
- mutation.texts.length ||
610
- mutation.attributes.length
611
- ) {
612
- addOnlyPayloads.push({
613
- adds: [],
614
- removes: mutation.removes,
615
- texts: mutation.texts,
616
- attributes: mutation.attributes
4220
+ function partitionMutationPayloadByEntrySize(mutation, measurements) {
4221
+ var safeMutation = createEmptyMutation()
4222
+ var safeMeasurements = {
4223
+ adds: [],
4224
+ removes: [],
4225
+ texts: [],
4226
+ attributes: [],
4227
+ approxBytes: BASE_MUTATION_PAYLOAD_APPROX_BYTES
4228
+ }
4229
+ var hasOversizedEntry = false
4230
+
4231
+ ;['adds', 'removes', 'texts', 'attributes'].forEach(function (type) {
4232
+ mutation[type].forEach(function (entry, index) {
4233
+ var entryBytes = measurements[type][index]
4234
+ if (
4235
+ BASE_MUTATION_PAYLOAD_APPROX_BYTES + entryBytes >
4236
+ MAX_MUTATION_EMIT_APPROX_BYTES
4237
+ ) {
4238
+ hasOversizedEntry = true
4239
+ return
4240
+ }
4241
+ safeMutation[type].push(entry)
4242
+ safeMeasurements[type].push(entryBytes)
4243
+ safeMeasurements.approxBytes += entryBytes
617
4244
  })
4245
+ })
4246
+
4247
+ return {
4248
+ mutation: safeMutation,
4249
+ measurements: safeMeasurements,
4250
+ hasOversizedEntry: hasOversizedEntry
618
4251
  }
4252
+ }
619
4253
 
620
- return addOnlyPayloads
4254
+ function hasOversizedMutationEntry(measurements) {
4255
+ return ['adds', 'removes', 'texts', 'attributes'].some(function (type) {
4256
+ return measurements[type].some(function (entryBytes) {
4257
+ return (
4258
+ BASE_MUTATION_PAYLOAD_APPROX_BYTES + entryBytes >
4259
+ MAX_MUTATION_EMIT_APPROX_BYTES
4260
+ )
4261
+ })
4262
+ })
621
4263
  }
622
4264
 
623
4265
  function createEmptyMutation() {
@@ -629,25 +4271,118 @@ function createEmptyMutation() {
629
4271
  }
630
4272
  }
631
4273
 
632
- var BASE_MUTATION_PAYLOAD_APPROX_BYTES = 64
633
- function estimateMutationPayloadBytes(mutation) {
4274
+ function hasMutationEntries(mutation) {
634
4275
  return (
635
- BASE_MUTATION_PAYLOAD_APPROX_BYTES +
636
- estimateMutationEntriesBytes(mutation.adds) +
637
- estimateMutationEntriesBytes(mutation.removes) +
638
- estimateMutationEntriesBytes(mutation.texts) +
639
- estimateMutationEntriesBytes(mutation.attributes)
4276
+ mutation.adds.length > 0 ||
4277
+ mutation.removes.length > 0 ||
4278
+ mutation.texts.length > 0 ||
4279
+ mutation.attributes.length > 0
640
4280
  )
641
4281
  }
642
4282
 
4283
+ var BASE_MUTATION_PAYLOAD_APPROX_BYTES = 64
4284
+ function measureMutationPayload(mutation) {
4285
+ var measurements = {
4286
+ adds: measureMutationEntries(mutation.adds),
4287
+ removes: measureMutationEntries(mutation.removes),
4288
+ texts: measureMutationEntries(mutation.texts),
4289
+ attributes: measureMutationEntries(mutation.attributes)
4290
+ }
4291
+ measurements.approxBytes =
4292
+ BASE_MUTATION_PAYLOAD_APPROX_BYTES +
4293
+ sumMutationEntryMeasurements(measurements.adds) +
4294
+ sumMutationEntryMeasurements(measurements.removes) +
4295
+ sumMutationEntryMeasurements(measurements.texts) +
4296
+ sumMutationEntryMeasurements(measurements.attributes)
4297
+ return measurements
4298
+ }
4299
+
643
4300
  function estimateMutationEntryBytes(entry) {
644
- return JSON.stringify(entry).length
4301
+ var approxBytes = 2
4302
+ Object.keys(entry).forEach(function (key) {
4303
+ approxBytes += estimateMutationJsonStringBytes(key) + 2
4304
+ if (key === 'node') {
4305
+ approxBytes +=
4306
+ getSerializedNodeApproxBytes(entry.node) ||
4307
+ estimateJsonValueBytes(entry.node)
4308
+ } else {
4309
+ approxBytes += estimateJsonValueBytes(entry[key])
4310
+ }
4311
+ })
4312
+ return approxBytes
645
4313
  }
646
4314
 
647
- function estimateMutationEntriesBytes(entries) {
648
- var total = 0
4315
+ function estimateJsonValueBytes(value, maxApproxBytes) {
4316
+ if (typeof maxApproxBytes !== 'number') {
4317
+ maxApproxBytes = MAX_MUTATION_EMIT_APPROX_BYTES
4318
+ }
4319
+ var approxBytes = 0
4320
+ var pendingValues = [value]
4321
+ while (
4322
+ pendingValues.length &&
4323
+ approxBytes <= maxApproxBytes
4324
+ ) {
4325
+ var current = pendingValues.pop()
4326
+ if (typeof current === 'string') {
4327
+ approxBytes += estimateMutationJsonStringBytes(current, maxApproxBytes)
4328
+ } else if (typeof current === 'number') {
4329
+ approxBytes += 16
4330
+ } else if (typeof current === 'boolean') {
4331
+ approxBytes += 5
4332
+ } else if (current && typeof current === 'object') {
4333
+ if (Array.isArray(current)) {
4334
+ approxBytes += current.length + 2
4335
+ for (var index = 0; index < current.length; index += 1) {
4336
+ pendingValues.push(current[index])
4337
+ }
4338
+ } else {
4339
+ Object.keys(current).forEach(function (key) {
4340
+ approxBytes += estimateMutationJsonStringBytes(key) + 2
4341
+ pendingValues.push(current[key])
4342
+ })
4343
+ }
4344
+ } else {
4345
+ approxBytes += 4
4346
+ }
4347
+ }
4348
+ return approxBytes
4349
+ }
4350
+
4351
+ function estimateMutationJsonStringBytes(value, maxApproxBytes) {
4352
+ if (typeof maxApproxBytes !== 'number') {
4353
+ maxApproxBytes = MAX_MUTATION_EMIT_APPROX_BYTES
4354
+ }
4355
+ if (value.length * 2 + 4 > maxApproxBytes) {
4356
+ return maxApproxBytes + 1
4357
+ }
4358
+ var bytes = 4
4359
+ for (var index = 0; index < value.length; index += 1) {
4360
+ var characterCode = value.charCodeAt(index)
4361
+ bytes +=
4362
+ characterCode <= 0x1f ||
4363
+ characterCode === 0x22 ||
4364
+ characterCode === 0x5c
4365
+ ? 12
4366
+ : 2
4367
+ if (bytes > maxApproxBytes) {
4368
+ return bytes
4369
+ }
4370
+ }
4371
+ return bytes
4372
+ }
4373
+
4374
+ function measureMutationEntries(entries) {
4375
+ var measurements = []
649
4376
  for (var i = 0; i < entries.length; i += 1) {
650
- total += estimateMutationEntryBytes(entries[i])
4377
+ measurements.push(estimateMutationEntryBytes(entries[i]))
4378
+ }
4379
+ return measurements
4380
+ }
4381
+
4382
+ function sumMutationEntryMeasurements(measurements) {
4383
+ var total = 0
4384
+ for (var i = 0; i < measurements.length; i += 1) {
4385
+ total += measurements[i]
651
4386
  }
652
4387
  return total
653
4388
  }
@@ -665,12 +4400,22 @@ function createReplayPerformanceStats() {
665
4400
  return {
666
4401
  processMutationsCount: 0,
667
4402
  processMutationsDuration: 0,
4403
+ mutationSerializationCount: 0,
4404
+ mutationSerializationDuration: 0,
4405
+ mutationLocalDropCount: 0,
4406
+ mutationLocalDropLastReason: undefined,
4407
+ mutationDropRecoveryCount: 0,
4408
+ mutationDropRecoveryLastReason: undefined,
4409
+ admissionGapRecoveryCount: 0,
4410
+ admissionGapRecoveryLastReason: undefined,
668
4411
  mutationCallbackCount: 0,
669
4412
  mutationRecordCount: 0,
670
4413
  mutationAddCount: 0,
671
4414
  mutationRemoveCount: 0,
672
4415
  mutationTextCount: 0,
673
- mutationAttributeCount: 0
4416
+ mutationAttributeCount: 0,
4417
+ fullSnapshotCount: 0,
4418
+ fullSnapshotDuration: 0
674
4419
  }
675
4420
  }
676
4421
 
@@ -681,12 +4426,31 @@ function accumulateReplayPerformanceStats(stats, delta) {
681
4426
 
682
4427
  stats.processMutationsCount += delta.processMutationsCount || 0
683
4428
  stats.processMutationsDuration += delta.processMutationsDuration || 0
4429
+ stats.mutationSerializationCount += delta.mutationSerializationCount || 0
4430
+ stats.mutationSerializationDuration +=
4431
+ delta.mutationSerializationDuration || 0
4432
+ stats.mutationLocalDropCount += delta.mutationLocalDropCount || 0
4433
+ if (delta.mutationLocalDropReason) {
4434
+ stats.mutationLocalDropLastReason = delta.mutationLocalDropReason
4435
+ }
4436
+ stats.mutationDropRecoveryCount += delta.mutationDropRecoveryCount || 0
4437
+ if (delta.mutationDropRecoveryLastReason) {
4438
+ stats.mutationDropRecoveryLastReason =
4439
+ delta.mutationDropRecoveryLastReason
4440
+ }
4441
+ stats.admissionGapRecoveryCount += delta.admissionGapRecoveryCount || 0
4442
+ if (delta.admissionGapRecoveryLastReason) {
4443
+ stats.admissionGapRecoveryLastReason =
4444
+ delta.admissionGapRecoveryLastReason
4445
+ }
684
4446
  stats.mutationCallbackCount += delta.mutationCallbackCount || 0
685
4447
  stats.mutationRecordCount += delta.mutationRecordCount || 0
686
4448
  stats.mutationAddCount += delta.mutationAddCount || 0
687
4449
  stats.mutationRemoveCount += delta.mutationRemoveCount || 0
688
4450
  stats.mutationTextCount += delta.mutationTextCount || 0
689
4451
  stats.mutationAttributeCount += delta.mutationAttributeCount || 0
4452
+ stats.fullSnapshotCount += delta.fullSnapshotCount || 0
4453
+ stats.fullSnapshotDuration += delta.fullSnapshotDuration || 0
690
4454
  }
691
4455
 
692
4456
  function countMutationPayloadRecords(mutation) {
@@ -707,22 +4471,46 @@ function cloneReplayPerformanceStats(stats) {
707
4471
  processMutationsCount: stats.processMutationsCount,
708
4472
  processMutationsDuration:
709
4473
  Math.round(stats.processMutationsDuration * 10) / 10,
4474
+ mutationSerializationCount: stats.mutationSerializationCount,
4475
+ mutationSerializationDuration:
4476
+ Math.round(stats.mutationSerializationDuration * 10) / 10,
4477
+ mutationLocalDropCount: stats.mutationLocalDropCount,
4478
+ mutationLocalDropLastReason: stats.mutationLocalDropLastReason,
4479
+ mutationDropRecoveryCount: stats.mutationDropRecoveryCount,
4480
+ mutationDropRecoveryLastReason:
4481
+ stats.mutationDropRecoveryLastReason,
4482
+ admissionGapRecoveryCount: stats.admissionGapRecoveryCount,
4483
+ admissionGapRecoveryLastReason:
4484
+ stats.admissionGapRecoveryLastReason,
710
4485
  mutationCallbackCount: stats.mutationCallbackCount,
711
4486
  mutationRecordCount: stats.mutationRecordCount,
712
4487
  mutationAddCount: stats.mutationAddCount,
713
4488
  mutationRemoveCount: stats.mutationRemoveCount,
714
4489
  mutationTextCount: stats.mutationTextCount,
715
- mutationAttributeCount: stats.mutationAttributeCount
4490
+ mutationAttributeCount: stats.mutationAttributeCount,
4491
+ fullSnapshotCount: stats.fullSnapshotCount,
4492
+ fullSnapshotDuration:
4493
+ Math.round(stats.fullSnapshotDuration * 10) / 10
4494
+ }
4495
+ }
4496
+
4497
+ function getPerformanceTime() {
4498
+ if (typeof performance !== 'undefined' && performance.now) {
4499
+ return performance.now()
716
4500
  }
4501
+ return Date.now()
717
4502
  }
718
4503
 
719
- function pushCanvasDebugHistoryEntry(history, entry) {
4504
+ function pushCanvasDebugHistoryEntry(history, entry, limit) {
720
4505
  if (!entry) {
721
4506
  return
722
4507
  }
723
4508
 
4509
+ if (typeof limit !== 'number') {
4510
+ limit = CANVAS_DEBUG_HISTORY_LIMIT
4511
+ }
724
4512
  history.push(entry)
725
- if (history.length > CANVAS_DEBUG_HISTORY_LIMIT) {
4513
+ if (history.length > limit) {
726
4514
  history.shift()
727
4515
  }
728
4516
  }
@@ -826,18 +4614,23 @@ function cloneCanvasMutationDebugResult(result) {
826
4614
  return clonedResult
827
4615
  }
828
4616
 
829
- function cloneDomMutationDebugResult(result) {
4617
+ function createDomMutationDebugSummary(result) {
830
4618
  if (!result) {
831
4619
  return result
832
4620
  }
833
4621
 
834
4622
  return {
835
- timestamp:
836
- typeof result.timestamp === 'number' ? result.timestamp : timeStampNow(),
837
- adds: (result.adds || []).map(cloneDebugValue),
838
- removes: (result.removes || []).map(cloneDebugValue),
839
- texts: (result.texts || []).map(cloneDebugValue),
840
- attributes: (result.attributes || []).map(cloneDebugValue),
4623
+ timestamp: timeStampNow(),
4624
+ adds: summarizeDomMutationEntries(result.adds, summarizeAddMutation),
4625
+ removes: summarizeDomMutationEntries(
4626
+ result.removes,
4627
+ summarizeRemoveMutation
4628
+ ),
4629
+ texts: summarizeDomMutationEntries(result.texts, summarizeTextMutation),
4630
+ attributes: summarizeDomMutationEntries(
4631
+ result.attributes,
4632
+ summarizeAttributeMutation
4633
+ ),
841
4634
  addsCount: (result.adds || []).length,
842
4635
  removesCount: (result.removes || []).length,
843
4636
  textsCount: (result.texts || []).length,
@@ -845,16 +4638,94 @@ function cloneDomMutationDebugResult(result) {
845
4638
  }
846
4639
  }
847
4640
 
848
- function cloneDebugValue(value) {
849
- if (!value || typeof value !== 'object') {
850
- return value
4641
+ function summarizeDomMutationEntries(entries, summarizeEntry) {
4642
+ var summaries = []
4643
+ var entryCount = Math.min(
4644
+ (entries || []).length,
4645
+ DOM_MUTATION_DEBUG_SAMPLE_LIMIT
4646
+ )
4647
+ for (var index = 0; index < entryCount; index += 1) {
4648
+ summaries.push(summarizeEntry(entries[index]))
4649
+ }
4650
+ return summaries
4651
+ }
4652
+
4653
+ function summarizeAddMutation(add) {
4654
+ var summary = {
4655
+ parentId: add.parentId,
4656
+ nextId: add.nextId
4657
+ }
4658
+ if (add.node) {
4659
+ summary.node = {
4660
+ id: add.node.id,
4661
+ type: add.node.type,
4662
+ tagName: add.node.tagName
4663
+ }
4664
+ }
4665
+ return summary
4666
+ }
4667
+
4668
+ function summarizeRemoveMutation(remove) {
4669
+ return {
4670
+ parentId: remove.parentId,
4671
+ id: remove.id
4672
+ }
4673
+ }
4674
+
4675
+ function summarizeTextMutation(textMutation) {
4676
+ return {
4677
+ id: textMutation.id,
4678
+ valueLength:
4679
+ typeof textMutation.value === 'string' ? textMutation.value.length : 0
4680
+ }
4681
+ }
4682
+
4683
+ function summarizeAttributeMutation(attributeMutation) {
4684
+ var attributeNames = []
4685
+ var attributeNamesTruncated = false
4686
+ var attributes = attributeMutation.attributes || {}
4687
+ for (var attributeName in attributes) {
4688
+ if (!Object.prototype.hasOwnProperty.call(attributes, attributeName)) {
4689
+ continue
4690
+ }
4691
+ if (attributeNames.length >= DOM_MUTATION_DEBUG_SAMPLE_LIMIT) {
4692
+ attributeNamesTruncated = true
4693
+ break
4694
+ }
4695
+ attributeNames.push(attributeName)
4696
+ }
4697
+ return {
4698
+ id: attributeMutation.id,
4699
+ attributeNames: attributeNames,
4700
+ attributeNamesTruncated: attributeNamesTruncated
4701
+ }
4702
+ }
4703
+
4704
+ function cloneDomMutationDebugResult(result) {
4705
+ if (!result) {
4706
+ return result
851
4707
  }
852
- if (Array.isArray(value)) {
853
- return value.map(cloneDebugValue)
4708
+
4709
+ return {
4710
+ timestamp: result.timestamp,
4711
+ adds: result.adds.map(cloneDomMutationDebugEntry),
4712
+ removes: result.removes.map(cloneDomMutationDebugEntry),
4713
+ texts: result.texts.map(cloneDomMutationDebugEntry),
4714
+ attributes: result.attributes.map(cloneDomMutationDebugEntry),
4715
+ addsCount: result.addsCount,
4716
+ removesCount: result.removesCount,
4717
+ textsCount: result.textsCount,
4718
+ attributesCount: result.attributesCount
854
4719
  }
4720
+ }
855
4721
 
856
- return Object.keys(value).reduce(function (accumulator, key) {
857
- accumulator[key] = cloneDebugValue(value[key])
858
- return accumulator
859
- }, {})
4722
+ function cloneDomMutationDebugEntry(entry) {
4723
+ var clonedEntry = assign({}, entry)
4724
+ if (entry.node) {
4725
+ clonedEntry.node = assign({}, entry.node)
4726
+ }
4727
+ if (entry.attributeNames) {
4728
+ clonedEntry.attributeNames = entry.attributeNames.slice()
4729
+ }
4730
+ return clonedEntry
860
4731
  }