@highlight-run/rrweb 1.2.1 → 2.0.4

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 (191) hide show
  1. package/dist/plugins/console-record.js +454 -0
  2. package/dist/plugins/console-record.min.js +12 -15
  3. package/dist/plugins/console-record.min.js.map +1 -1
  4. package/dist/plugins/console-replay.js +164 -0
  5. package/dist/plugins/console-replay.min.js +5 -0
  6. package/dist/plugins/console-replay.min.js.map +1 -0
  7. package/dist/plugins/sequential-id-record.js +30 -0
  8. package/dist/plugins/sequential-id-record.min.js +2 -0
  9. package/dist/plugins/sequential-id-record.min.js.map +1 -0
  10. package/dist/plugins/sequential-id-replay.js +33 -0
  11. package/dist/plugins/sequential-id-replay.min.js +2 -0
  12. package/dist/plugins/sequential-id-replay.min.js.map +1 -0
  13. package/dist/record/rrweb-record-pack.js +664 -0
  14. package/dist/record/rrweb-record-pack.min.js +4 -0
  15. package/dist/record/rrweb-record-pack.min.js.map +1 -0
  16. package/dist/record/rrweb-record.js +3202 -0
  17. package/dist/record/rrweb-record.min.js +5 -0
  18. package/dist/record/rrweb-record.min.js.map +1 -0
  19. package/dist/replay/rrweb-replay-unpack.js +4926 -0
  20. package/dist/replay/rrweb-replay-unpack.min.js +18 -0
  21. package/dist/replay/rrweb-replay-unpack.min.js.map +1 -0
  22. package/dist/replay/rrweb-replay.js +4518 -0
  23. package/dist/replay/rrweb-replay.min.js +18 -0
  24. package/dist/replay/rrweb-replay.min.js.map +1 -0
  25. package/dist/rrweb-all.js +8889 -0
  26. package/dist/rrweb-all.min.js +29 -0
  27. package/dist/rrweb-all.min.js.map +1 -0
  28. package/dist/rrweb.js +7558 -0
  29. package/dist/rrweb.min.js +6 -17
  30. package/dist/rrweb.min.js.map +1 -1
  31. package/es/rrweb/_virtual/_rollup-plugin-web-worker-loader__helper__auto__createBase64WorkerFactory.js +12 -0
  32. package/es/rrweb/_virtual/_rollup-plugin-web-worker-loader__helper__auto__isNodeJS.js +7 -0
  33. package/es/rrweb/_virtual/_rollup-plugin-web-worker-loader__helper__browser__createBase64WorkerFactory.js +31 -0
  34. package/es/rrweb/_virtual/_rollup-plugin-web-worker-loader__helper__node__WorkerClass.js +11 -0
  35. package/es/rrweb/_virtual/_rollup-plugin-web-worker-loader__helper__node__createBase64WorkerFactory.js +18 -0
  36. package/es/rrweb/_virtual/image-bitmap-data-url-worker.js +6 -0
  37. package/es/rrweb/ext/@xstate/fsm/es/index.js +17 -0
  38. package/es/rrweb/ext/base64-arraybuffer/dist/base64-arraybuffer.es5.js +49 -0
  39. package/es/rrweb/ext/fflate/esm/browser.js +777 -0
  40. package/es/rrweb/ext/mitt/dist/mitt.es.js +63 -0
  41. package/es/rrweb/ext/tslib/tslib.es6.js +38 -0
  42. package/es/rrweb/packages/rrdom/es/virtual-dom.js +1099 -0
  43. package/es/rrweb/packages/rrweb/src/entries/all.js +13 -0
  44. package/es/rrweb/packages/rrweb/src/index.js +14 -0
  45. package/es/rrweb/packages/rrweb/src/packer/base.js +3 -0
  46. package/es/rrweb/packages/rrweb/src/packer/pack.js +9 -0
  47. package/es/rrweb/packages/rrweb/src/packer/unpack.js +29 -0
  48. package/es/rrweb/packages/rrweb/src/plugins/console/record/error-stack-parser.js +178 -0
  49. package/es/rrweb/packages/rrweb/src/plugins/console/record/index.js +115 -0
  50. package/es/rrweb/packages/rrweb/src/plugins/console/record/stringify.js +128 -0
  51. package/es/rrweb/packages/rrweb/src/plugins/console/replay/index.js +94 -0
  52. package/es/rrweb/packages/rrweb/src/plugins/sequential-id/record/index.js +22 -0
  53. package/es/rrweb/packages/rrweb/src/plugins/sequential-id/replay/index.js +28 -0
  54. package/es/rrweb/packages/rrweb/src/record/iframe-manager.js +31 -0
  55. package/es/rrweb/packages/rrweb/src/record/index.js +356 -0
  56. package/es/rrweb/packages/rrweb/src/record/mutation.js +491 -0
  57. package/es/rrweb/packages/rrweb/src/record/observer.js +590 -0
  58. package/es/rrweb/packages/rrweb/src/record/observers/canvas/2d.js +49 -0
  59. package/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js +172 -0
  60. package/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas.js +25 -0
  61. package/es/rrweb/packages/rrweb/src/record/observers/canvas/serialize-args.js +123 -0
  62. package/es/rrweb/packages/rrweb/src/record/observers/canvas/webgl.js +59 -0
  63. package/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js +43 -0
  64. package/es/rrweb/packages/rrweb/src/record/stylesheet-manager.js +31 -0
  65. package/es/rrweb/packages/rrweb/src/replay/canvas/2d.js +29 -0
  66. package/es/rrweb/packages/rrweb/src/replay/canvas/deserialize-args.js +67 -0
  67. package/es/rrweb/packages/rrweb/src/replay/canvas/index.js +43 -0
  68. package/es/rrweb/packages/rrweb/src/replay/canvas/webgl.js +62 -0
  69. package/es/rrweb/packages/rrweb/src/replay/index.js +1555 -0
  70. package/es/rrweb/packages/rrweb/src/replay/machine.js +281 -0
  71. package/es/rrweb/packages/rrweb/src/replay/smoothscroll.js +219 -0
  72. package/es/rrweb/packages/rrweb/src/replay/styles/inject-style.js +8 -0
  73. package/es/rrweb/packages/rrweb/src/replay/timer.js +92 -0
  74. package/es/rrweb/packages/rrweb/src/types.js +75 -0
  75. package/es/rrweb/packages/rrweb/src/utils.js +315 -0
  76. package/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js +1821 -0
  77. package/lib/plugins/console-record.js +492 -0
  78. package/lib/plugins/console-replay.js +218 -0
  79. package/lib/plugins/sequential-id-record.js +27 -0
  80. package/lib/plugins/sequential-id-replay.js +32 -0
  81. package/lib/record/rrweb-record-pack.js +787 -0
  82. package/lib/record/rrweb-record.js +3363 -0
  83. package/lib/replay/rrweb-replay-unpack.js +5075 -0
  84. package/lib/replay/rrweb-replay.js +4665 -0
  85. package/lib/rrweb-all.js +9181 -0
  86. package/lib/rrweb.js +7814 -0
  87. package/package.json +41 -42
  88. package/typings/entries/all.d.ts +6 -0
  89. package/{dist → typings}/entries/record-pack.d.ts +0 -0
  90. package/{dist → typings}/entries/replay-unpack.d.ts +0 -0
  91. package/{dist → typings}/index.d.ts +1 -2
  92. package/{dist → typings}/packer/base.d.ts +1 -1
  93. package/{dist → typings}/packer/index.d.ts +0 -0
  94. package/{dist → typings}/packer/pack.d.ts +0 -0
  95. package/{dist → typings}/packer/unpack.d.ts +0 -0
  96. package/{dist → typings}/plugins/console/record/error-stack-parser.d.ts +0 -0
  97. package/{dist → typings}/plugins/console/record/index.d.ts +4 -3
  98. package/{dist → typings}/plugins/console/record/stringify.d.ts +1 -1
  99. package/{dist → typings}/plugins/console/replay/index.d.ts +2 -2
  100. package/{dist → typings}/plugins/sequential-id/record/index.d.ts +1 -1
  101. package/{dist → typings}/plugins/sequential-id/replay/index.d.ts +1 -1
  102. package/{dist → typings}/record/iframe-manager.d.ts +3 -3
  103. package/{dist/plugins → typings}/record/index.d.ts +9 -9
  104. package/{dist → typings}/record/mutation.d.ts +6 -8
  105. package/typings/record/observer.d.ts +7 -0
  106. package/{dist/plugins → typings}/record/observers/canvas/2d.d.ts +3 -2
  107. package/{dist → typings}/record/observers/canvas/canvas-manager.d.ts +5 -2
  108. package/{dist/plugins → typings}/record/observers/canvas/canvas.d.ts +2 -2
  109. package/typings/record/observers/canvas/serialize-args.d.ts +6 -0
  110. package/{dist/plugins → typings}/record/observers/canvas/webgl.d.ts +3 -2
  111. package/typings/record/observers/canvas/webgl2.d.ts +2 -0
  112. package/typings/record/shadow-dom-manager.d.ts +22 -0
  113. package/typings/record/stylesheet-manager.d.ts +12 -0
  114. package/typings/record/workers/image-bitmap-data-url-worker.d.ts +5 -0
  115. package/{dist → typings}/replay/canvas/2d.d.ts +3 -3
  116. package/typings/replay/canvas/deserialize-args.d.ts +7 -0
  117. package/{dist/plugins → typings}/replay/canvas/index.d.ts +10 -9
  118. package/typings/replay/canvas/webgl.d.ts +9 -0
  119. package/{dist → typings}/replay/index.d.ts +7 -9
  120. package/{dist → typings}/replay/machine.d.ts +0 -0
  121. package/{dist → typings}/replay/smoothscroll.d.ts +0 -0
  122. package/{dist → typings}/replay/styles/inject-style.d.ts +0 -0
  123. package/{dist → typings}/replay/timer.d.ts +0 -0
  124. package/{dist → typings}/rrdom/index.d.ts +0 -0
  125. package/{dist → typings}/rrdom/tree-node.d.ts +0 -0
  126. package/{dist/plugins → typings}/types.d.ts +536 -509
  127. package/typings/utils.d.ts +43 -0
  128. package/CHANGELOG.md +0 -26
  129. package/README.md +0 -124
  130. package/README.zh_CN.md +0 -122
  131. package/dist/entries/all.d.ts +0 -4
  132. package/dist/index.css +0 -82
  133. package/dist/index.css.map +0 -1
  134. package/dist/index.js +0 -3
  135. package/dist/index.js.LICENSE.txt +0 -14
  136. package/dist/index.js.map +0 -1
  137. package/dist/plugins/entries/all.d.ts +0 -4
  138. package/dist/plugins/entries/record-pack.d.ts +0 -2
  139. package/dist/plugins/entries/replay-unpack.d.ts +0 -2
  140. package/dist/plugins/index.d.ts +0 -9
  141. package/dist/plugins/packer/base.d.ts +0 -7
  142. package/dist/plugins/packer/index.d.ts +0 -2
  143. package/dist/plugins/packer/pack.d.ts +0 -2
  144. package/dist/plugins/packer/unpack.d.ts +0 -2
  145. package/dist/plugins/plugins/console/record/error-stack-parser.d.ts +0 -37
  146. package/dist/plugins/plugins/console/record/index.d.ts +0 -41
  147. package/dist/plugins/plugins/console/record/stringify.d.ts +0 -2
  148. package/dist/plugins/plugins/console/replay/index.d.ts +0 -9
  149. package/dist/plugins/plugins/sequential-id/record/index.d.ts +0 -6
  150. package/dist/plugins/plugins/sequential-id/replay/index.d.ts +0 -7
  151. package/dist/plugins/record/iframe-manager.d.ts +0 -13
  152. package/dist/plugins/record/mutation.d.ts +0 -45
  153. package/dist/plugins/record/observer.d.ts +0 -11
  154. package/dist/plugins/record/observers/canvas/canvas-manager.d.ts +0 -32
  155. package/dist/plugins/record/observers/canvas/serialize-args.d.ts +0 -6
  156. package/dist/plugins/record/shadow-dom-manager.d.ts +0 -34
  157. package/dist/plugins/replay/canvas/2d.d.ts +0 -9
  158. package/dist/plugins/replay/canvas/webgl.d.ts +0 -11
  159. package/dist/plugins/replay/index.d.ts +0 -82
  160. package/dist/plugins/replay/machine.d.ts +0 -85
  161. package/dist/plugins/replay/smoothscroll.d.ts +0 -1
  162. package/dist/plugins/replay/styles/inject-style.d.ts +0 -2
  163. package/dist/plugins/replay/timer.d.ts +0 -19
  164. package/dist/plugins/replay/virtual-styles.d.ts +0 -43
  165. package/dist/plugins/rrdom/index.d.ts +0 -1
  166. package/dist/plugins/rrdom/tree-node.d.ts +0 -20
  167. package/dist/plugins/snapshot/css.d.ts +0 -92
  168. package/dist/plugins/snapshot/index.d.ts +0 -5
  169. package/dist/plugins/snapshot/rebuild.d.ts +0 -19
  170. package/dist/plugins/snapshot/snapshot.d.ts +0 -49
  171. package/dist/plugins/snapshot/types.d.ts +0 -99
  172. package/dist/plugins/snapshot/utils.d.ts +0 -11
  173. package/dist/plugins/utils.d.ts +0 -71
  174. package/dist/record/index.d.ts +0 -9
  175. package/dist/record/observer.d.ts +0 -11
  176. package/dist/record/observers/canvas/2d.d.ts +0 -2
  177. package/dist/record/observers/canvas/canvas.d.ts +0 -2
  178. package/dist/record/observers/canvas/serialize-args.d.ts +0 -6
  179. package/dist/record/observers/canvas/webgl.d.ts +0 -2
  180. package/dist/record/shadow-dom-manager.d.ts +0 -34
  181. package/dist/replay/canvas/index.d.ts +0 -9
  182. package/dist/replay/canvas/webgl.d.ts +0 -11
  183. package/dist/replay/virtual-styles.d.ts +0 -43
  184. package/dist/snapshot/css.d.ts +0 -92
  185. package/dist/snapshot/index.d.ts +0 -5
  186. package/dist/snapshot/rebuild.d.ts +0 -19
  187. package/dist/snapshot/snapshot.d.ts +0 -49
  188. package/dist/snapshot/types.d.ts +0 -99
  189. package/dist/snapshot/utils.d.ts +0 -11
  190. package/dist/types.d.ts +0 -509
  191. package/dist/utils.d.ts +0 -71
@@ -0,0 +1,4926 @@
1
+ var rrwebReplay = (function (exports) {
2
+ 'use strict';
3
+
4
+ var NodeType$2;
5
+ (function(NodeType2) {
6
+ NodeType2[NodeType2["Document"] = 0] = "Document";
7
+ NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
8
+ NodeType2[NodeType2["Element"] = 2] = "Element";
9
+ NodeType2[NodeType2["Text"] = 3] = "Text";
10
+ NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
11
+ NodeType2[NodeType2["Comment"] = 5] = "Comment";
12
+ })(NodeType$2 || (NodeType$2 = {}));
13
+ function isElement(n) {
14
+ return n.nodeType === n.ELEMENT_NODE;
15
+ }
16
+ var Mirror$2 = function() {
17
+ function Mirror2() {
18
+ this.idNodeMap = /* @__PURE__ */ new Map();
19
+ this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
20
+ }
21
+ Mirror2.prototype.getId = function(n) {
22
+ var _a;
23
+ if (!n)
24
+ return -1;
25
+ var id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;
26
+ return id !== null && id !== void 0 ? id : -1;
27
+ };
28
+ Mirror2.prototype.getNode = function(id) {
29
+ return this.idNodeMap.get(id) || null;
30
+ };
31
+ Mirror2.prototype.getIds = function() {
32
+ return Array.from(this.idNodeMap.keys());
33
+ };
34
+ Mirror2.prototype.getMeta = function(n) {
35
+ return this.nodeMetaMap.get(n) || null;
36
+ };
37
+ Mirror2.prototype.removeNodeFromMap = function(n) {
38
+ var _this = this;
39
+ var id = this.getId(n);
40
+ this.idNodeMap["delete"](id);
41
+ if (n.childNodes) {
42
+ n.childNodes.forEach(function(childNode) {
43
+ return _this.removeNodeFromMap(childNode);
44
+ });
45
+ }
46
+ };
47
+ Mirror2.prototype.has = function(id) {
48
+ return this.idNodeMap.has(id);
49
+ };
50
+ Mirror2.prototype.hasNode = function(node) {
51
+ return this.nodeMetaMap.has(node);
52
+ };
53
+ Mirror2.prototype.add = function(n, meta) {
54
+ var id = meta.id;
55
+ this.idNodeMap.set(id, n);
56
+ this.nodeMetaMap.set(n, meta);
57
+ };
58
+ Mirror2.prototype.replace = function(id, n) {
59
+ this.idNodeMap.set(id, n);
60
+ };
61
+ Mirror2.prototype.reset = function() {
62
+ this.idNodeMap = /* @__PURE__ */ new Map();
63
+ this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
64
+ };
65
+ return Mirror2;
66
+ }();
67
+ function createMirror$2() {
68
+ return new Mirror$2();
69
+ }
70
+ var commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;
71
+ function parse(css, options) {
72
+ if (options === void 0) {
73
+ options = {};
74
+ }
75
+ var lineno = 1;
76
+ var column = 1;
77
+ function updatePosition(str) {
78
+ var lines = str.match(/\n/g);
79
+ if (lines) {
80
+ lineno += lines.length;
81
+ }
82
+ var i = str.lastIndexOf("\n");
83
+ column = i === -1 ? column + str.length : str.length - i;
84
+ }
85
+ function position() {
86
+ var start = { line: lineno, column };
87
+ return function(node) {
88
+ node.position = new Position(start);
89
+ whitespace();
90
+ return node;
91
+ };
92
+ }
93
+ var Position = function() {
94
+ function Position2(start) {
95
+ this.start = start;
96
+ this.end = { line: lineno, column };
97
+ this.source = options.source;
98
+ }
99
+ return Position2;
100
+ }();
101
+ Position.prototype.content = css;
102
+ var errorsList = [];
103
+ function error(msg) {
104
+ var err = new Error(options.source + ":" + lineno + ":" + column + ": " + msg);
105
+ err.reason = msg;
106
+ err.filename = options.source;
107
+ err.line = lineno;
108
+ err.column = column;
109
+ err.source = css;
110
+ if (options.silent) {
111
+ errorsList.push(err);
112
+ } else {
113
+ throw err;
114
+ }
115
+ }
116
+ function stylesheet() {
117
+ var rulesList = rules();
118
+ return {
119
+ type: "stylesheet",
120
+ stylesheet: {
121
+ source: options.source,
122
+ rules: rulesList,
123
+ parsingErrors: errorsList
124
+ }
125
+ };
126
+ }
127
+ function open() {
128
+ return match(/^{\s*/);
129
+ }
130
+ function close() {
131
+ return match(/^}/);
132
+ }
133
+ function rules() {
134
+ var node;
135
+ var rules2 = [];
136
+ whitespace();
137
+ comments(rules2);
138
+ while (css.length && css.charAt(0) !== "}" && (node = atrule() || rule())) {
139
+ if (node !== false) {
140
+ rules2.push(node);
141
+ comments(rules2);
142
+ }
143
+ }
144
+ return rules2;
145
+ }
146
+ function match(re) {
147
+ var m = re.exec(css);
148
+ if (!m) {
149
+ return;
150
+ }
151
+ var str = m[0];
152
+ updatePosition(str);
153
+ css = css.slice(str.length);
154
+ return m;
155
+ }
156
+ function whitespace() {
157
+ match(/^\s*/);
158
+ }
159
+ function comments(rules2) {
160
+ if (rules2 === void 0) {
161
+ rules2 = [];
162
+ }
163
+ var c;
164
+ while (c = comment()) {
165
+ if (c !== false) {
166
+ rules2.push(c);
167
+ }
168
+ c = comment();
169
+ }
170
+ return rules2;
171
+ }
172
+ function comment() {
173
+ var pos = position();
174
+ if (css.charAt(0) !== "/" || css.charAt(1) !== "*") {
175
+ return;
176
+ }
177
+ var i = 2;
178
+ while (css.charAt(i) !== "" && (css.charAt(i) !== "*" || css.charAt(i + 1) !== "/")) {
179
+ ++i;
180
+ }
181
+ i += 2;
182
+ if (css.charAt(i - 1) === "") {
183
+ return error("End of comment missing");
184
+ }
185
+ var str = css.slice(2, i - 2);
186
+ column += 2;
187
+ updatePosition(str);
188
+ css = css.slice(i);
189
+ column += 2;
190
+ return pos({
191
+ type: "comment",
192
+ comment: str
193
+ });
194
+ }
195
+ function selector() {
196
+ var m = match(/^([^{]+)/);
197
+ if (!m) {
198
+ return;
199
+ }
200
+ return trim(m[0]).replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, "").replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(m2) {
201
+ return m2.replace(/,/g, "\u200C");
202
+ }).split(/\s*(?![^(]*\)),\s*/).map(function(s) {
203
+ return s.replace(/\u200C/g, ",");
204
+ });
205
+ }
206
+ function declaration() {
207
+ var pos = position();
208
+ var propMatch = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);
209
+ if (!propMatch) {
210
+ return;
211
+ }
212
+ var prop = trim(propMatch[0]);
213
+ if (!match(/^:\s*/)) {
214
+ return error("property missing ':'");
215
+ }
216
+ var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/);
217
+ var ret = pos({
218
+ type: "declaration",
219
+ property: prop.replace(commentre, ""),
220
+ value: val ? trim(val[0]).replace(commentre, "") : ""
221
+ });
222
+ match(/^[;\s]*/);
223
+ return ret;
224
+ }
225
+ function declarations() {
226
+ var decls = [];
227
+ if (!open()) {
228
+ return error("missing '{'");
229
+ }
230
+ comments(decls);
231
+ var decl;
232
+ while (decl = declaration()) {
233
+ if (decl !== false) {
234
+ decls.push(decl);
235
+ comments(decls);
236
+ }
237
+ decl = declaration();
238
+ }
239
+ if (!close()) {
240
+ return error("missing '}'");
241
+ }
242
+ return decls;
243
+ }
244
+ function keyframe() {
245
+ var m;
246
+ var vals = [];
247
+ var pos = position();
248
+ while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) {
249
+ vals.push(m[1]);
250
+ match(/^,\s*/);
251
+ }
252
+ if (!vals.length) {
253
+ return;
254
+ }
255
+ return pos({
256
+ type: "keyframe",
257
+ values: vals,
258
+ declarations: declarations()
259
+ });
260
+ }
261
+ function atkeyframes() {
262
+ var pos = position();
263
+ var m = match(/^@([-\w]+)?keyframes\s*/);
264
+ if (!m) {
265
+ return;
266
+ }
267
+ var vendor = m[1];
268
+ m = match(/^([-\w]+)\s*/);
269
+ if (!m) {
270
+ return error("@keyframes missing name");
271
+ }
272
+ var name = m[1];
273
+ if (!open()) {
274
+ return error("@keyframes missing '{'");
275
+ }
276
+ var frame;
277
+ var frames = comments();
278
+ while (frame = keyframe()) {
279
+ frames.push(frame);
280
+ frames = frames.concat(comments());
281
+ }
282
+ if (!close()) {
283
+ return error("@keyframes missing '}'");
284
+ }
285
+ return pos({
286
+ type: "keyframes",
287
+ name,
288
+ vendor,
289
+ keyframes: frames
290
+ });
291
+ }
292
+ function atsupports() {
293
+ var pos = position();
294
+ var m = match(/^@supports *([^{]+)/);
295
+ if (!m) {
296
+ return;
297
+ }
298
+ var supports = trim(m[1]);
299
+ if (!open()) {
300
+ return error("@supports missing '{'");
301
+ }
302
+ var style = comments().concat(rules());
303
+ if (!close()) {
304
+ return error("@supports missing '}'");
305
+ }
306
+ return pos({
307
+ type: "supports",
308
+ supports,
309
+ rules: style
310
+ });
311
+ }
312
+ function athost() {
313
+ var pos = position();
314
+ var m = match(/^@host\s*/);
315
+ if (!m) {
316
+ return;
317
+ }
318
+ if (!open()) {
319
+ return error("@host missing '{'");
320
+ }
321
+ var style = comments().concat(rules());
322
+ if (!close()) {
323
+ return error("@host missing '}'");
324
+ }
325
+ return pos({
326
+ type: "host",
327
+ rules: style
328
+ });
329
+ }
330
+ function atmedia() {
331
+ var pos = position();
332
+ var m = match(/^@media *([^{]+)/);
333
+ if (!m) {
334
+ return;
335
+ }
336
+ var media = trim(m[1]);
337
+ if (!open()) {
338
+ return error("@media missing '{'");
339
+ }
340
+ var style = comments().concat(rules());
341
+ if (!close()) {
342
+ return error("@media missing '}'");
343
+ }
344
+ return pos({
345
+ type: "media",
346
+ media,
347
+ rules: style
348
+ });
349
+ }
350
+ function atcustommedia() {
351
+ var pos = position();
352
+ var m = match(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/);
353
+ if (!m) {
354
+ return;
355
+ }
356
+ return pos({
357
+ type: "custom-media",
358
+ name: trim(m[1]),
359
+ media: trim(m[2])
360
+ });
361
+ }
362
+ function atpage() {
363
+ var pos = position();
364
+ var m = match(/^@page */);
365
+ if (!m) {
366
+ return;
367
+ }
368
+ var sel = selector() || [];
369
+ if (!open()) {
370
+ return error("@page missing '{'");
371
+ }
372
+ var decls = comments();
373
+ var decl;
374
+ while (decl = declaration()) {
375
+ decls.push(decl);
376
+ decls = decls.concat(comments());
377
+ }
378
+ if (!close()) {
379
+ return error("@page missing '}'");
380
+ }
381
+ return pos({
382
+ type: "page",
383
+ selectors: sel,
384
+ declarations: decls
385
+ });
386
+ }
387
+ function atdocument() {
388
+ var pos = position();
389
+ var m = match(/^@([-\w]+)?document *([^{]+)/);
390
+ if (!m) {
391
+ return;
392
+ }
393
+ var vendor = trim(m[1]);
394
+ var doc = trim(m[2]);
395
+ if (!open()) {
396
+ return error("@document missing '{'");
397
+ }
398
+ var style = comments().concat(rules());
399
+ if (!close()) {
400
+ return error("@document missing '}'");
401
+ }
402
+ return pos({
403
+ type: "document",
404
+ document: doc,
405
+ vendor,
406
+ rules: style
407
+ });
408
+ }
409
+ function atfontface() {
410
+ var pos = position();
411
+ var m = match(/^@font-face\s*/);
412
+ if (!m) {
413
+ return;
414
+ }
415
+ if (!open()) {
416
+ return error("@font-face missing '{'");
417
+ }
418
+ var decls = comments();
419
+ var decl;
420
+ while (decl = declaration()) {
421
+ decls.push(decl);
422
+ decls = decls.concat(comments());
423
+ }
424
+ if (!close()) {
425
+ return error("@font-face missing '}'");
426
+ }
427
+ return pos({
428
+ type: "font-face",
429
+ declarations: decls
430
+ });
431
+ }
432
+ var atimport = _compileAtrule("import");
433
+ var atcharset = _compileAtrule("charset");
434
+ var atnamespace = _compileAtrule("namespace");
435
+ function _compileAtrule(name) {
436
+ var re = new RegExp("^@" + name + "\\s*([^;]+);");
437
+ return function() {
438
+ var pos = position();
439
+ var m = match(re);
440
+ if (!m) {
441
+ return;
442
+ }
443
+ var ret = { type: name };
444
+ ret[name] = m[1].trim();
445
+ return pos(ret);
446
+ };
447
+ }
448
+ function atrule() {
449
+ if (css[0] !== "@") {
450
+ return;
451
+ }
452
+ return atkeyframes() || atmedia() || atcustommedia() || atsupports() || atimport() || atcharset() || atnamespace() || atdocument() || atpage() || athost() || atfontface();
453
+ }
454
+ function rule() {
455
+ var pos = position();
456
+ var sel = selector();
457
+ if (!sel) {
458
+ return error("selector missing");
459
+ }
460
+ comments();
461
+ return pos({
462
+ type: "rule",
463
+ selectors: sel,
464
+ declarations: declarations()
465
+ });
466
+ }
467
+ return addParent(stylesheet());
468
+ }
469
+ function trim(str) {
470
+ return str ? str.replace(/^\s+|\s+$/g, "") : "";
471
+ }
472
+ function addParent(obj, parent) {
473
+ var isNode = obj && typeof obj.type === "string";
474
+ var childParent = isNode ? obj : parent;
475
+ for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {
476
+ var k = _a[_i];
477
+ var value = obj[k];
478
+ if (Array.isArray(value)) {
479
+ value.forEach(function(v) {
480
+ addParent(v, childParent);
481
+ });
482
+ } else if (value && typeof value === "object") {
483
+ addParent(value, childParent);
484
+ }
485
+ }
486
+ if (isNode) {
487
+ Object.defineProperty(obj, "parent", {
488
+ configurable: true,
489
+ writable: true,
490
+ enumerable: false,
491
+ value: parent || null
492
+ });
493
+ }
494
+ return obj;
495
+ }
496
+ var tagMap = {
497
+ script: "noscript",
498
+ altglyph: "altGlyph",
499
+ altglyphdef: "altGlyphDef",
500
+ altglyphitem: "altGlyphItem",
501
+ animatecolor: "animateColor",
502
+ animatemotion: "animateMotion",
503
+ animatetransform: "animateTransform",
504
+ clippath: "clipPath",
505
+ feblend: "feBlend",
506
+ fecolormatrix: "feColorMatrix",
507
+ fecomponenttransfer: "feComponentTransfer",
508
+ fecomposite: "feComposite",
509
+ feconvolvematrix: "feConvolveMatrix",
510
+ fediffuselighting: "feDiffuseLighting",
511
+ fedisplacementmap: "feDisplacementMap",
512
+ fedistantlight: "feDistantLight",
513
+ fedropshadow: "feDropShadow",
514
+ feflood: "feFlood",
515
+ fefunca: "feFuncA",
516
+ fefuncb: "feFuncB",
517
+ fefuncg: "feFuncG",
518
+ fefuncr: "feFuncR",
519
+ fegaussianblur: "feGaussianBlur",
520
+ feimage: "feImage",
521
+ femerge: "feMerge",
522
+ femergenode: "feMergeNode",
523
+ femorphology: "feMorphology",
524
+ feoffset: "feOffset",
525
+ fepointlight: "fePointLight",
526
+ fespecularlighting: "feSpecularLighting",
527
+ fespotlight: "feSpotLight",
528
+ fetile: "feTile",
529
+ feturbulence: "feTurbulence",
530
+ foreignobject: "foreignObject",
531
+ glyphref: "glyphRef",
532
+ lineargradient: "linearGradient",
533
+ radialgradient: "radialGradient"
534
+ };
535
+ function getTagName(n) {
536
+ var tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;
537
+ if (tagName === "link" && n.attributes._cssText) {
538
+ tagName = "style";
539
+ }
540
+ return tagName;
541
+ }
542
+ function escapeRegExp(str) {
543
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
544
+ }
545
+ var HOVER_SELECTOR = /([^\\]):hover/;
546
+ var HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, "g");
547
+ function addHoverClass(cssText, cache) {
548
+ var _a;
549
+ if (!((_a = window.HIG_CONFIGURATION) === null || _a === void 0 ? void 0 : _a.enableOnHoverClass)) {
550
+ return cssText;
551
+ }
552
+ var cachedStyle = cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.get(cssText);
553
+ if (cachedStyle)
554
+ return cachedStyle;
555
+ var ast = parse(cssText, {
556
+ silent: true
557
+ });
558
+ if (!ast.stylesheet) {
559
+ return cssText;
560
+ }
561
+ var selectors = [];
562
+ ast.stylesheet.rules.forEach(function(rule) {
563
+ if ("selectors" in rule) {
564
+ (rule.selectors || []).forEach(function(selector) {
565
+ if (HOVER_SELECTOR.test(selector)) {
566
+ selectors.push(selector);
567
+ }
568
+ });
569
+ }
570
+ });
571
+ if (selectors.length === 0) {
572
+ return cssText;
573
+ }
574
+ var selectorMatcher = new RegExp(selectors.filter(function(selector, index) {
575
+ return selectors.indexOf(selector) === index;
576
+ }).sort(function(a, b) {
577
+ return b.length - a.length;
578
+ }).map(function(selector) {
579
+ return escapeRegExp(selector);
580
+ }).join("|"), "g");
581
+ var result = cssText.replace(selectorMatcher, function(selector) {
582
+ var newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, "$1.\\:hover");
583
+ return selector + ", " + newSelector;
584
+ });
585
+ cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.set(cssText, result);
586
+ return result;
587
+ }
588
+ function createCache() {
589
+ var stylesWithHoverClass = /* @__PURE__ */ new Map();
590
+ return {
591
+ stylesWithHoverClass
592
+ };
593
+ }
594
+ function buildNode(n, options) {
595
+ var doc = options.doc, hackCss = options.hackCss, cache = options.cache;
596
+ switch (n.type) {
597
+ case NodeType$2.Document:
598
+ return doc.implementation.createDocument(null, "", null);
599
+ case NodeType$2.DocumentType:
600
+ return doc.implementation.createDocumentType(n.name || "html", n.publicId, n.systemId);
601
+ case NodeType$2.Element:
602
+ var tagName = getTagName(n);
603
+ var node_1;
604
+ if (n.isSVG) {
605
+ node_1 = doc.createElementNS("http://www.w3.org/2000/svg", tagName);
606
+ } else {
607
+ node_1 = doc.createElement(tagName);
608
+ }
609
+ var _loop_1 = function(name_12) {
610
+ if (!n.attributes.hasOwnProperty(name_12)) {
611
+ return "continue";
612
+ }
613
+ var value = n.attributes[name_12];
614
+ if (tagName === "option" && name_12 === "selected" && value === false) {
615
+ return "continue";
616
+ }
617
+ value = typeof value === "boolean" || typeof value === "number" ? "" : value;
618
+ if (!name_12.startsWith("rr_")) {
619
+ var isTextarea = tagName === "textarea" && name_12 === "value";
620
+ var isRemoteOrDynamicCss = tagName === "style" && name_12 === "_cssText";
621
+ if (isRemoteOrDynamicCss && hackCss) {
622
+ value = addHoverClass(value, cache);
623
+ if (typeof value === "string") {
624
+ var regex = /url\(\"https:\/\/\S*(.eot|.woff2|.ttf|.woff)\S*\"\)/gm;
625
+ var m = void 0;
626
+ var fontUrls_1 = [];
627
+ var PROXY_URL_1 = "https://replay-cors-proxy.highlightrun.workers.dev";
628
+ while ((m = regex.exec(value)) !== null) {
629
+ if (m.index === regex.lastIndex) {
630
+ regex.lastIndex++;
631
+ }
632
+ m.forEach(function(match, groupIndex) {
633
+ if (groupIndex === 0) {
634
+ var url = match.slice(5, match.length - 2);
635
+ fontUrls_1.push({
636
+ originalUrl: url,
637
+ proxyUrl: url.replace(url, PROXY_URL_1 + "?url=" + url)
638
+ });
639
+ }
640
+ });
641
+ }
642
+ fontUrls_1.forEach(function(urlPair) {
643
+ value = value.replace(urlPair.originalUrl, urlPair.proxyUrl);
644
+ });
645
+ }
646
+ }
647
+ if (isTextarea || isRemoteOrDynamicCss) {
648
+ var child = doc.createTextNode(value);
649
+ for (var _i = 0, _a = Array.from(node_1.childNodes); _i < _a.length; _i++) {
650
+ var c = _a[_i];
651
+ if (c.nodeType === node_1.TEXT_NODE) {
652
+ node_1.removeChild(c);
653
+ }
654
+ }
655
+ node_1.appendChild(child);
656
+ return "continue";
657
+ }
658
+ try {
659
+ if (n.isSVG && name_12 === "xlink:href") {
660
+ node_1.setAttributeNS("http://www.w3.org/1999/xlink", name_12, value);
661
+ } else if (name_12 === "onload" || name_12 === "onclick" || name_12.substring(0, 7) === "onmouse") {
662
+ node_1.setAttribute("_" + name_12, value);
663
+ } else if (tagName === "meta" && n.attributes["http-equiv"] === "Content-Security-Policy" && name_12 === "content") {
664
+ node_1.setAttribute("csp-content", value);
665
+ return "continue";
666
+ } else if (tagName === "link" && n.attributes.rel === "preload" && n.attributes.as === "script") {
667
+ } else if (tagName === "link" && n.attributes.rel === "prefetch" && typeof n.attributes.href === "string" && n.attributes.href.endsWith(".js")) {
668
+ } else if (tagName === "img" && n.attributes.srcset && n.attributes.rr_dataURL) {
669
+ node_1.setAttribute("rrweb-original-srcset", n.attributes.srcset);
670
+ } else {
671
+ node_1.setAttribute(name_12, value);
672
+ }
673
+ } catch (error) {
674
+ }
675
+ } else {
676
+ if (tagName === "canvas" && name_12 === "rr_dataURL") {
677
+ var image_1 = document.createElement("img");
678
+ image_1.src = value;
679
+ image_1.onload = function() {
680
+ var ctx = node_1.getContext("2d");
681
+ if (ctx) {
682
+ ctx.drawImage(image_1, 0, 0, image_1.width, image_1.height);
683
+ }
684
+ };
685
+ } else if (tagName === "img" && name_12 === "rr_dataURL") {
686
+ var image = node_1;
687
+ if (!image.currentSrc.startsWith("data:")) {
688
+ image.setAttribute("rrweb-original-src", n.attributes.src);
689
+ image.src = value;
690
+ }
691
+ }
692
+ if (name_12 === "rr_width") {
693
+ node_1.style.width = value;
694
+ } else if (name_12 === "rr_height") {
695
+ node_1.style.height = value;
696
+ } else if (name_12 === "rr_mediaCurrentTime") {
697
+ node_1.currentTime = n.attributes.rr_mediaCurrentTime;
698
+ } else if (name_12 === "rr_mediaState") {
699
+ switch (value) {
700
+ case "played":
701
+ node_1.play()["catch"](function(e) {
702
+ return console.warn("media playback error", e);
703
+ });
704
+ break;
705
+ case "paused":
706
+ node_1.pause();
707
+ break;
708
+ }
709
+ }
710
+ }
711
+ };
712
+ for (var name_1 in n.attributes) {
713
+ _loop_1(name_1);
714
+ }
715
+ if (n.isShadowHost) {
716
+ if (!node_1.shadowRoot) {
717
+ node_1.attachShadow({ mode: "open" });
718
+ } else {
719
+ while (node_1.shadowRoot.firstChild) {
720
+ node_1.shadowRoot.removeChild(node_1.shadowRoot.firstChild);
721
+ }
722
+ }
723
+ }
724
+ return node_1;
725
+ case NodeType$2.Text:
726
+ return doc.createTextNode(n.isStyle && hackCss ? addHoverClass(n.textContent, cache) : n.textContent);
727
+ case NodeType$2.CDATA:
728
+ return doc.createCDATASection(n.textContent);
729
+ case NodeType$2.Comment:
730
+ return doc.createComment(n.textContent);
731
+ default:
732
+ return null;
733
+ }
734
+ }
735
+ function buildNodeWithSN(n, options) {
736
+ var doc = options.doc, mirror = options.mirror, _a = options.skipChild, skipChild = _a === void 0 ? false : _a, _b = options.hackCss, hackCss = _b === void 0 ? true : _b, afterAppend = options.afterAppend, cache = options.cache;
737
+ var node = buildNode(n, { doc, hackCss, cache });
738
+ if (!node) {
739
+ return null;
740
+ }
741
+ if (n.rootId) {
742
+ console.assert(mirror.getNode(n.rootId) === doc, "Target document should have the same root id.");
743
+ }
744
+ if (n.type === NodeType$2.Document) {
745
+ doc.close();
746
+ doc.open();
747
+ if (n.compatMode === "BackCompat" && n.childNodes && n.childNodes[0].type !== NodeType$2.DocumentType) {
748
+ if (n.childNodes[0].type === NodeType$2.Element && "xmlns" in n.childNodes[0].attributes && n.childNodes[0].attributes.xmlns === "http://www.w3.org/1999/xhtml") {
749
+ doc.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">');
750
+ } else {
751
+ doc.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "">');
752
+ }
753
+ }
754
+ node = doc;
755
+ }
756
+ mirror.add(node, n);
757
+ if ((n.type === NodeType$2.Document || n.type === NodeType$2.Element) && !skipChild) {
758
+ for (var _i = 0, _c = n.childNodes; _i < _c.length; _i++) {
759
+ var childN = _c[_i];
760
+ var childNode = buildNodeWithSN(childN, {
761
+ doc,
762
+ mirror,
763
+ skipChild: false,
764
+ hackCss,
765
+ afterAppend,
766
+ cache
767
+ });
768
+ if (!childNode) {
769
+ console.warn("Failed to rebuild", childN);
770
+ continue;
771
+ }
772
+ if (childN.isShadow && isElement(node) && node.shadowRoot) {
773
+ node.shadowRoot.appendChild(childNode);
774
+ } else {
775
+ node.appendChild(childNode);
776
+ }
777
+ if (afterAppend) {
778
+ afterAppend(childNode);
779
+ }
780
+ }
781
+ }
782
+ return node;
783
+ }
784
+ function visit(mirror, onVisit) {
785
+ function walk(node) {
786
+ onVisit(node);
787
+ }
788
+ for (var _i = 0, _a = mirror.getIds(); _i < _a.length; _i++) {
789
+ var id = _a[_i];
790
+ if (mirror.has(id)) {
791
+ walk(mirror.getNode(id));
792
+ }
793
+ }
794
+ }
795
+ function handleScroll(node, mirror) {
796
+ var n = mirror.getMeta(node);
797
+ if ((n === null || n === void 0 ? void 0 : n.type) !== NodeType$2.Element) {
798
+ return;
799
+ }
800
+ var el = node;
801
+ for (var name_2 in n.attributes) {
802
+ if (!(n.attributes.hasOwnProperty(name_2) && name_2.startsWith("rr_"))) {
803
+ continue;
804
+ }
805
+ var value = n.attributes[name_2];
806
+ if (name_2 === "rr_scrollLeft") {
807
+ el.scrollLeft = value;
808
+ }
809
+ if (name_2 === "rr_scrollTop") {
810
+ el.scrollTop = value;
811
+ }
812
+ }
813
+ }
814
+ function rebuild(n, options) {
815
+ var doc = options.doc, onVisit = options.onVisit, _a = options.hackCss, hackCss = _a === void 0 ? true : _a, afterAppend = options.afterAppend, cache = options.cache, _b = options.mirror, mirror = _b === void 0 ? new Mirror$2() : _b;
816
+ var node = buildNodeWithSN(n, {
817
+ doc,
818
+ mirror,
819
+ skipChild: false,
820
+ hackCss,
821
+ afterAppend,
822
+ cache
823
+ });
824
+ visit(mirror, function(visitedNode) {
825
+ if (onVisit) {
826
+ onVisit(visitedNode);
827
+ }
828
+ handleScroll(visitedNode, mirror);
829
+ });
830
+ return node;
831
+ }
832
+
833
+ var NodeType$1;
834
+ (function(NodeType2) {
835
+ NodeType2[NodeType2["Document"] = 0] = "Document";
836
+ NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
837
+ NodeType2[NodeType2["Element"] = 2] = "Element";
838
+ NodeType2[NodeType2["Text"] = 3] = "Text";
839
+ NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
840
+ NodeType2[NodeType2["Comment"] = 5] = "Comment";
841
+ })(NodeType$1 || (NodeType$1 = {}));
842
+ var Mirror$1 = function() {
843
+ function Mirror2() {
844
+ this.idNodeMap = /* @__PURE__ */ new Map();
845
+ this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
846
+ }
847
+ Mirror2.prototype.getId = function(n) {
848
+ var _a;
849
+ if (!n)
850
+ return -1;
851
+ var id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;
852
+ return id !== null && id !== void 0 ? id : -1;
853
+ };
854
+ Mirror2.prototype.getNode = function(id) {
855
+ return this.idNodeMap.get(id) || null;
856
+ };
857
+ Mirror2.prototype.getIds = function() {
858
+ return Array.from(this.idNodeMap.keys());
859
+ };
860
+ Mirror2.prototype.getMeta = function(n) {
861
+ return this.nodeMetaMap.get(n) || null;
862
+ };
863
+ Mirror2.prototype.removeNodeFromMap = function(n) {
864
+ var _this = this;
865
+ var id = this.getId(n);
866
+ this.idNodeMap["delete"](id);
867
+ if (n.childNodes) {
868
+ n.childNodes.forEach(function(childNode) {
869
+ return _this.removeNodeFromMap(childNode);
870
+ });
871
+ }
872
+ };
873
+ Mirror2.prototype.has = function(id) {
874
+ return this.idNodeMap.has(id);
875
+ };
876
+ Mirror2.prototype.hasNode = function(node) {
877
+ return this.nodeMetaMap.has(node);
878
+ };
879
+ Mirror2.prototype.add = function(n, meta) {
880
+ var id = meta.id;
881
+ this.idNodeMap.set(id, n);
882
+ this.nodeMetaMap.set(n, meta);
883
+ };
884
+ Mirror2.prototype.replace = function(id, n) {
885
+ this.idNodeMap.set(id, n);
886
+ };
887
+ Mirror2.prototype.reset = function() {
888
+ this.idNodeMap = /* @__PURE__ */ new Map();
889
+ this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
890
+ };
891
+ return Mirror2;
892
+ }();
893
+ function createMirror$1() {
894
+ return new Mirror$1();
895
+ }
896
+ function parseCSSText(cssText) {
897
+ const res = {};
898
+ const listDelimiter = /;(?![^(]*\))/g;
899
+ const propertyDelimiter = /:(.+)/;
900
+ const comment = /\/\*.*?\*\//g;
901
+ cssText.replace(comment, "").split(listDelimiter).forEach(function(item) {
902
+ if (item) {
903
+ const tmp = item.split(propertyDelimiter);
904
+ tmp.length > 1 && (res[camelize(tmp[0].trim())] = tmp[1].trim());
905
+ }
906
+ });
907
+ return res;
908
+ }
909
+ function toCSSText(style) {
910
+ const properties = [];
911
+ for (const name in style) {
912
+ const value = style[name];
913
+ if (typeof value !== "string")
914
+ continue;
915
+ const normalizedName = hyphenate(name);
916
+ properties.push(`${normalizedName}: ${value};`);
917
+ }
918
+ return properties.join(" ");
919
+ }
920
+ const camelizeRE = /-([a-z])/g;
921
+ const CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9-]+$/;
922
+ const camelize = (str) => {
923
+ if (CUSTOM_PROPERTY_REGEX.test(str))
924
+ return str;
925
+ return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
926
+ };
927
+ const hyphenateRE = /\B([A-Z])/g;
928
+ const hyphenate = (str) => {
929
+ return str.replace(hyphenateRE, "-$1").toLowerCase();
930
+ };
931
+ class BaseRRNode {
932
+ constructor(...args) {
933
+ this.childNodes = [];
934
+ this.parentElement = null;
935
+ this.parentNode = null;
936
+ this.ELEMENT_NODE = NodeType.ELEMENT_NODE;
937
+ this.TEXT_NODE = NodeType.TEXT_NODE;
938
+ }
939
+ get firstChild() {
940
+ return this.childNodes[0] || null;
941
+ }
942
+ get lastChild() {
943
+ return this.childNodes[this.childNodes.length - 1] || null;
944
+ }
945
+ get nextSibling() {
946
+ const parentNode = this.parentNode;
947
+ if (!parentNode)
948
+ return null;
949
+ const siblings = parentNode.childNodes;
950
+ const index = siblings.indexOf(this);
951
+ return siblings[index + 1] || null;
952
+ }
953
+ contains(node) {
954
+ if (node === this)
955
+ return true;
956
+ for (const child of this.childNodes) {
957
+ if (child.contains(node))
958
+ return true;
959
+ }
960
+ return false;
961
+ }
962
+ appendChild(_newChild) {
963
+ throw new Error(`RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.`);
964
+ }
965
+ insertBefore(_newChild, _refChild) {
966
+ throw new Error(`RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.`);
967
+ }
968
+ removeChild(node) {
969
+ throw new Error(`RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.`);
970
+ }
971
+ toString() {
972
+ return "RRNode";
973
+ }
974
+ }
975
+ function BaseRRDocumentImpl(RRNodeClass) {
976
+ return class BaseRRDocument extends RRNodeClass {
977
+ constructor() {
978
+ super(...arguments);
979
+ this.nodeType = NodeType.DOCUMENT_NODE;
980
+ this.nodeName = "#document";
981
+ this.compatMode = "CSS1Compat";
982
+ this.RRNodeType = NodeType$1.Document;
983
+ this.textContent = null;
984
+ }
985
+ get documentElement() {
986
+ return this.childNodes.find((node) => node.RRNodeType === NodeType$1.Element && node.tagName === "HTML") || null;
987
+ }
988
+ get body() {
989
+ var _a;
990
+ return ((_a = this.documentElement) === null || _a === void 0 ? void 0 : _a.childNodes.find((node) => node.RRNodeType === NodeType$1.Element && node.tagName === "BODY")) || null;
991
+ }
992
+ get head() {
993
+ var _a;
994
+ return ((_a = this.documentElement) === null || _a === void 0 ? void 0 : _a.childNodes.find((node) => node.RRNodeType === NodeType$1.Element && node.tagName === "HEAD")) || null;
995
+ }
996
+ get implementation() {
997
+ return this;
998
+ }
999
+ get firstElementChild() {
1000
+ return this.documentElement;
1001
+ }
1002
+ appendChild(childNode) {
1003
+ const nodeType = childNode.RRNodeType;
1004
+ if (nodeType === NodeType$1.Element || nodeType === NodeType$1.DocumentType) {
1005
+ if (this.childNodes.some((s) => s.RRNodeType === nodeType)) {
1006
+ throw new Error(`RRDomException: Failed to execute 'appendChild' on 'RRNode': Only one ${nodeType === NodeType$1.Element ? "RRElement" : "RRDoctype"} on RRDocument allowed.`);
1007
+ }
1008
+ }
1009
+ childNode.parentElement = null;
1010
+ childNode.parentNode = this;
1011
+ this.childNodes.push(childNode);
1012
+ return childNode;
1013
+ }
1014
+ insertBefore(newChild, refChild) {
1015
+ const nodeType = newChild.RRNodeType;
1016
+ if (nodeType === NodeType$1.Element || nodeType === NodeType$1.DocumentType) {
1017
+ if (this.childNodes.some((s) => s.RRNodeType === nodeType)) {
1018
+ throw new Error(`RRDomException: Failed to execute 'insertBefore' on 'RRNode': Only one ${nodeType === NodeType$1.Element ? "RRElement" : "RRDoctype"} on RRDocument allowed.`);
1019
+ }
1020
+ }
1021
+ if (refChild === null)
1022
+ return this.appendChild(newChild);
1023
+ const childIndex = this.childNodes.indexOf(refChild);
1024
+ if (childIndex == -1)
1025
+ throw new Error("Failed to execute 'insertBefore' on 'RRNode': The RRNode before which the new node is to be inserted is not a child of this RRNode.");
1026
+ this.childNodes.splice(childIndex, 0, newChild);
1027
+ newChild.parentElement = null;
1028
+ newChild.parentNode = this;
1029
+ return newChild;
1030
+ }
1031
+ removeChild(node) {
1032
+ const indexOfChild = this.childNodes.indexOf(node);
1033
+ if (indexOfChild === -1)
1034
+ throw new Error("Failed to execute 'removeChild' on 'RRDocument': The RRNode to be removed is not a child of this RRNode.");
1035
+ this.childNodes.splice(indexOfChild, 1);
1036
+ node.parentElement = null;
1037
+ node.parentNode = null;
1038
+ return node;
1039
+ }
1040
+ open() {
1041
+ this.childNodes = [];
1042
+ }
1043
+ close() {
1044
+ }
1045
+ write(content) {
1046
+ let publicId;
1047
+ if (content === '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">')
1048
+ publicId = "-//W3C//DTD XHTML 1.0 Transitional//EN";
1049
+ else if (content === '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "">')
1050
+ publicId = "-//W3C//DTD HTML 4.0 Transitional//EN";
1051
+ if (publicId) {
1052
+ const doctype = this.createDocumentType("html", publicId, "");
1053
+ this.open();
1054
+ this.appendChild(doctype);
1055
+ }
1056
+ }
1057
+ createDocument(_namespace, _qualifiedName, _doctype) {
1058
+ return new BaseRRDocument();
1059
+ }
1060
+ createDocumentType(qualifiedName, publicId, systemId) {
1061
+ const doctype = new (BaseRRDocumentTypeImpl(BaseRRNode))(qualifiedName, publicId, systemId);
1062
+ doctype.ownerDocument = this;
1063
+ return doctype;
1064
+ }
1065
+ createElement(tagName) {
1066
+ const element = new (BaseRRElementImpl(BaseRRNode))(tagName);
1067
+ element.ownerDocument = this;
1068
+ return element;
1069
+ }
1070
+ createElementNS(_namespaceURI, qualifiedName) {
1071
+ return this.createElement(qualifiedName);
1072
+ }
1073
+ createTextNode(data) {
1074
+ const text = new (BaseRRTextImpl(BaseRRNode))(data);
1075
+ text.ownerDocument = this;
1076
+ return text;
1077
+ }
1078
+ createComment(data) {
1079
+ const comment = new (BaseRRCommentImpl(BaseRRNode))(data);
1080
+ comment.ownerDocument = this;
1081
+ return comment;
1082
+ }
1083
+ createCDATASection(data) {
1084
+ const CDATASection = new (BaseRRCDATASectionImpl(BaseRRNode))(data);
1085
+ CDATASection.ownerDocument = this;
1086
+ return CDATASection;
1087
+ }
1088
+ toString() {
1089
+ return "RRDocument";
1090
+ }
1091
+ };
1092
+ }
1093
+ function BaseRRDocumentTypeImpl(RRNodeClass) {
1094
+ return class BaseRRDocumentType extends RRNodeClass {
1095
+ constructor(qualifiedName, publicId, systemId) {
1096
+ super();
1097
+ this.nodeType = NodeType.DOCUMENT_TYPE_NODE;
1098
+ this.RRNodeType = NodeType$1.DocumentType;
1099
+ this.textContent = null;
1100
+ this.name = qualifiedName;
1101
+ this.publicId = publicId;
1102
+ this.systemId = systemId;
1103
+ this.nodeName = qualifiedName;
1104
+ }
1105
+ toString() {
1106
+ return "RRDocumentType";
1107
+ }
1108
+ };
1109
+ }
1110
+ function BaseRRElementImpl(RRNodeClass) {
1111
+ return class BaseRRElement extends RRNodeClass {
1112
+ constructor(tagName) {
1113
+ super();
1114
+ this.nodeType = NodeType.ELEMENT_NODE;
1115
+ this.RRNodeType = NodeType$1.Element;
1116
+ this.attributes = {};
1117
+ this.shadowRoot = null;
1118
+ this.tagName = tagName.toUpperCase();
1119
+ this.nodeName = tagName.toUpperCase();
1120
+ }
1121
+ get textContent() {
1122
+ let result = "";
1123
+ this.childNodes.forEach((node) => result += node.textContent);
1124
+ return result;
1125
+ }
1126
+ set textContent(textContent) {
1127
+ this.childNodes = [this.ownerDocument.createTextNode(textContent)];
1128
+ }
1129
+ get classList() {
1130
+ return new ClassList(this.attributes.class, (newClassName) => {
1131
+ this.attributes.class = newClassName;
1132
+ });
1133
+ }
1134
+ get id() {
1135
+ return this.attributes.id || "";
1136
+ }
1137
+ get className() {
1138
+ return this.attributes.class || "";
1139
+ }
1140
+ get style() {
1141
+ const style = this.attributes.style ? parseCSSText(this.attributes.style) : {};
1142
+ const hyphenateRE2 = /\B([A-Z])/g;
1143
+ style.setProperty = (name, value, priority) => {
1144
+ if (hyphenateRE2.test(name))
1145
+ return;
1146
+ const normalizedName = camelize(name);
1147
+ if (!value)
1148
+ delete style[normalizedName];
1149
+ else
1150
+ style[normalizedName] = value;
1151
+ if (priority === "important")
1152
+ style[normalizedName] += " !important";
1153
+ this.attributes.style = toCSSText(style);
1154
+ };
1155
+ style.removeProperty = (name) => {
1156
+ if (hyphenateRE2.test(name))
1157
+ return "";
1158
+ const normalizedName = camelize(name);
1159
+ const value = style[normalizedName] || "";
1160
+ delete style[normalizedName];
1161
+ this.attributes.style = toCSSText(style);
1162
+ return value;
1163
+ };
1164
+ return style;
1165
+ }
1166
+ getAttribute(name) {
1167
+ return this.attributes[name] || null;
1168
+ }
1169
+ setAttribute(name, attribute) {
1170
+ this.attributes[name] = attribute;
1171
+ }
1172
+ setAttributeNS(_namespace, qualifiedName, value) {
1173
+ this.setAttribute(qualifiedName, value);
1174
+ }
1175
+ removeAttribute(name) {
1176
+ delete this.attributes[name];
1177
+ }
1178
+ appendChild(newChild) {
1179
+ this.childNodes.push(newChild);
1180
+ newChild.parentNode = this;
1181
+ newChild.parentElement = this;
1182
+ return newChild;
1183
+ }
1184
+ insertBefore(newChild, refChild) {
1185
+ if (refChild === null)
1186
+ return this.appendChild(newChild);
1187
+ const childIndex = this.childNodes.indexOf(refChild);
1188
+ if (childIndex == -1)
1189
+ throw new Error("Failed to execute 'insertBefore' on 'RRNode': The RRNode before which the new node is to be inserted is not a child of this RRNode.");
1190
+ this.childNodes.splice(childIndex, 0, newChild);
1191
+ newChild.parentElement = this;
1192
+ newChild.parentNode = this;
1193
+ return newChild;
1194
+ }
1195
+ removeChild(node) {
1196
+ const indexOfChild = this.childNodes.indexOf(node);
1197
+ if (indexOfChild === -1)
1198
+ throw new Error("Failed to execute 'removeChild' on 'RRElement': The RRNode to be removed is not a child of this RRNode.");
1199
+ this.childNodes.splice(indexOfChild, 1);
1200
+ node.parentElement = null;
1201
+ node.parentNode = null;
1202
+ return node;
1203
+ }
1204
+ attachShadow(_init) {
1205
+ const shadowRoot = this.ownerDocument.createElement("SHADOWROOT");
1206
+ this.shadowRoot = shadowRoot;
1207
+ return shadowRoot;
1208
+ }
1209
+ dispatchEvent(_event) {
1210
+ return true;
1211
+ }
1212
+ toString() {
1213
+ let attributeString = "";
1214
+ for (const attribute in this.attributes) {
1215
+ attributeString += `${attribute}="${this.attributes[attribute]}" `;
1216
+ }
1217
+ return `${this.tagName} ${attributeString}`;
1218
+ }
1219
+ };
1220
+ }
1221
+ function BaseRRMediaElementImpl(RRElementClass) {
1222
+ return class BaseRRMediaElement extends RRElementClass {
1223
+ attachShadow(_init) {
1224
+ throw new Error(`RRDomException: Failed to execute 'attachShadow' on 'RRElement': This RRElement does not support attachShadow`);
1225
+ }
1226
+ play() {
1227
+ this.paused = false;
1228
+ }
1229
+ pause() {
1230
+ this.paused = true;
1231
+ }
1232
+ };
1233
+ }
1234
+ function BaseRRTextImpl(RRNodeClass) {
1235
+ return class BaseRRText extends RRNodeClass {
1236
+ constructor(data) {
1237
+ super();
1238
+ this.nodeType = NodeType.TEXT_NODE;
1239
+ this.nodeName = "#text";
1240
+ this.RRNodeType = NodeType$1.Text;
1241
+ this.data = data;
1242
+ }
1243
+ get textContent() {
1244
+ return this.data;
1245
+ }
1246
+ set textContent(textContent) {
1247
+ this.data = textContent;
1248
+ }
1249
+ toString() {
1250
+ return `RRText text=${JSON.stringify(this.data)}`;
1251
+ }
1252
+ };
1253
+ }
1254
+ function BaseRRCommentImpl(RRNodeClass) {
1255
+ return class BaseRRComment extends RRNodeClass {
1256
+ constructor(data) {
1257
+ super();
1258
+ this.nodeType = NodeType.COMMENT_NODE;
1259
+ this.nodeName = "#comment";
1260
+ this.RRNodeType = NodeType$1.Comment;
1261
+ this.data = data;
1262
+ }
1263
+ get textContent() {
1264
+ return this.data;
1265
+ }
1266
+ set textContent(textContent) {
1267
+ this.data = textContent;
1268
+ }
1269
+ toString() {
1270
+ return `RRComment text=${JSON.stringify(this.data)}`;
1271
+ }
1272
+ };
1273
+ }
1274
+ function BaseRRCDATASectionImpl(RRNodeClass) {
1275
+ return class BaseRRCDATASection extends RRNodeClass {
1276
+ constructor(data) {
1277
+ super();
1278
+ this.nodeName = "#cdata-section";
1279
+ this.nodeType = NodeType.CDATA_SECTION_NODE;
1280
+ this.RRNodeType = NodeType$1.CDATA;
1281
+ this.data = data;
1282
+ }
1283
+ get textContent() {
1284
+ return this.data;
1285
+ }
1286
+ set textContent(textContent) {
1287
+ this.data = textContent;
1288
+ }
1289
+ toString() {
1290
+ return `RRCDATASection data=${JSON.stringify(this.data)}`;
1291
+ }
1292
+ };
1293
+ }
1294
+ class ClassList {
1295
+ constructor(classText, onChange) {
1296
+ this.classes = [];
1297
+ this.add = (...classNames) => {
1298
+ for (const item of classNames) {
1299
+ const className = String(item);
1300
+ if (this.classes.indexOf(className) >= 0)
1301
+ continue;
1302
+ this.classes.push(className);
1303
+ }
1304
+ this.onChange && this.onChange(this.classes.join(" "));
1305
+ };
1306
+ this.remove = (...classNames) => {
1307
+ this.classes = this.classes.filter((item) => classNames.indexOf(item) === -1);
1308
+ this.onChange && this.onChange(this.classes.join(" "));
1309
+ };
1310
+ if (classText) {
1311
+ const classes = classText.trim().split(/\s+/);
1312
+ this.classes.push(...classes);
1313
+ }
1314
+ this.onChange = onChange;
1315
+ }
1316
+ }
1317
+ var NodeType;
1318
+ (function(NodeType2) {
1319
+ NodeType2[NodeType2["PLACEHOLDER"] = 0] = "PLACEHOLDER";
1320
+ NodeType2[NodeType2["ELEMENT_NODE"] = 1] = "ELEMENT_NODE";
1321
+ NodeType2[NodeType2["ATTRIBUTE_NODE"] = 2] = "ATTRIBUTE_NODE";
1322
+ NodeType2[NodeType2["TEXT_NODE"] = 3] = "TEXT_NODE";
1323
+ NodeType2[NodeType2["CDATA_SECTION_NODE"] = 4] = "CDATA_SECTION_NODE";
1324
+ NodeType2[NodeType2["ENTITY_REFERENCE_NODE"] = 5] = "ENTITY_REFERENCE_NODE";
1325
+ NodeType2[NodeType2["ENTITY_NODE"] = 6] = "ENTITY_NODE";
1326
+ NodeType2[NodeType2["PROCESSING_INSTRUCTION_NODE"] = 7] = "PROCESSING_INSTRUCTION_NODE";
1327
+ NodeType2[NodeType2["COMMENT_NODE"] = 8] = "COMMENT_NODE";
1328
+ NodeType2[NodeType2["DOCUMENT_NODE"] = 9] = "DOCUMENT_NODE";
1329
+ NodeType2[NodeType2["DOCUMENT_TYPE_NODE"] = 10] = "DOCUMENT_TYPE_NODE";
1330
+ NodeType2[NodeType2["DOCUMENT_FRAGMENT_NODE"] = 11] = "DOCUMENT_FRAGMENT_NODE";
1331
+ })(NodeType || (NodeType = {}));
1332
+ const NAMESPACES = {
1333
+ svg: "http://www.w3.org/2000/svg",
1334
+ "xlink:href": "http://www.w3.org/1999/xlink",
1335
+ xmlns: "http://www.w3.org/2000/xmlns/"
1336
+ };
1337
+ function diff(oldTree, newTree, replayer, rrnodeMirror) {
1338
+ const oldChildren = oldTree.childNodes;
1339
+ const newChildren = newTree.childNodes;
1340
+ rrnodeMirror = rrnodeMirror || newTree.mirror || newTree.ownerDocument.mirror;
1341
+ if (oldChildren.length > 0 || newChildren.length > 0) {
1342
+ diffChildren(Array.from(oldChildren), newChildren, oldTree, replayer, rrnodeMirror);
1343
+ }
1344
+ let inputDataToApply = null, scrollDataToApply = null;
1345
+ switch (newTree.RRNodeType) {
1346
+ case NodeType$1.Document: {
1347
+ const newRRDocument = newTree;
1348
+ scrollDataToApply = newRRDocument.scrollData;
1349
+ break;
1350
+ }
1351
+ case NodeType$1.Element: {
1352
+ const oldElement = oldTree;
1353
+ const newRRElement = newTree;
1354
+ diffProps(oldElement, newRRElement, rrnodeMirror);
1355
+ scrollDataToApply = newRRElement.scrollData;
1356
+ inputDataToApply = newRRElement.inputData;
1357
+ switch (newRRElement.tagName) {
1358
+ case "AUDIO":
1359
+ case "VIDEO": {
1360
+ const oldMediaElement = oldTree;
1361
+ const newMediaRRElement = newRRElement;
1362
+ if (newMediaRRElement.paused !== void 0)
1363
+ newMediaRRElement.paused ? oldMediaElement.pause() : oldMediaElement.play();
1364
+ if (newMediaRRElement.muted !== void 0)
1365
+ oldMediaElement.muted = newMediaRRElement.muted;
1366
+ if (newMediaRRElement.volume !== void 0)
1367
+ oldMediaElement.volume = newMediaRRElement.volume;
1368
+ if (newMediaRRElement.currentTime !== void 0)
1369
+ oldMediaElement.currentTime = newMediaRRElement.currentTime;
1370
+ break;
1371
+ }
1372
+ case "CANVAS":
1373
+ newTree.canvasMutations.forEach((canvasMutation) => replayer.applyCanvas(canvasMutation.event, canvasMutation.mutation, oldTree));
1374
+ break;
1375
+ case "STYLE":
1376
+ applyVirtualStyleRulesToNode(oldElement, newTree.rules);
1377
+ break;
1378
+ }
1379
+ if (newRRElement.shadowRoot) {
1380
+ if (!oldElement.shadowRoot)
1381
+ oldElement.attachShadow({ mode: "open" });
1382
+ const oldChildren2 = oldElement.shadowRoot.childNodes;
1383
+ const newChildren2 = newRRElement.shadowRoot.childNodes;
1384
+ if (oldChildren2.length > 0 || newChildren2.length > 0)
1385
+ diffChildren(Array.from(oldChildren2), newChildren2, oldElement.shadowRoot, replayer, rrnodeMirror);
1386
+ }
1387
+ break;
1388
+ }
1389
+ case NodeType$1.Text:
1390
+ case NodeType$1.Comment:
1391
+ case NodeType$1.CDATA:
1392
+ if (oldTree.textContent !== newTree.data)
1393
+ oldTree.textContent = newTree.data;
1394
+ break;
1395
+ }
1396
+ scrollDataToApply && replayer.applyScroll(scrollDataToApply, true);
1397
+ inputDataToApply && replayer.applyInput(inputDataToApply);
1398
+ if (newTree.nodeName === "IFRAME") {
1399
+ const oldContentDocument = oldTree.contentDocument;
1400
+ const newIFrameElement = newTree;
1401
+ if (oldContentDocument) {
1402
+ const sn = rrnodeMirror.getMeta(newIFrameElement.contentDocument);
1403
+ if (sn) {
1404
+ replayer.mirror.add(oldContentDocument, Object.assign({}, sn));
1405
+ }
1406
+ diff(oldContentDocument, newIFrameElement.contentDocument, replayer, rrnodeMirror);
1407
+ }
1408
+ }
1409
+ }
1410
+ function diffProps(oldTree, newTree, rrnodeMirror) {
1411
+ const oldAttributes = oldTree.attributes;
1412
+ const newAttributes = newTree.attributes;
1413
+ for (const name in newAttributes) {
1414
+ const newValue = newAttributes[name];
1415
+ const sn = rrnodeMirror.getMeta(newTree);
1416
+ if (sn && "isSVG" in sn && sn.isSVG && NAMESPACES[name])
1417
+ oldTree.setAttributeNS(NAMESPACES[name], name, newValue);
1418
+ else if (newTree.tagName === "CANVAS" && name === "rr_dataURL") {
1419
+ const image = document.createElement("img");
1420
+ image.src = newValue;
1421
+ image.onload = () => {
1422
+ const ctx = oldTree.getContext("2d");
1423
+ if (ctx) {
1424
+ ctx.drawImage(image, 0, 0, image.width, image.height);
1425
+ }
1426
+ };
1427
+ } else
1428
+ oldTree.setAttribute(name, newValue);
1429
+ }
1430
+ for (const { name } of Array.from(oldAttributes))
1431
+ if (!(name in newAttributes))
1432
+ oldTree.removeAttribute(name);
1433
+ newTree.scrollLeft && (oldTree.scrollLeft = newTree.scrollLeft);
1434
+ newTree.scrollTop && (oldTree.scrollTop = newTree.scrollTop);
1435
+ }
1436
+ function diffChildren(oldChildren, newChildren, parentNode, replayer, rrnodeMirror) {
1437
+ var _a, _b;
1438
+ let oldStartIndex = 0, oldEndIndex = oldChildren.length - 1, newStartIndex = 0, newEndIndex = newChildren.length - 1;
1439
+ let oldStartNode = oldChildren[oldStartIndex], oldEndNode = oldChildren[oldEndIndex], newStartNode = newChildren[newStartIndex], newEndNode = newChildren[newEndIndex];
1440
+ let oldIdToIndex = void 0, indexInOld;
1441
+ while (oldStartIndex <= oldEndIndex && newStartIndex <= newEndIndex) {
1442
+ if (oldStartNode === void 0) {
1443
+ oldStartNode = oldChildren[++oldStartIndex];
1444
+ } else if (oldEndNode === void 0) {
1445
+ oldEndNode = oldChildren[--oldEndIndex];
1446
+ } else if (replayer.mirror.getId(oldStartNode) === rrnodeMirror.getId(newStartNode)) {
1447
+ diff(oldStartNode, newStartNode, replayer, rrnodeMirror);
1448
+ oldStartNode = oldChildren[++oldStartIndex];
1449
+ newStartNode = newChildren[++newStartIndex];
1450
+ } else if (replayer.mirror.getId(oldEndNode) === rrnodeMirror.getId(newEndNode)) {
1451
+ diff(oldEndNode, newEndNode, replayer, rrnodeMirror);
1452
+ oldEndNode = oldChildren[--oldEndIndex];
1453
+ newEndNode = newChildren[--newEndIndex];
1454
+ } else if (replayer.mirror.getId(oldStartNode) === rrnodeMirror.getId(newEndNode)) {
1455
+ parentNode.insertBefore(oldStartNode, oldEndNode.nextSibling);
1456
+ diff(oldStartNode, newEndNode, replayer, rrnodeMirror);
1457
+ oldStartNode = oldChildren[++oldStartIndex];
1458
+ newEndNode = newChildren[--newEndIndex];
1459
+ } else if (replayer.mirror.getId(oldEndNode) === rrnodeMirror.getId(newStartNode)) {
1460
+ parentNode.insertBefore(oldEndNode, oldStartNode);
1461
+ diff(oldEndNode, newStartNode, replayer, rrnodeMirror);
1462
+ oldEndNode = oldChildren[--oldEndIndex];
1463
+ newStartNode = newChildren[++newStartIndex];
1464
+ } else {
1465
+ if (!oldIdToIndex) {
1466
+ oldIdToIndex = {};
1467
+ for (let i = oldStartIndex; i <= oldEndIndex; i++) {
1468
+ const oldChild = oldChildren[i];
1469
+ if (oldChild && replayer.mirror.hasNode(oldChild))
1470
+ oldIdToIndex[replayer.mirror.getId(oldChild)] = i;
1471
+ }
1472
+ }
1473
+ indexInOld = oldIdToIndex[rrnodeMirror.getId(newStartNode)];
1474
+ if (indexInOld) {
1475
+ const nodeToMove = oldChildren[indexInOld];
1476
+ parentNode.insertBefore(nodeToMove, oldStartNode);
1477
+ diff(nodeToMove, newStartNode, replayer, rrnodeMirror);
1478
+ oldChildren[indexInOld] = void 0;
1479
+ } else {
1480
+ const newNode = createOrGetNode(newStartNode, replayer.mirror, rrnodeMirror);
1481
+ if (((_a = replayer.mirror.getMeta(parentNode)) === null || _a === void 0 ? void 0 : _a.type) === NodeType$1.Document && ((_b = replayer.mirror.getMeta(newNode)) === null || _b === void 0 ? void 0 : _b.type) === NodeType$1.Element && parentNode.documentElement) {
1482
+ parentNode.removeChild(parentNode.documentElement);
1483
+ oldChildren[oldStartIndex] = void 0;
1484
+ oldStartNode = void 0;
1485
+ }
1486
+ parentNode.insertBefore(newNode, oldStartNode || null);
1487
+ diff(newNode, newStartNode, replayer, rrnodeMirror);
1488
+ }
1489
+ newStartNode = newChildren[++newStartIndex];
1490
+ }
1491
+ }
1492
+ if (oldStartIndex > oldEndIndex) {
1493
+ const referenceRRNode = newChildren[newEndIndex + 1];
1494
+ let referenceNode = null;
1495
+ if (referenceRRNode)
1496
+ parentNode.childNodes.forEach((child) => {
1497
+ if (replayer.mirror.getId(child) === rrnodeMirror.getId(referenceRRNode))
1498
+ referenceNode = child;
1499
+ });
1500
+ for (; newStartIndex <= newEndIndex; ++newStartIndex) {
1501
+ const newNode = createOrGetNode(newChildren[newStartIndex], replayer.mirror, rrnodeMirror);
1502
+ parentNode.insertBefore(newNode, referenceNode);
1503
+ diff(newNode, newChildren[newStartIndex], replayer, rrnodeMirror);
1504
+ }
1505
+ } else if (newStartIndex > newEndIndex) {
1506
+ for (; oldStartIndex <= oldEndIndex; oldStartIndex++) {
1507
+ const node = oldChildren[oldStartIndex];
1508
+ if (node) {
1509
+ parentNode.removeChild(node);
1510
+ replayer.mirror.removeNodeFromMap(node);
1511
+ }
1512
+ }
1513
+ }
1514
+ }
1515
+ function createOrGetNode(rrNode, domMirror, rrnodeMirror) {
1516
+ let node = domMirror.getNode(rrnodeMirror.getId(rrNode));
1517
+ const sn = rrnodeMirror.getMeta(rrNode);
1518
+ if (node !== null)
1519
+ return node;
1520
+ switch (rrNode.RRNodeType) {
1521
+ case NodeType$1.Document:
1522
+ node = new Document();
1523
+ break;
1524
+ case NodeType$1.DocumentType:
1525
+ node = document.implementation.createDocumentType(rrNode.name, rrNode.publicId, rrNode.systemId);
1526
+ break;
1527
+ case NodeType$1.Element: {
1528
+ rrNode.tagName.toLowerCase();
1529
+ if (sn && "isSVG" in sn && (sn === null || sn === void 0 ? void 0 : sn.isSVG)) {
1530
+ node = document.createElementNS(NAMESPACES["svg"], rrNode.tagName.toLowerCase());
1531
+ } else
1532
+ node = document.createElement(rrNode.tagName);
1533
+ break;
1534
+ }
1535
+ case NodeType$1.Text:
1536
+ node = document.createTextNode(rrNode.data);
1537
+ break;
1538
+ case NodeType$1.Comment:
1539
+ node = document.createComment(rrNode.data);
1540
+ break;
1541
+ case NodeType$1.CDATA:
1542
+ node = document.createCDATASection(rrNode.data);
1543
+ break;
1544
+ }
1545
+ if (sn)
1546
+ domMirror.add(node, Object.assign({}, sn));
1547
+ return node;
1548
+ }
1549
+ function getNestedRule$1(rules, position) {
1550
+ const rule = rules[position[0]];
1551
+ if (position.length === 1) {
1552
+ return rule;
1553
+ } else {
1554
+ return getNestedRule$1(rule.cssRules[position[1]].cssRules, position.slice(2));
1555
+ }
1556
+ }
1557
+ var StyleRuleType;
1558
+ (function(StyleRuleType2) {
1559
+ StyleRuleType2[StyleRuleType2["Insert"] = 0] = "Insert";
1560
+ StyleRuleType2[StyleRuleType2["Remove"] = 1] = "Remove";
1561
+ StyleRuleType2[StyleRuleType2["Snapshot"] = 2] = "Snapshot";
1562
+ StyleRuleType2[StyleRuleType2["SetProperty"] = 3] = "SetProperty";
1563
+ StyleRuleType2[StyleRuleType2["RemoveProperty"] = 4] = "RemoveProperty";
1564
+ })(StyleRuleType || (StyleRuleType = {}));
1565
+ function getPositionsAndIndex$1(nestedIndex) {
1566
+ const positions = [...nestedIndex];
1567
+ const index = positions.pop();
1568
+ return { positions, index };
1569
+ }
1570
+ function applyVirtualStyleRulesToNode(styleNode, virtualStyleRules) {
1571
+ const sheet = styleNode.sheet;
1572
+ virtualStyleRules.forEach((rule) => {
1573
+ if (rule.type === StyleRuleType.Insert) {
1574
+ try {
1575
+ if (Array.isArray(rule.index)) {
1576
+ const { positions, index } = getPositionsAndIndex$1(rule.index);
1577
+ const nestedRule = getNestedRule$1(sheet.cssRules, positions);
1578
+ nestedRule.insertRule(rule.cssText, index);
1579
+ } else {
1580
+ sheet.insertRule(rule.cssText, rule.index);
1581
+ }
1582
+ } catch (e) {
1583
+ }
1584
+ } else if (rule.type === StyleRuleType.Remove) {
1585
+ try {
1586
+ if (Array.isArray(rule.index)) {
1587
+ const { positions, index } = getPositionsAndIndex$1(rule.index);
1588
+ const nestedRule = getNestedRule$1(sheet.cssRules, positions);
1589
+ nestedRule.deleteRule(index || 0);
1590
+ } else {
1591
+ sheet.deleteRule(rule.index);
1592
+ }
1593
+ } catch (e) {
1594
+ }
1595
+ } else if (rule.type === StyleRuleType.SetProperty) {
1596
+ const nativeRule = getNestedRule$1(sheet.cssRules, rule.index);
1597
+ nativeRule.style.setProperty(rule.property, rule.value, rule.priority);
1598
+ } else if (rule.type === StyleRuleType.RemoveProperty) {
1599
+ const nativeRule = getNestedRule$1(sheet.cssRules, rule.index);
1600
+ nativeRule.style.removeProperty(rule.property);
1601
+ }
1602
+ });
1603
+ }
1604
+ class RRDocument extends BaseRRDocumentImpl(BaseRRNode) {
1605
+ constructor(mirror) {
1606
+ super();
1607
+ this._unserializedId = -1;
1608
+ this.mirror = createMirror();
1609
+ this.scrollData = null;
1610
+ if (mirror) {
1611
+ this.mirror = mirror;
1612
+ }
1613
+ }
1614
+ get unserializedId() {
1615
+ return this._unserializedId--;
1616
+ }
1617
+ createDocument(_namespace, _qualifiedName, _doctype) {
1618
+ return new RRDocument();
1619
+ }
1620
+ createDocumentType(qualifiedName, publicId, systemId) {
1621
+ const documentTypeNode = new RRDocumentType(qualifiedName, publicId, systemId);
1622
+ documentTypeNode.ownerDocument = this;
1623
+ return documentTypeNode;
1624
+ }
1625
+ createElement(tagName) {
1626
+ const upperTagName = tagName.toUpperCase();
1627
+ let element;
1628
+ switch (upperTagName) {
1629
+ case "AUDIO":
1630
+ case "VIDEO":
1631
+ element = new RRMediaElement(upperTagName);
1632
+ break;
1633
+ case "IFRAME":
1634
+ element = new RRIFrameElement(upperTagName, this.mirror);
1635
+ break;
1636
+ case "CANVAS":
1637
+ element = new RRCanvasElement(upperTagName);
1638
+ break;
1639
+ case "STYLE":
1640
+ element = new RRStyleElement(upperTagName);
1641
+ break;
1642
+ default:
1643
+ element = new RRElement(upperTagName);
1644
+ break;
1645
+ }
1646
+ element.ownerDocument = this;
1647
+ return element;
1648
+ }
1649
+ createComment(data) {
1650
+ const commentNode = new RRComment(data);
1651
+ commentNode.ownerDocument = this;
1652
+ return commentNode;
1653
+ }
1654
+ createCDATASection(data) {
1655
+ const sectionNode = new RRCDATASection(data);
1656
+ sectionNode.ownerDocument = this;
1657
+ return sectionNode;
1658
+ }
1659
+ createTextNode(data) {
1660
+ const textNode = new RRText(data);
1661
+ textNode.ownerDocument = this;
1662
+ return textNode;
1663
+ }
1664
+ destroyTree() {
1665
+ this.childNodes = [];
1666
+ this.mirror.reset();
1667
+ }
1668
+ open() {
1669
+ super.open();
1670
+ this._unserializedId = -1;
1671
+ }
1672
+ }
1673
+ const RRDocumentType = BaseRRDocumentTypeImpl(BaseRRNode);
1674
+ class RRElement extends BaseRRElementImpl(BaseRRNode) {
1675
+ constructor() {
1676
+ super(...arguments);
1677
+ this.inputData = null;
1678
+ this.scrollData = null;
1679
+ }
1680
+ }
1681
+ class RRMediaElement extends BaseRRMediaElementImpl(RRElement) {
1682
+ }
1683
+ class RRCanvasElement extends RRElement {
1684
+ constructor() {
1685
+ super(...arguments);
1686
+ this.canvasMutations = [];
1687
+ }
1688
+ getContext() {
1689
+ return null;
1690
+ }
1691
+ }
1692
+ class RRStyleElement extends RRElement {
1693
+ constructor() {
1694
+ super(...arguments);
1695
+ this.rules = [];
1696
+ }
1697
+ }
1698
+ class RRIFrameElement extends RRElement {
1699
+ constructor(upperTagName, mirror) {
1700
+ super(upperTagName);
1701
+ this.contentDocument = new RRDocument();
1702
+ this.contentDocument.mirror = mirror;
1703
+ }
1704
+ }
1705
+ const RRText = BaseRRTextImpl(BaseRRNode);
1706
+ const RRComment = BaseRRCommentImpl(BaseRRNode);
1707
+ const RRCDATASection = BaseRRCDATASectionImpl(BaseRRNode);
1708
+ function getValidTagName(element) {
1709
+ if (element instanceof HTMLFormElement) {
1710
+ return "FORM";
1711
+ }
1712
+ return element.tagName.toUpperCase();
1713
+ }
1714
+ function buildFromNode(node, rrdom, domMirror, parentRRNode) {
1715
+ let rrNode;
1716
+ switch (node.nodeType) {
1717
+ case NodeType.DOCUMENT_NODE:
1718
+ if (parentRRNode && parentRRNode.nodeName === "IFRAME")
1719
+ rrNode = parentRRNode.contentDocument;
1720
+ else {
1721
+ rrNode = rrdom;
1722
+ rrNode.compatMode = node.compatMode;
1723
+ }
1724
+ break;
1725
+ case NodeType.DOCUMENT_TYPE_NODE:
1726
+ const documentType = node;
1727
+ rrNode = rrdom.createDocumentType(documentType.name, documentType.publicId, documentType.systemId);
1728
+ break;
1729
+ case NodeType.ELEMENT_NODE:
1730
+ const elementNode = node;
1731
+ const tagName = getValidTagName(elementNode);
1732
+ rrNode = rrdom.createElement(tagName);
1733
+ const rrElement = rrNode;
1734
+ for (const { name, value } of Array.from(elementNode.attributes)) {
1735
+ rrElement.attributes[name] = value;
1736
+ }
1737
+ elementNode.scrollLeft && (rrElement.scrollLeft = elementNode.scrollLeft);
1738
+ elementNode.scrollTop && (rrElement.scrollTop = elementNode.scrollTop);
1739
+ break;
1740
+ case NodeType.TEXT_NODE:
1741
+ rrNode = rrdom.createTextNode(node.textContent || "");
1742
+ break;
1743
+ case NodeType.CDATA_SECTION_NODE:
1744
+ rrNode = rrdom.createCDATASection(node.data);
1745
+ break;
1746
+ case NodeType.COMMENT_NODE:
1747
+ rrNode = rrdom.createComment(node.textContent || "");
1748
+ break;
1749
+ case NodeType.DOCUMENT_FRAGMENT_NODE:
1750
+ rrNode = parentRRNode.attachShadow({ mode: "open" });
1751
+ break;
1752
+ default:
1753
+ return null;
1754
+ }
1755
+ let sn = domMirror.getMeta(node);
1756
+ if (rrdom instanceof RRDocument) {
1757
+ if (!sn) {
1758
+ sn = getDefaultSN(rrNode, rrdom.unserializedId);
1759
+ domMirror.add(node, sn);
1760
+ }
1761
+ rrdom.mirror.add(rrNode, Object.assign({}, sn));
1762
+ }
1763
+ return rrNode;
1764
+ }
1765
+ function buildFromDom(dom, domMirror = createMirror$1(), rrdom = new RRDocument()) {
1766
+ function walk(node, parentRRNode) {
1767
+ const rrNode = buildFromNode(node, rrdom, domMirror, parentRRNode);
1768
+ if (rrNode === null)
1769
+ return;
1770
+ if ((parentRRNode === null || parentRRNode === void 0 ? void 0 : parentRRNode.nodeName) !== "IFRAME" && node.nodeType !== NodeType.DOCUMENT_FRAGMENT_NODE) {
1771
+ parentRRNode === null || parentRRNode === void 0 ? void 0 : parentRRNode.appendChild(rrNode);
1772
+ rrNode.parentNode = parentRRNode;
1773
+ rrNode.parentElement = parentRRNode;
1774
+ }
1775
+ if (node.nodeName === "IFRAME") {
1776
+ walk(node.contentDocument, rrNode);
1777
+ } else if (node.nodeType === NodeType.DOCUMENT_NODE || node.nodeType === NodeType.ELEMENT_NODE || node.nodeType === NodeType.DOCUMENT_FRAGMENT_NODE) {
1778
+ if (node.nodeType === NodeType.ELEMENT_NODE && node.shadowRoot)
1779
+ walk(node.shadowRoot, rrNode);
1780
+ node.childNodes.forEach((childNode) => walk(childNode, rrNode));
1781
+ }
1782
+ }
1783
+ walk(dom, null);
1784
+ return rrdom;
1785
+ }
1786
+ function createMirror() {
1787
+ return new Mirror();
1788
+ }
1789
+ class Mirror {
1790
+ constructor() {
1791
+ this.idNodeMap = /* @__PURE__ */ new Map();
1792
+ this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
1793
+ }
1794
+ getId(n) {
1795
+ var _a;
1796
+ if (!n)
1797
+ return -1;
1798
+ const id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;
1799
+ return id !== null && id !== void 0 ? id : -1;
1800
+ }
1801
+ getNode(id) {
1802
+ return this.idNodeMap.get(id) || null;
1803
+ }
1804
+ getIds() {
1805
+ return Array.from(this.idNodeMap.keys());
1806
+ }
1807
+ getMeta(n) {
1808
+ return this.nodeMetaMap.get(n) || null;
1809
+ }
1810
+ removeNodeFromMap(n) {
1811
+ const id = this.getId(n);
1812
+ this.idNodeMap.delete(id);
1813
+ if (n.childNodes) {
1814
+ n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));
1815
+ }
1816
+ }
1817
+ has(id) {
1818
+ return this.idNodeMap.has(id);
1819
+ }
1820
+ hasNode(node) {
1821
+ return this.nodeMetaMap.has(node);
1822
+ }
1823
+ add(n, meta) {
1824
+ const id = meta.id;
1825
+ this.idNodeMap.set(id, n);
1826
+ this.nodeMetaMap.set(n, meta);
1827
+ }
1828
+ replace(id, n) {
1829
+ this.idNodeMap.set(id, n);
1830
+ }
1831
+ reset() {
1832
+ this.idNodeMap = /* @__PURE__ */ new Map();
1833
+ this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
1834
+ }
1835
+ }
1836
+ function getDefaultSN(node, id) {
1837
+ switch (node.RRNodeType) {
1838
+ case NodeType$1.Document:
1839
+ return {
1840
+ id,
1841
+ type: node.RRNodeType,
1842
+ childNodes: []
1843
+ };
1844
+ case NodeType$1.DocumentType:
1845
+ const doctype = node;
1846
+ return {
1847
+ id,
1848
+ type: node.RRNodeType,
1849
+ name: doctype.name,
1850
+ publicId: doctype.publicId,
1851
+ systemId: doctype.systemId
1852
+ };
1853
+ case NodeType$1.Element:
1854
+ return {
1855
+ id,
1856
+ type: node.RRNodeType,
1857
+ tagName: node.tagName.toLowerCase(),
1858
+ attributes: {},
1859
+ childNodes: []
1860
+ };
1861
+ case NodeType$1.Text:
1862
+ return {
1863
+ id,
1864
+ type: node.RRNodeType,
1865
+ textContent: node.textContent || ""
1866
+ };
1867
+ case NodeType$1.Comment:
1868
+ return {
1869
+ id,
1870
+ type: node.RRNodeType,
1871
+ textContent: node.textContent || ""
1872
+ };
1873
+ case NodeType$1.CDATA:
1874
+ return {
1875
+ id,
1876
+ type: node.RRNodeType,
1877
+ textContent: ""
1878
+ };
1879
+ }
1880
+ }
1881
+
1882
+ //
1883
+ // An event handler can take an optional event argument
1884
+ // and should not return a value
1885
+
1886
+
1887
+
1888
+ // An array of all currently registered event handlers for a type
1889
+
1890
+
1891
+ // A map of event types and their corresponding event handlers.
1892
+
1893
+
1894
+
1895
+
1896
+
1897
+ /** Mitt: Tiny (~200b) functional event emitter / pubsub.
1898
+ * @name mitt
1899
+ * @returns {Mitt}
1900
+ */
1901
+ function mitt$1(all ) {
1902
+ all = all || Object.create(null);
1903
+
1904
+ return {
1905
+ /**
1906
+ * Register an event handler for the given type.
1907
+ *
1908
+ * @param {String} type Type of event to listen for, or `"*"` for all events
1909
+ * @param {Function} handler Function to call in response to given event
1910
+ * @memberOf mitt
1911
+ */
1912
+ on: function on(type , handler ) {
1913
+ (all[type] || (all[type] = [])).push(handler);
1914
+ },
1915
+
1916
+ /**
1917
+ * Remove an event handler for the given type.
1918
+ *
1919
+ * @param {String} type Type of event to unregister `handler` from, or `"*"`
1920
+ * @param {Function} handler Handler function to remove
1921
+ * @memberOf mitt
1922
+ */
1923
+ off: function off(type , handler ) {
1924
+ if (all[type]) {
1925
+ all[type].splice(all[type].indexOf(handler) >>> 0, 1);
1926
+ }
1927
+ },
1928
+
1929
+ /**
1930
+ * Invoke all handlers for the given type.
1931
+ * If present, `"*"` handlers are invoked after type-matched handlers.
1932
+ *
1933
+ * @param {String} type The event type to invoke
1934
+ * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
1935
+ * @memberOf mitt
1936
+ */
1937
+ emit: function emit(type , evt ) {
1938
+ (all[type] || []).slice().map(function (handler) { handler(evt); });
1939
+ (all['*'] || []).slice().map(function (handler) { handler(type, evt); });
1940
+ }
1941
+ };
1942
+ }
1943
+
1944
+ var mittProxy = /*#__PURE__*/Object.freeze({
1945
+ __proto__: null,
1946
+ 'default': mitt$1
1947
+ });
1948
+
1949
+ function polyfill$1(w = window, d = document) {
1950
+ if ("scrollBehavior" in d.documentElement.style && w.__forceSmoothScrollPolyfill__ !== true) {
1951
+ return;
1952
+ }
1953
+ const Element = w.HTMLElement || w.Element;
1954
+ const SCROLL_TIME = 468;
1955
+ const original = {
1956
+ scroll: w.scroll || w.scrollTo,
1957
+ scrollBy: w.scrollBy,
1958
+ elementScroll: Element.prototype.scroll || scrollElement,
1959
+ scrollIntoView: Element.prototype.scrollIntoView
1960
+ };
1961
+ const now = w.performance && w.performance.now ? w.performance.now.bind(w.performance) : Date.now;
1962
+ function isMicrosoftBrowser(userAgent) {
1963
+ const userAgentPatterns = ["MSIE ", "Trident/", "Edge/"];
1964
+ return new RegExp(userAgentPatterns.join("|")).test(userAgent);
1965
+ }
1966
+ const ROUNDING_TOLERANCE = isMicrosoftBrowser(w.navigator.userAgent) ? 1 : 0;
1967
+ function scrollElement(x, y) {
1968
+ this.scrollLeft = x;
1969
+ this.scrollTop = y;
1970
+ }
1971
+ function ease(k) {
1972
+ return 0.5 * (1 - Math.cos(Math.PI * k));
1973
+ }
1974
+ function shouldBailOut(firstArg) {
1975
+ if (firstArg === null || typeof firstArg !== "object" || firstArg.behavior === void 0 || firstArg.behavior === "auto" || firstArg.behavior === "instant") {
1976
+ return true;
1977
+ }
1978
+ if (typeof firstArg === "object" && firstArg.behavior === "smooth") {
1979
+ return false;
1980
+ }
1981
+ throw new TypeError("behavior member of ScrollOptions " + firstArg.behavior + " is not a valid value for enumeration ScrollBehavior.");
1982
+ }
1983
+ function hasScrollableSpace(el, axis) {
1984
+ if (axis === "Y") {
1985
+ return el.clientHeight + ROUNDING_TOLERANCE < el.scrollHeight;
1986
+ }
1987
+ if (axis === "X") {
1988
+ return el.clientWidth + ROUNDING_TOLERANCE < el.scrollWidth;
1989
+ }
1990
+ }
1991
+ function canOverflow(el, axis) {
1992
+ const overflowValue = w.getComputedStyle(el, null)["overflow" + axis];
1993
+ return overflowValue === "auto" || overflowValue === "scroll";
1994
+ }
1995
+ function isScrollable(el) {
1996
+ const isScrollableY = hasScrollableSpace(el, "Y") && canOverflow(el, "Y");
1997
+ const isScrollableX = hasScrollableSpace(el, "X") && canOverflow(el, "X");
1998
+ return isScrollableY || isScrollableX;
1999
+ }
2000
+ function findScrollableParent(el) {
2001
+ while (el !== d.body && isScrollable(el) === false) {
2002
+ el = el.parentNode || el.host;
2003
+ }
2004
+ return el;
2005
+ }
2006
+ function step(context) {
2007
+ const time = now();
2008
+ let value;
2009
+ let currentX;
2010
+ let currentY;
2011
+ let elapsed = (time - context.startTime) / SCROLL_TIME;
2012
+ elapsed = elapsed > 1 ? 1 : elapsed;
2013
+ value = ease(elapsed);
2014
+ currentX = context.startX + (context.x - context.startX) * value;
2015
+ currentY = context.startY + (context.y - context.startY) * value;
2016
+ context.method.call(context.scrollable, currentX, currentY);
2017
+ if (currentX !== context.x || currentY !== context.y) {
2018
+ w.requestAnimationFrame(step.bind(w, context));
2019
+ }
2020
+ }
2021
+ function smoothScroll(el, x, y) {
2022
+ let scrollable;
2023
+ let startX;
2024
+ let startY;
2025
+ let method;
2026
+ const startTime = now();
2027
+ if (el === d.body) {
2028
+ scrollable = w;
2029
+ startX = w.scrollX || w.pageXOffset;
2030
+ startY = w.scrollY || w.pageYOffset;
2031
+ method = original.scroll;
2032
+ } else {
2033
+ scrollable = el;
2034
+ startX = el.scrollLeft;
2035
+ startY = el.scrollTop;
2036
+ method = scrollElement;
2037
+ }
2038
+ step({
2039
+ scrollable,
2040
+ method,
2041
+ startTime,
2042
+ startX,
2043
+ startY,
2044
+ x,
2045
+ y
2046
+ });
2047
+ }
2048
+ w.scroll = w.scrollTo = function() {
2049
+ if (arguments[0] === void 0) {
2050
+ return;
2051
+ }
2052
+ if (shouldBailOut(arguments[0]) === true) {
2053
+ original.scroll.call(w, arguments[0].left !== void 0 ? arguments[0].left : typeof arguments[0] !== "object" ? arguments[0] : w.scrollX || w.pageXOffset, arguments[0].top !== void 0 ? arguments[0].top : arguments[1] !== void 0 ? arguments[1] : w.scrollY || w.pageYOffset);
2054
+ return;
2055
+ }
2056
+ smoothScroll.call(w, d.body, arguments[0].left !== void 0 ? ~~arguments[0].left : w.scrollX || w.pageXOffset, arguments[0].top !== void 0 ? ~~arguments[0].top : w.scrollY || w.pageYOffset);
2057
+ };
2058
+ w.scrollBy = function() {
2059
+ if (arguments[0] === void 0) {
2060
+ return;
2061
+ }
2062
+ if (shouldBailOut(arguments[0])) {
2063
+ original.scrollBy.call(w, arguments[0].left !== void 0 ? arguments[0].left : typeof arguments[0] !== "object" ? arguments[0] : 0, arguments[0].top !== void 0 ? arguments[0].top : arguments[1] !== void 0 ? arguments[1] : 0);
2064
+ return;
2065
+ }
2066
+ smoothScroll.call(w, d.body, ~~arguments[0].left + (w.scrollX || w.pageXOffset), ~~arguments[0].top + (w.scrollY || w.pageYOffset));
2067
+ };
2068
+ Element.prototype.scroll = Element.prototype.scrollTo = function() {
2069
+ if (arguments[0] === void 0) {
2070
+ return;
2071
+ }
2072
+ if (shouldBailOut(arguments[0]) === true) {
2073
+ if (typeof arguments[0] === "number" && arguments[1] === void 0) {
2074
+ throw new SyntaxError("Value could not be converted");
2075
+ }
2076
+ original.elementScroll.call(this, arguments[0].left !== void 0 ? ~~arguments[0].left : typeof arguments[0] !== "object" ? ~~arguments[0] : this.scrollLeft, arguments[0].top !== void 0 ? ~~arguments[0].top : arguments[1] !== void 0 ? ~~arguments[1] : this.scrollTop);
2077
+ return;
2078
+ }
2079
+ const left = arguments[0].left;
2080
+ const top = arguments[0].top;
2081
+ smoothScroll.call(this, this, typeof left === "undefined" ? this.scrollLeft : ~~left, typeof top === "undefined" ? this.scrollTop : ~~top);
2082
+ };
2083
+ Element.prototype.scrollBy = function() {
2084
+ if (arguments[0] === void 0) {
2085
+ return;
2086
+ }
2087
+ if (shouldBailOut(arguments[0]) === true) {
2088
+ original.elementScroll.call(this, arguments[0].left !== void 0 ? ~~arguments[0].left + this.scrollLeft : ~~arguments[0] + this.scrollLeft, arguments[0].top !== void 0 ? ~~arguments[0].top + this.scrollTop : ~~arguments[1] + this.scrollTop);
2089
+ return;
2090
+ }
2091
+ this.scroll({
2092
+ left: ~~arguments[0].left + this.scrollLeft,
2093
+ top: ~~arguments[0].top + this.scrollTop,
2094
+ behavior: arguments[0].behavior
2095
+ });
2096
+ };
2097
+ Element.prototype.scrollIntoView = function() {
2098
+ if (shouldBailOut(arguments[0]) === true) {
2099
+ original.scrollIntoView.call(this, arguments[0] === void 0 ? true : arguments[0]);
2100
+ return;
2101
+ }
2102
+ const scrollableParent = findScrollableParent(this);
2103
+ const parentRects = scrollableParent.getBoundingClientRect();
2104
+ const clientRects = this.getBoundingClientRect();
2105
+ if (scrollableParent !== d.body) {
2106
+ smoothScroll.call(this, scrollableParent, scrollableParent.scrollLeft + clientRects.left - parentRects.left, scrollableParent.scrollTop + clientRects.top - parentRects.top);
2107
+ if (w.getComputedStyle(scrollableParent).position !== "fixed") {
2108
+ w.scrollBy({
2109
+ left: parentRects.left,
2110
+ top: parentRects.top,
2111
+ behavior: "smooth"
2112
+ });
2113
+ }
2114
+ } else {
2115
+ w.scrollBy({
2116
+ left: clientRects.left,
2117
+ top: clientRects.top,
2118
+ behavior: "smooth"
2119
+ });
2120
+ }
2121
+ };
2122
+ }
2123
+
2124
+ var EventType = /* @__PURE__ */ ((EventType2) => {
2125
+ EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
2126
+ EventType2[EventType2["Load"] = 1] = "Load";
2127
+ EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
2128
+ EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
2129
+ EventType2[EventType2["Meta"] = 4] = "Meta";
2130
+ EventType2[EventType2["Custom"] = 5] = "Custom";
2131
+ EventType2[EventType2["Plugin"] = 6] = "Plugin";
2132
+ return EventType2;
2133
+ })(EventType || {});
2134
+ var IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {
2135
+ IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
2136
+ IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
2137
+ IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
2138
+ IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
2139
+ IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
2140
+ IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
2141
+ IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
2142
+ IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
2143
+ IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
2144
+ IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
2145
+ IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
2146
+ IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
2147
+ IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
2148
+ IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
2149
+ return IncrementalSource2;
2150
+ })(IncrementalSource || {});
2151
+ var MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {
2152
+ MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
2153
+ MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
2154
+ MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
2155
+ MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
2156
+ MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
2157
+ MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
2158
+ MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
2159
+ MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
2160
+ MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
2161
+ MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
2162
+ MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
2163
+ return MouseInteractions2;
2164
+ })(MouseInteractions || {});
2165
+ var CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {
2166
+ CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
2167
+ CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
2168
+ CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
2169
+ return CanvasContext2;
2170
+ })(CanvasContext || {});
2171
+ var MediaInteractions = /* @__PURE__ */ ((MediaInteractions2) => {
2172
+ MediaInteractions2[MediaInteractions2["Play"] = 0] = "Play";
2173
+ MediaInteractions2[MediaInteractions2["Pause"] = 1] = "Pause";
2174
+ MediaInteractions2[MediaInteractions2["Seeked"] = 2] = "Seeked";
2175
+ MediaInteractions2[MediaInteractions2["VolumeChange"] = 3] = "VolumeChange";
2176
+ return MediaInteractions2;
2177
+ })(MediaInteractions || {});
2178
+ var ReplayerEvents = /* @__PURE__ */ ((ReplayerEvents2) => {
2179
+ ReplayerEvents2["Start"] = "start";
2180
+ ReplayerEvents2["Pause"] = "pause";
2181
+ ReplayerEvents2["Resume"] = "resume";
2182
+ ReplayerEvents2["Resize"] = "resize";
2183
+ ReplayerEvents2["Finish"] = "finish";
2184
+ ReplayerEvents2["FullsnapshotRebuilded"] = "fullsnapshot-rebuilded";
2185
+ ReplayerEvents2["LoadStylesheetStart"] = "load-stylesheet-start";
2186
+ ReplayerEvents2["LoadStylesheetEnd"] = "load-stylesheet-end";
2187
+ ReplayerEvents2["SkipStart"] = "skip-start";
2188
+ ReplayerEvents2["SkipEnd"] = "skip-end";
2189
+ ReplayerEvents2["MouseInteraction"] = "mouse-interaction";
2190
+ ReplayerEvents2["EventCast"] = "event-cast";
2191
+ ReplayerEvents2["CustomEvent"] = "custom-event";
2192
+ ReplayerEvents2["Flush"] = "flush";
2193
+ ReplayerEvents2["StateChange"] = "state-change";
2194
+ ReplayerEvents2["PlayBack"] = "play-back";
2195
+ return ReplayerEvents2;
2196
+ })(ReplayerEvents || {});
2197
+
2198
+ class Timer {
2199
+ constructor(actions = [], speed) {
2200
+ this.timeOffset = 0;
2201
+ this.raf = null;
2202
+ this.actions = actions;
2203
+ this.speed = speed;
2204
+ }
2205
+ addAction(action) {
2206
+ const index = this.findActionIndex(action);
2207
+ this.actions.splice(index, 0, action);
2208
+ }
2209
+ addActions(actions) {
2210
+ this.actions = this.actions.concat(actions);
2211
+ }
2212
+ replaceActions(actions) {
2213
+ this.actions.length = 0;
2214
+ this.actions.splice(0, 0, ...actions);
2215
+ }
2216
+ start() {
2217
+ this.timeOffset = 0;
2218
+ let lastTimestamp = performance.now();
2219
+ const { actions } = this;
2220
+ const self = this;
2221
+ function check() {
2222
+ const time = performance.now();
2223
+ self.timeOffset += (time - lastTimestamp) * self.speed;
2224
+ lastTimestamp = time;
2225
+ while (actions.length) {
2226
+ const action = actions[0];
2227
+ if (self.timeOffset >= action.delay) {
2228
+ actions.shift();
2229
+ action.doAction();
2230
+ } else {
2231
+ break;
2232
+ }
2233
+ }
2234
+ if (actions.length > 0 || self.liveMode) {
2235
+ self.raf = requestAnimationFrame(check);
2236
+ }
2237
+ }
2238
+ this.raf = requestAnimationFrame(check);
2239
+ }
2240
+ clear() {
2241
+ if (this.raf) {
2242
+ cancelAnimationFrame(this.raf);
2243
+ this.raf = null;
2244
+ }
2245
+ this.actions.length = 0;
2246
+ }
2247
+ setSpeed(speed) {
2248
+ this.speed = speed;
2249
+ }
2250
+ toggleLiveMode(mode) {
2251
+ this.liveMode = mode;
2252
+ }
2253
+ isActive() {
2254
+ return this.raf !== null;
2255
+ }
2256
+ findActionIndex(action) {
2257
+ let start = 0;
2258
+ let end = this.actions.length - 1;
2259
+ while (start <= end) {
2260
+ const mid = Math.floor((start + end) / 2);
2261
+ if (this.actions[mid].delay < action.delay) {
2262
+ start = mid + 1;
2263
+ } else if (this.actions[mid].delay > action.delay) {
2264
+ end = mid - 1;
2265
+ } else {
2266
+ return mid + 1;
2267
+ }
2268
+ }
2269
+ return start;
2270
+ }
2271
+ }
2272
+ function addDelay(event, baselineTime) {
2273
+ if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.MouseMove) {
2274
+ const firstOffset = event.data.positions[0].timeOffset;
2275
+ const firstTimestamp = event.timestamp + firstOffset;
2276
+ event.delay = firstTimestamp - baselineTime;
2277
+ return firstTimestamp - baselineTime;
2278
+ }
2279
+ event.delay = event.timestamp - baselineTime;
2280
+ return event.delay;
2281
+ }
2282
+
2283
+ /*! *****************************************************************************
2284
+ Copyright (c) Microsoft Corporation.
2285
+
2286
+ Permission to use, copy, modify, and/or distribute this software for any
2287
+ purpose with or without fee is hereby granted.
2288
+
2289
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2290
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2291
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2292
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2293
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2294
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2295
+ PERFORMANCE OF THIS SOFTWARE.
2296
+ ***************************************************************************** */
2297
+ function t(t,n){var e="function"==typeof Symbol&&t[Symbol.iterator];if(!e)return t;var r,o,i=e.call(t),a=[];try{for(;(void 0===n||n-- >0)&&!(r=i.next()).done;)a.push(r.value);}catch(t){o={error:t};}finally{try{r&&!r.done&&(e=i.return)&&e.call(i);}finally{if(o)throw o.error}}return a}var n;!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped";}(n||(n={}));var e={type:"xstate.init"};function r(t){return void 0===t?[]:[].concat(t)}function o(t){return {type:"xstate.assign",assignment:t}}function i$2(t,n){return "string"==typeof(t="string"==typeof t&&n&&n[t]?n[t]:t)?{type:t}:"function"==typeof t?{type:t.name,exec:t}:t}function a(t){return function(n){return t===n}}function u(t){return "string"==typeof t?{type:t}:t}function c(t,n){return {value:t,context:n,actions:[],changed:!1,matches:a(t)}}function f(t,n,e){var r=n,o=!1;return [t.filter((function(t){if("xstate.assign"===t.type){o=!0;var n=Object.assign({},r);return "function"==typeof t.assignment?n=t.assignment(r,e):Object.keys(t.assignment).forEach((function(o){n[o]="function"==typeof t.assignment[o]?t.assignment[o](r,e):t.assignment[o];})),r=n,!1}return !0})),r,o]}function s(n,o){void 0===o&&(o={});var s=t(f(r(n.states[n.initial].entry).map((function(t){return i$2(t,o.actions)})),n.context,e),2),l=s[0],v=s[1],y={config:n,_options:o,initialState:{value:n.initial,actions:l,context:v,matches:a(n.initial)},transition:function(e,o){var s,l,v="string"==typeof e?{value:e,context:n.context}:e,p=v.value,g=v.context,d=u(o),x=n.states[p];if(x.on){var m=r(x.on[d.type]);try{for(var h=function(t){var n="function"==typeof Symbol&&Symbol.iterator,e=n&&t[n],r=0;if(e)return e.call(t);if(t&&"number"==typeof t.length)return {next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}(m),b=h.next();!b.done;b=h.next()){var S=b.value;if(void 0===S)return c(p,g);var w="string"==typeof S?{target:S}:S,j=w.target,E=w.actions,R=void 0===E?[]:E,N=w.cond,O=void 0===N?function(){return !0}:N,_=void 0===j,k=null!=j?j:p,T=n.states[k];if(O(g,d)){var q=t(f((_?r(R):[].concat(x.exit,R,T.entry).filter((function(t){return t}))).map((function(t){return i$2(t,y._options.actions)})),g,d),3),z=q[0],A=q[1],B=q[2],C=null!=j?j:p;return {value:C,context:A,actions:z,changed:j!==p||z.length>0||B,matches:a(C)}}}}catch(t){s={error:t};}finally{try{b&&!b.done&&(l=h.return)&&l.call(h);}finally{if(s)throw s.error}}}return c(p,g)}};return y}var l=function(t,n){return t.actions.forEach((function(e){var r=e.exec;return r&&r(t.context,n)}))};function v(t){var r=t.initialState,o=n.NotStarted,i=new Set,c={_machine:t,send:function(e){o===n.Running&&(r=t.transition(r,e),l(r,u(e)),i.forEach((function(t){return t(r)})));},subscribe:function(t){return i.add(t),t(r),{unsubscribe:function(){return i.delete(t)}}},start:function(i){if(i){var u="object"==typeof i?i:{context:t.config.context,value:i};r={value:u.value,actions:[],context:u.context,matches:a(u.value)};}return o=n.Running,l(r,e),c},stop:function(){return o=n.Stopped,i.clear(),c},get state(){return r},get status(){return o}};return c}
2298
+
2299
+ var __defProp$1 = Object.defineProperty;
2300
+ var __defProps$1 = Object.defineProperties;
2301
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
2302
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
2303
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
2304
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
2305
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2306
+ var __spreadValues$1 = (a, b) => {
2307
+ for (var prop in b || (b = {}))
2308
+ if (__hasOwnProp$1.call(b, prop))
2309
+ __defNormalProp$1(a, prop, b[prop]);
2310
+ if (__getOwnPropSymbols$1)
2311
+ for (var prop of __getOwnPropSymbols$1(b)) {
2312
+ if (__propIsEnum$1.call(b, prop))
2313
+ __defNormalProp$1(a, prop, b[prop]);
2314
+ }
2315
+ return a;
2316
+ };
2317
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
2318
+ function discardPriorSnapshots(events, baselineTime) {
2319
+ for (let idx = events.length - 1; idx >= 0; idx--) {
2320
+ const event = events[idx];
2321
+ if (event.type === EventType.Meta) {
2322
+ if (event.timestamp <= baselineTime) {
2323
+ return events.slice(idx);
2324
+ }
2325
+ }
2326
+ }
2327
+ return events;
2328
+ }
2329
+ function createPlayerService(context, { getCastFn, applyEventsSynchronously, emitter }) {
2330
+ const playerMachine = s({
2331
+ id: "player",
2332
+ context,
2333
+ initial: "paused",
2334
+ states: {
2335
+ playing: {
2336
+ on: {
2337
+ PAUSE: {
2338
+ target: "paused",
2339
+ actions: ["pause"]
2340
+ },
2341
+ CAST_EVENT: {
2342
+ target: "playing",
2343
+ actions: "castEvent"
2344
+ },
2345
+ END: {
2346
+ target: "paused",
2347
+ actions: ["resetLastPlayedEvent", "pause"]
2348
+ },
2349
+ ADD_EVENT: {
2350
+ target: "playing",
2351
+ actions: ["addEvent"]
2352
+ },
2353
+ REPLACE_EVENTS: {
2354
+ target: "playing",
2355
+ actions: ["replaceEvents"]
2356
+ }
2357
+ }
2358
+ },
2359
+ paused: {
2360
+ on: {
2361
+ PLAY: {
2362
+ target: "playing",
2363
+ actions: ["recordTimeOffset", "play"]
2364
+ },
2365
+ CAST_EVENT: {
2366
+ target: "paused",
2367
+ actions: "castEvent"
2368
+ },
2369
+ TO_LIVE: {
2370
+ target: "live",
2371
+ actions: ["startLive"]
2372
+ },
2373
+ ADD_EVENT: {
2374
+ target: "paused",
2375
+ actions: ["addEvent"]
2376
+ },
2377
+ REPLACE_EVENTS: {
2378
+ target: "paused",
2379
+ actions: ["replaceEvents"]
2380
+ }
2381
+ }
2382
+ },
2383
+ live: {
2384
+ on: {
2385
+ ADD_EVENT: {
2386
+ target: "live",
2387
+ actions: ["addEvent"]
2388
+ },
2389
+ CAST_EVENT: {
2390
+ target: "live",
2391
+ actions: ["castEvent"]
2392
+ }
2393
+ }
2394
+ }
2395
+ }
2396
+ }, {
2397
+ actions: {
2398
+ castEvent: o({
2399
+ lastPlayedEvent: (ctx, event) => {
2400
+ if (event.type === "CAST_EVENT") {
2401
+ return event.payload.event;
2402
+ }
2403
+ return ctx.lastPlayedEvent;
2404
+ }
2405
+ }),
2406
+ recordTimeOffset: o((ctx, event) => {
2407
+ let timeOffset = ctx.timeOffset;
2408
+ if ("payload" in event && "timeOffset" in event.payload) {
2409
+ timeOffset = event.payload.timeOffset;
2410
+ }
2411
+ return __spreadProps$1(__spreadValues$1({}, ctx), {
2412
+ timeOffset,
2413
+ baselineTime: ctx.events[0].timestamp + timeOffset
2414
+ });
2415
+ }),
2416
+ play(ctx) {
2417
+ var _a;
2418
+ const { timer, events, baselineTime, lastPlayedEvent } = ctx;
2419
+ timer.clear();
2420
+ for (const event of events) {
2421
+ addDelay(event, baselineTime);
2422
+ }
2423
+ const neededEvents = discardPriorSnapshots(events, baselineTime);
2424
+ let lastPlayedTimestamp = lastPlayedEvent == null ? void 0 : lastPlayedEvent.timestamp;
2425
+ if ((lastPlayedEvent == null ? void 0 : lastPlayedEvent.type) === EventType.IncrementalSnapshot && lastPlayedEvent.data.source === IncrementalSource.MouseMove) {
2426
+ lastPlayedTimestamp = lastPlayedEvent.timestamp + ((_a = lastPlayedEvent.data.positions[0]) == null ? void 0 : _a.timeOffset);
2427
+ }
2428
+ if (baselineTime < (lastPlayedTimestamp || 0)) {
2429
+ emitter.emit(ReplayerEvents.PlayBack);
2430
+ }
2431
+ const syncEvents = new Array();
2432
+ const actions = new Array();
2433
+ for (const event of neededEvents) {
2434
+ if (lastPlayedTimestamp && lastPlayedTimestamp < baselineTime && (event.timestamp <= lastPlayedTimestamp || event === lastPlayedEvent)) {
2435
+ continue;
2436
+ }
2437
+ if (event.timestamp < baselineTime) {
2438
+ syncEvents.push(event);
2439
+ } else {
2440
+ const castFn = getCastFn(event, false);
2441
+ actions.push({
2442
+ doAction: () => {
2443
+ castFn();
2444
+ },
2445
+ delay: event.delay
2446
+ });
2447
+ }
2448
+ }
2449
+ applyEventsSynchronously(syncEvents);
2450
+ emitter.emit(ReplayerEvents.Flush);
2451
+ timer.addActions(actions);
2452
+ timer.start();
2453
+ },
2454
+ pause(ctx) {
2455
+ ctx.timer.clear();
2456
+ },
2457
+ resetLastPlayedEvent: o((ctx) => {
2458
+ return __spreadProps$1(__spreadValues$1({}, ctx), {
2459
+ lastPlayedEvent: null
2460
+ });
2461
+ }),
2462
+ startLive: o({
2463
+ baselineTime: (ctx, event) => {
2464
+ ctx.timer.toggleLiveMode(true);
2465
+ ctx.timer.start();
2466
+ if (event.type === "TO_LIVE" && event.payload.baselineTime) {
2467
+ return event.payload.baselineTime;
2468
+ }
2469
+ return Date.now();
2470
+ }
2471
+ }),
2472
+ replaceEvents: o((ctx, machineEvent) => {
2473
+ const { events: curEvents, timer, baselineTime } = ctx;
2474
+ if (machineEvent.type === "REPLACE_EVENTS") {
2475
+ const { events: newEvents } = machineEvent.payload;
2476
+ curEvents.length = 0;
2477
+ const actions = [];
2478
+ for (const event of newEvents) {
2479
+ addDelay(event, baselineTime);
2480
+ curEvents.push(event);
2481
+ if (event.timestamp >= timer.timeOffset + baselineTime) {
2482
+ const castFn = getCastFn(event, false);
2483
+ actions.push({
2484
+ doAction: () => {
2485
+ castFn();
2486
+ },
2487
+ delay: event.delay
2488
+ });
2489
+ }
2490
+ }
2491
+ if (timer.isActive()) {
2492
+ timer.replaceActions(actions);
2493
+ }
2494
+ }
2495
+ return __spreadProps$1(__spreadValues$1({}, ctx), { events: curEvents });
2496
+ }),
2497
+ addEvent: o((ctx, machineEvent) => {
2498
+ const { baselineTime, timer, events } = ctx;
2499
+ if (machineEvent.type === "ADD_EVENT") {
2500
+ const { event } = machineEvent.payload;
2501
+ addDelay(event, baselineTime);
2502
+ let end = events.length - 1;
2503
+ if (!events[end] || events[end].timestamp <= event.timestamp) {
2504
+ events.push(event);
2505
+ } else {
2506
+ let insertionIndex = -1;
2507
+ let start = 0;
2508
+ while (start <= end) {
2509
+ const mid = Math.floor((start + end) / 2);
2510
+ if (events[mid].timestamp <= event.timestamp) {
2511
+ start = mid + 1;
2512
+ } else {
2513
+ end = mid - 1;
2514
+ }
2515
+ }
2516
+ if (insertionIndex === -1) {
2517
+ insertionIndex = start;
2518
+ }
2519
+ events.splice(insertionIndex, 0, event);
2520
+ }
2521
+ const isSync = event.timestamp < baselineTime;
2522
+ const castFn = getCastFn(event, isSync);
2523
+ if (isSync) {
2524
+ castFn();
2525
+ } else if (timer.isActive()) {
2526
+ timer.addAction({
2527
+ doAction: () => {
2528
+ castFn();
2529
+ },
2530
+ delay: event.delay
2531
+ });
2532
+ }
2533
+ }
2534
+ return __spreadProps$1(__spreadValues$1({}, ctx), { events });
2535
+ })
2536
+ }
2537
+ });
2538
+ return v(playerMachine);
2539
+ }
2540
+ function createSpeedService(context) {
2541
+ const speedMachine = s({
2542
+ id: "speed",
2543
+ context,
2544
+ initial: "normal",
2545
+ states: {
2546
+ normal: {
2547
+ on: {
2548
+ FAST_FORWARD: {
2549
+ target: "skipping",
2550
+ actions: ["recordSpeed", "setSpeed"]
2551
+ },
2552
+ SET_SPEED: {
2553
+ target: "normal",
2554
+ actions: ["setSpeed"]
2555
+ }
2556
+ }
2557
+ },
2558
+ skipping: {
2559
+ on: {
2560
+ BACK_TO_NORMAL: {
2561
+ target: "normal",
2562
+ actions: ["restoreSpeed"]
2563
+ },
2564
+ SET_SPEED: {
2565
+ target: "normal",
2566
+ actions: ["setSpeed"]
2567
+ }
2568
+ }
2569
+ }
2570
+ }
2571
+ }, {
2572
+ actions: {
2573
+ setSpeed: (ctx, event) => {
2574
+ if ("payload" in event) {
2575
+ ctx.timer.setSpeed(event.payload.speed);
2576
+ }
2577
+ },
2578
+ recordSpeed: o({
2579
+ normalSpeed: (ctx) => ctx.timer.speed
2580
+ }),
2581
+ restoreSpeed: (ctx) => {
2582
+ ctx.timer.setSpeed(ctx.normalSpeed);
2583
+ }
2584
+ }
2585
+ });
2586
+ return v(speedMachine);
2587
+ }
2588
+
2589
+ const DEPARTED_MIRROR_ACCESS_WARNING = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";
2590
+ let _mirror = {
2591
+ map: {},
2592
+ getId() {
2593
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
2594
+ return -1;
2595
+ },
2596
+ getNode() {
2597
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
2598
+ return null;
2599
+ },
2600
+ removeNodeFromMap() {
2601
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
2602
+ },
2603
+ has() {
2604
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
2605
+ return false;
2606
+ },
2607
+ reset() {
2608
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
2609
+ }
2610
+ };
2611
+ if (typeof window !== "undefined" && window.Proxy && window.Reflect) {
2612
+ _mirror = new Proxy(_mirror, {
2613
+ get(target, prop, receiver) {
2614
+ if (prop === "map") {
2615
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
2616
+ }
2617
+ return Reflect.get(target, prop, receiver);
2618
+ }
2619
+ });
2620
+ }
2621
+ function polyfill(win = window) {
2622
+ if ("NodeList" in win && !win.NodeList.prototype.forEach) {
2623
+ win.NodeList.prototype.forEach = Array.prototype.forEach;
2624
+ }
2625
+ if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) {
2626
+ win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
2627
+ }
2628
+ if (!Node.prototype.contains) {
2629
+ Node.prototype.contains = function contains(node) {
2630
+ if (!(0 in arguments)) {
2631
+ throw new TypeError("1 argument is required");
2632
+ }
2633
+ do {
2634
+ if (this === node) {
2635
+ return true;
2636
+ }
2637
+ } while (node = node && node.parentNode);
2638
+ return false;
2639
+ };
2640
+ }
2641
+ }
2642
+ function queueToResolveTrees(queue) {
2643
+ const queueNodeMap = {};
2644
+ const putIntoMap = (m, parent) => {
2645
+ const nodeInTree = {
2646
+ value: m,
2647
+ parent,
2648
+ children: []
2649
+ };
2650
+ queueNodeMap[m.node.id] = nodeInTree;
2651
+ return nodeInTree;
2652
+ };
2653
+ const queueNodeTrees = [];
2654
+ for (const mutation of queue) {
2655
+ const { nextId, parentId } = mutation;
2656
+ if (nextId && nextId in queueNodeMap) {
2657
+ const nextInTree = queueNodeMap[nextId];
2658
+ if (nextInTree.parent) {
2659
+ const idx = nextInTree.parent.children.indexOf(nextInTree);
2660
+ nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));
2661
+ } else {
2662
+ const idx = queueNodeTrees.indexOf(nextInTree);
2663
+ queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));
2664
+ }
2665
+ continue;
2666
+ }
2667
+ if (parentId in queueNodeMap) {
2668
+ const parentInTree = queueNodeMap[parentId];
2669
+ parentInTree.children.push(putIntoMap(mutation, parentInTree));
2670
+ continue;
2671
+ }
2672
+ queueNodeTrees.push(putIntoMap(mutation, null));
2673
+ }
2674
+ return queueNodeTrees;
2675
+ }
2676
+ function iterateResolveTree(tree, cb) {
2677
+ cb(tree.value);
2678
+ for (let i = tree.children.length - 1; i >= 0; i--) {
2679
+ iterateResolveTree(tree.children[i], cb);
2680
+ }
2681
+ }
2682
+ function isSerializedIframe(n, mirror) {
2683
+ return Boolean(n.nodeName === "IFRAME" && mirror.getMeta(n));
2684
+ }
2685
+ function getBaseDimension(node, rootIframe) {
2686
+ var _a, _b;
2687
+ const frameElement = (_b = (_a = node.ownerDocument) == null ? void 0 : _a.defaultView) == null ? void 0 : _b.frameElement;
2688
+ if (!frameElement || frameElement === rootIframe) {
2689
+ return {
2690
+ x: 0,
2691
+ y: 0,
2692
+ relativeScale: 1,
2693
+ absoluteScale: 1
2694
+ };
2695
+ }
2696
+ const frameDimension = frameElement.getBoundingClientRect();
2697
+ const frameBaseDimension = getBaseDimension(frameElement, rootIframe);
2698
+ const relativeScale = frameDimension.height / frameElement.clientHeight;
2699
+ return {
2700
+ x: frameDimension.x * frameBaseDimension.relativeScale + frameBaseDimension.x,
2701
+ y: frameDimension.y * frameBaseDimension.relativeScale + frameBaseDimension.y,
2702
+ relativeScale,
2703
+ absoluteScale: frameBaseDimension.absoluteScale * relativeScale
2704
+ };
2705
+ }
2706
+ function hasShadowRoot(n) {
2707
+ return Boolean(n == null ? void 0 : n.shadowRoot);
2708
+ }
2709
+ function getNestedRule(rules, position) {
2710
+ const rule = rules[position[0]];
2711
+ if (position.length === 1) {
2712
+ return rule;
2713
+ } else {
2714
+ return getNestedRule(rule.cssRules[position[1]].cssRules, position.slice(2));
2715
+ }
2716
+ }
2717
+ function getPositionsAndIndex(nestedIndex) {
2718
+ const positions = [...nestedIndex];
2719
+ const index = positions.pop();
2720
+ return { positions, index };
2721
+ }
2722
+ function uniqueTextMutations(mutations) {
2723
+ const idSet = /* @__PURE__ */ new Set();
2724
+ const uniqueMutations = [];
2725
+ for (let i = mutations.length; i--; ) {
2726
+ const mutation = mutations[i];
2727
+ if (!idSet.has(mutation.id)) {
2728
+ uniqueMutations.push(mutation);
2729
+ idSet.add(mutation.id);
2730
+ }
2731
+ }
2732
+ return uniqueMutations;
2733
+ }
2734
+
2735
+ const rules = (blockClass) => [
2736
+ `.${blockClass} { background: currentColor }`,
2737
+ "noscript { display: none !important; }",
2738
+ `.${blockClass} { background: currentColor; border-radius: 5px; }`,
2739
+ `.${blockClass}:hover::after {content: 'Redacted'; color: white; background: black; text-align: center; width: 100%; display: block;}`
2740
+ ];
2741
+
2742
+ /*
2743
+ * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
2744
+ * Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
2745
+ * Released under MIT License
2746
+ */
2747
+ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2748
+ // Use a lookup table to find the index.
2749
+ var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
2750
+ for (var i$1 = 0; i$1 < chars.length; i$1++) {
2751
+ lookup[chars.charCodeAt(i$1)] = i$1;
2752
+ }
2753
+ var decode = function (base64) {
2754
+ var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
2755
+ if (base64[base64.length - 1] === '=') {
2756
+ bufferLength--;
2757
+ if (base64[base64.length - 2] === '=') {
2758
+ bufferLength--;
2759
+ }
2760
+ }
2761
+ var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
2762
+ for (i = 0; i < len; i += 4) {
2763
+ encoded1 = lookup[base64.charCodeAt(i)];
2764
+ encoded2 = lookup[base64.charCodeAt(i + 1)];
2765
+ encoded3 = lookup[base64.charCodeAt(i + 2)];
2766
+ encoded4 = lookup[base64.charCodeAt(i + 3)];
2767
+ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
2768
+ bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
2769
+ bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
2770
+ }
2771
+ return arraybuffer;
2772
+ };
2773
+
2774
+ var __async$4 = (__this, __arguments, generator) => {
2775
+ return new Promise((resolve, reject) => {
2776
+ var fulfilled = (value) => {
2777
+ try {
2778
+ step(generator.next(value));
2779
+ } catch (e) {
2780
+ reject(e);
2781
+ }
2782
+ };
2783
+ var rejected = (value) => {
2784
+ try {
2785
+ step(generator.throw(value));
2786
+ } catch (e) {
2787
+ reject(e);
2788
+ }
2789
+ };
2790
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
2791
+ step((generator = generator.apply(__this, __arguments)).next());
2792
+ });
2793
+ };
2794
+ const webGLVarMap = /* @__PURE__ */ new Map();
2795
+ function variableListFor(ctx, ctor) {
2796
+ let contextMap = webGLVarMap.get(ctx);
2797
+ if (!contextMap) {
2798
+ contextMap = /* @__PURE__ */ new Map();
2799
+ webGLVarMap.set(ctx, contextMap);
2800
+ }
2801
+ if (!contextMap.has(ctor)) {
2802
+ contextMap.set(ctor, []);
2803
+ }
2804
+ return contextMap.get(ctor);
2805
+ }
2806
+ function deserializeArg(imageMap, ctx, preload) {
2807
+ return (arg) => __async$4(this, null, function* () {
2808
+ if (arg && typeof arg === "object" && "rr_type" in arg) {
2809
+ if (preload)
2810
+ preload.isUnchanged = false;
2811
+ if (arg.rr_type === "ImageBitmap" && "args" in arg) {
2812
+ const args = yield deserializeArg(imageMap, ctx, preload)(arg.args);
2813
+ return yield createImageBitmap.apply(null, args);
2814
+ } else if ("index" in arg) {
2815
+ if (preload || ctx === null)
2816
+ return arg;
2817
+ const { rr_type: name, index } = arg;
2818
+ return variableListFor(ctx, name)[index];
2819
+ } else if ("args" in arg) {
2820
+ const { rr_type: name, args } = arg;
2821
+ const ctor = window[name];
2822
+ return new ctor(...yield Promise.all(args.map(deserializeArg(imageMap, ctx, preload))));
2823
+ } else if ("base64" in arg) {
2824
+ return decode(arg.base64);
2825
+ } else if ("src" in arg) {
2826
+ const image = imageMap.get(arg.src);
2827
+ if (image) {
2828
+ return image;
2829
+ } else {
2830
+ const image2 = new Image();
2831
+ image2.src = arg.src;
2832
+ imageMap.set(arg.src, image2);
2833
+ return image2;
2834
+ }
2835
+ } else if ("data" in arg && arg.rr_type === "Blob") {
2836
+ const blobContents = yield Promise.all(arg.data.map(deserializeArg(imageMap, ctx, preload)));
2837
+ const blob = new Blob(blobContents, {
2838
+ type: arg.type
2839
+ });
2840
+ return blob;
2841
+ }
2842
+ } else if (Array.isArray(arg)) {
2843
+ const result = yield Promise.all(arg.map(deserializeArg(imageMap, ctx, preload)));
2844
+ return result;
2845
+ }
2846
+ return arg;
2847
+ });
2848
+ }
2849
+
2850
+ var __async$3 = (__this, __arguments, generator) => {
2851
+ return new Promise((resolve, reject) => {
2852
+ var fulfilled = (value) => {
2853
+ try {
2854
+ step(generator.next(value));
2855
+ } catch (e) {
2856
+ reject(e);
2857
+ }
2858
+ };
2859
+ var rejected = (value) => {
2860
+ try {
2861
+ step(generator.throw(value));
2862
+ } catch (e) {
2863
+ reject(e);
2864
+ }
2865
+ };
2866
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
2867
+ step((generator = generator.apply(__this, __arguments)).next());
2868
+ });
2869
+ };
2870
+ function getContext(target, type) {
2871
+ try {
2872
+ if (type === CanvasContext.WebGL) {
2873
+ return target.getContext("webgl") || target.getContext("experimental-webgl");
2874
+ }
2875
+ return target.getContext("webgl2");
2876
+ } catch (e) {
2877
+ return null;
2878
+ }
2879
+ }
2880
+ const WebGLVariableConstructorsNames = [
2881
+ "WebGLActiveInfo",
2882
+ "WebGLBuffer",
2883
+ "WebGLFramebuffer",
2884
+ "WebGLProgram",
2885
+ "WebGLRenderbuffer",
2886
+ "WebGLShader",
2887
+ "WebGLShaderPrecisionFormat",
2888
+ "WebGLTexture",
2889
+ "WebGLUniformLocation",
2890
+ "WebGLVertexArrayObject"
2891
+ ];
2892
+ function saveToWebGLVarMap(ctx, result) {
2893
+ if (!(result == null ? void 0 : result.constructor))
2894
+ return;
2895
+ const { name } = result.constructor;
2896
+ if (!WebGLVariableConstructorsNames.includes(name))
2897
+ return;
2898
+ const variables = variableListFor(ctx, name);
2899
+ if (!variables.includes(result))
2900
+ variables.push(result);
2901
+ }
2902
+ function webglMutation(_0) {
2903
+ return __async$3(this, arguments, function* ({
2904
+ mutation,
2905
+ target,
2906
+ type,
2907
+ imageMap,
2908
+ errorHandler
2909
+ }) {
2910
+ try {
2911
+ const ctx = getContext(target, type);
2912
+ if (!ctx)
2913
+ return;
2914
+ if (mutation.setter) {
2915
+ ctx[mutation.property] = mutation.args[0];
2916
+ return;
2917
+ }
2918
+ const original = ctx[mutation.property];
2919
+ const args = yield Promise.all(mutation.args.map(deserializeArg(imageMap, ctx)));
2920
+ const result = original.apply(ctx, args);
2921
+ saveToWebGLVarMap(ctx, result);
2922
+ const debugMode = false;
2923
+ if (debugMode) ;
2924
+ } catch (error) {
2925
+ errorHandler(mutation, error);
2926
+ }
2927
+ });
2928
+ }
2929
+
2930
+ var __async$2 = (__this, __arguments, generator) => {
2931
+ return new Promise((resolve, reject) => {
2932
+ var fulfilled = (value) => {
2933
+ try {
2934
+ step(generator.next(value));
2935
+ } catch (e) {
2936
+ reject(e);
2937
+ }
2938
+ };
2939
+ var rejected = (value) => {
2940
+ try {
2941
+ step(generator.throw(value));
2942
+ } catch (e) {
2943
+ reject(e);
2944
+ }
2945
+ };
2946
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
2947
+ step((generator = generator.apply(__this, __arguments)).next());
2948
+ });
2949
+ };
2950
+ function canvasMutation$1(_0) {
2951
+ return __async$2(this, arguments, function* ({
2952
+ event,
2953
+ mutation,
2954
+ target,
2955
+ imageMap,
2956
+ errorHandler
2957
+ }) {
2958
+ try {
2959
+ const ctx = target.getContext("2d");
2960
+ if (mutation.setter) {
2961
+ ctx[mutation.property] = mutation.args[0];
2962
+ return;
2963
+ }
2964
+ const original = ctx[mutation.property];
2965
+ if (mutation.property === "drawImage" && typeof mutation.args[0] === "string") {
2966
+ const image = imageMap.get(event);
2967
+ original.apply(ctx, mutation.args);
2968
+ } else {
2969
+ const args = yield Promise.all(mutation.args.map(deserializeArg(imageMap, ctx)));
2970
+ original.apply(ctx, args);
2971
+ }
2972
+ } catch (error) {
2973
+ errorHandler(mutation, error);
2974
+ }
2975
+ });
2976
+ }
2977
+
2978
+ var __async$1 = (__this, __arguments, generator) => {
2979
+ return new Promise((resolve, reject) => {
2980
+ var fulfilled = (value) => {
2981
+ try {
2982
+ step(generator.next(value));
2983
+ } catch (e) {
2984
+ reject(e);
2985
+ }
2986
+ };
2987
+ var rejected = (value) => {
2988
+ try {
2989
+ step(generator.throw(value));
2990
+ } catch (e) {
2991
+ reject(e);
2992
+ }
2993
+ };
2994
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
2995
+ step((generator = generator.apply(__this, __arguments)).next());
2996
+ });
2997
+ };
2998
+ function canvasMutation(_0) {
2999
+ return __async$1(this, arguments, function* ({
3000
+ event,
3001
+ mutation,
3002
+ target,
3003
+ imageMap,
3004
+ canvasEventMap,
3005
+ errorHandler
3006
+ }) {
3007
+ try {
3008
+ const precomputedMutation = canvasEventMap.get(event) || mutation;
3009
+ const commands = "commands" in precomputedMutation ? precomputedMutation.commands : [precomputedMutation];
3010
+ if ([CanvasContext.WebGL, CanvasContext.WebGL2].includes(mutation.type)) {
3011
+ for (let i = 0; i < commands.length; i++) {
3012
+ const command = commands[i];
3013
+ yield webglMutation({
3014
+ mutation: command,
3015
+ type: mutation.type,
3016
+ target,
3017
+ imageMap,
3018
+ errorHandler
3019
+ });
3020
+ }
3021
+ return;
3022
+ }
3023
+ for (let i = 0; i < commands.length; i++) {
3024
+ const command = commands[i];
3025
+ yield canvasMutation$1({
3026
+ event,
3027
+ mutation: command,
3028
+ target,
3029
+ imageMap,
3030
+ errorHandler
3031
+ });
3032
+ }
3033
+ } catch (error) {
3034
+ errorHandler(mutation, error);
3035
+ }
3036
+ });
3037
+ }
3038
+
3039
+ var __defProp = Object.defineProperty;
3040
+ var __defProps = Object.defineProperties;
3041
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
3042
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3043
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
3044
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
3045
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3046
+ var __spreadValues = (a, b) => {
3047
+ for (var prop in b || (b = {}))
3048
+ if (__hasOwnProp.call(b, prop))
3049
+ __defNormalProp(a, prop, b[prop]);
3050
+ if (__getOwnPropSymbols)
3051
+ for (var prop of __getOwnPropSymbols(b)) {
3052
+ if (__propIsEnum.call(b, prop))
3053
+ __defNormalProp(a, prop, b[prop]);
3054
+ }
3055
+ return a;
3056
+ };
3057
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
3058
+ var __async = (__this, __arguments, generator) => {
3059
+ return new Promise((resolve, reject) => {
3060
+ var fulfilled = (value) => {
3061
+ try {
3062
+ step(generator.next(value));
3063
+ } catch (e) {
3064
+ reject(e);
3065
+ }
3066
+ };
3067
+ var rejected = (value) => {
3068
+ try {
3069
+ step(generator.throw(value));
3070
+ } catch (e) {
3071
+ reject(e);
3072
+ }
3073
+ };
3074
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
3075
+ step((generator = generator.apply(__this, __arguments)).next());
3076
+ });
3077
+ };
3078
+ const SKIP_TIME_THRESHOLD = 10 * 1e3;
3079
+ const SKIP_TIME_INTERVAL = 2 * 1e3;
3080
+ const SKIP_TIME_MIN = 1 * 1e3;
3081
+ const SKIP_DURATION_LIMIT = 60 * 60 * 1e3;
3082
+ const mitt = mitt$1 || mittProxy;
3083
+ const REPLAY_CONSOLE_PREFIX = "[replayer]";
3084
+ const defaultMouseTailConfig = {
3085
+ duration: 500,
3086
+ lineCap: "round",
3087
+ lineWidth: 3,
3088
+ strokeStyle: "red"
3089
+ };
3090
+ function indicatesTouchDevice(e) {
3091
+ return e.type == EventType.IncrementalSnapshot && (e.data.source == IncrementalSource.TouchMove || e.data.source == IncrementalSource.MouseInteraction && e.data.type == MouseInteractions.TouchStart);
3092
+ }
3093
+ class Replayer {
3094
+ constructor(events, config) {
3095
+ this.usingVirtualDom = false;
3096
+ this.virtualDom = new RRDocument();
3097
+ this.mouseTail = null;
3098
+ this.tailPositions = [];
3099
+ this.emitter = mitt();
3100
+ this.activityIntervals = [];
3101
+ this.legacy_missingNodeRetryMap = {};
3102
+ this.cache = createCache();
3103
+ this.imageMap = /* @__PURE__ */ new Map();
3104
+ this.canvasEventMap = /* @__PURE__ */ new Map();
3105
+ this.mirror = createMirror$2();
3106
+ this.firstFullSnapshot = null;
3107
+ this.newDocumentQueue = [];
3108
+ this.mousePos = null;
3109
+ this.touchActive = null;
3110
+ if (!(config == null ? void 0 : config.liveMode) && events.length < 2) {
3111
+ throw new Error("Replayer need at least 2 events.");
3112
+ }
3113
+ const defaultConfig = {
3114
+ speed: 1,
3115
+ maxSpeed: 360,
3116
+ root: document.body,
3117
+ loadTimeout: 0,
3118
+ skipInactive: false,
3119
+ showWarning: true,
3120
+ showDebug: false,
3121
+ blockClass: "highlight-block",
3122
+ liveMode: false,
3123
+ insertStyleRules: [],
3124
+ triggerFocus: true,
3125
+ UNSAFE_replayCanvas: false,
3126
+ pauseAnimation: true,
3127
+ mouseTail: defaultMouseTailConfig,
3128
+ useVirtualDom: true,
3129
+ inactiveThreshold: 0.02,
3130
+ inactiveSkipTime: SKIP_TIME_INTERVAL
3131
+ };
3132
+ this.config = Object.assign({}, defaultConfig, config);
3133
+ this.handleResize = this.handleResize.bind(this);
3134
+ this.getCastFn = this.getCastFn.bind(this);
3135
+ this.applyEventsSynchronously = this.applyEventsSynchronously.bind(this);
3136
+ this.emitter.on(ReplayerEvents.Resize, this.handleResize);
3137
+ this.setupDom();
3138
+ this.emitter.on(ReplayerEvents.Flush, () => {
3139
+ if (this.usingVirtualDom) {
3140
+ const replayerHandler = {
3141
+ mirror: this.mirror,
3142
+ applyCanvas: (canvasEvent, canvasMutationData2, target) => {
3143
+ canvasMutation({
3144
+ event: canvasEvent,
3145
+ mutation: canvasMutationData2,
3146
+ target,
3147
+ imageMap: this.imageMap,
3148
+ canvasEventMap: this.canvasEventMap,
3149
+ errorHandler: this.warnCanvasMutationFailed.bind(this)
3150
+ });
3151
+ },
3152
+ applyInput: this.applyInput.bind(this),
3153
+ applyScroll: this.applyScroll.bind(this)
3154
+ };
3155
+ diff(this.iframe.contentDocument, this.virtualDom, replayerHandler, this.virtualDom.mirror);
3156
+ this.virtualDom.destroyTree();
3157
+ this.usingVirtualDom = false;
3158
+ if (Object.keys(this.legacy_missingNodeRetryMap).length) {
3159
+ for (const key in this.legacy_missingNodeRetryMap) {
3160
+ try {
3161
+ const value = this.legacy_missingNodeRetryMap[key];
3162
+ const realNode = createOrGetNode(value.node, this.mirror, this.virtualDom.mirror);
3163
+ diff(realNode, value.node, replayerHandler, this.virtualDom.mirror);
3164
+ value.node = realNode;
3165
+ } catch (error) {
3166
+ if (this.config.showWarning) {
3167
+ console.warn(error);
3168
+ }
3169
+ }
3170
+ }
3171
+ }
3172
+ }
3173
+ if (this.mousePos) {
3174
+ this.moveAndHover(this.mousePos.x, this.mousePos.y, this.mousePos.id, true, this.mousePos.debugData);
3175
+ }
3176
+ this.mousePos = null;
3177
+ });
3178
+ this.emitter.on(ReplayerEvents.PlayBack, () => {
3179
+ this.firstFullSnapshot = null;
3180
+ this.mirror.reset();
3181
+ });
3182
+ const timer = new Timer([], (config == null ? void 0 : config.speed) || defaultConfig.speed);
3183
+ this.service = createPlayerService({
3184
+ events: events.map((e) => {
3185
+ if (config && config.unpackFn) {
3186
+ return config.unpackFn(e);
3187
+ }
3188
+ return e;
3189
+ }).sort((a1, a2) => a1.timestamp - a2.timestamp),
3190
+ timer,
3191
+ timeOffset: 0,
3192
+ baselineTime: 0,
3193
+ lastPlayedEvent: null
3194
+ }, {
3195
+ getCastFn: this.getCastFn,
3196
+ applyEventsSynchronously: this.applyEventsSynchronously,
3197
+ emitter: this.emitter
3198
+ });
3199
+ this.service.start();
3200
+ this.service.subscribe((state) => {
3201
+ this.emitter.emit(ReplayerEvents.StateChange, {
3202
+ player: state
3203
+ });
3204
+ });
3205
+ this.speedService = createSpeedService({
3206
+ normalSpeed: -1,
3207
+ timer
3208
+ });
3209
+ this.speedService.start();
3210
+ this.speedService.subscribe((state) => {
3211
+ this.emitter.emit(ReplayerEvents.StateChange, {
3212
+ speed: state
3213
+ });
3214
+ });
3215
+ const firstMeta = this.service.state.context.events.find((e) => e.type === EventType.Meta);
3216
+ const firstFullsnapshot = this.service.state.context.events.find((e) => e.type === EventType.FullSnapshot);
3217
+ if (firstMeta) {
3218
+ const { width, height } = firstMeta.data;
3219
+ setTimeout(() => {
3220
+ this.emitter.emit(ReplayerEvents.Resize, {
3221
+ width,
3222
+ height
3223
+ });
3224
+ }, 0);
3225
+ }
3226
+ if (firstFullsnapshot) {
3227
+ setTimeout(() => {
3228
+ if (this.firstFullSnapshot) {
3229
+ return;
3230
+ }
3231
+ this.firstFullSnapshot = firstFullsnapshot;
3232
+ this.rebuildFullSnapshot(firstFullsnapshot);
3233
+ this.iframe.contentWindow.scrollTo(firstFullsnapshot.data.initialOffset);
3234
+ }, 1);
3235
+ }
3236
+ if (this.service.state.context.events.find(indicatesTouchDevice)) {
3237
+ this.mouse.classList.add("touch-device");
3238
+ }
3239
+ }
3240
+ get timer() {
3241
+ return this.service.state.context.timer;
3242
+ }
3243
+ on(event, handler) {
3244
+ this.emitter.on(event, handler);
3245
+ return this;
3246
+ }
3247
+ off(event, handler) {
3248
+ this.emitter.off(event, handler);
3249
+ return this;
3250
+ }
3251
+ setConfig(config) {
3252
+ Object.keys(config).forEach((key) => {
3253
+ this.config[key] = config[key];
3254
+ });
3255
+ if (!this.config.skipInactive) {
3256
+ this.backToNormal();
3257
+ }
3258
+ if (typeof config.speed !== "undefined") {
3259
+ this.speedService.send({
3260
+ type: "SET_SPEED",
3261
+ payload: {
3262
+ speed: config.speed
3263
+ }
3264
+ });
3265
+ }
3266
+ if (typeof config.mouseTail !== "undefined") {
3267
+ if (config.mouseTail === false) {
3268
+ if (this.mouseTail) {
3269
+ this.mouseTail.style.display = "none";
3270
+ }
3271
+ } else {
3272
+ if (!this.mouseTail) {
3273
+ this.mouseTail = document.createElement("canvas");
3274
+ this.mouseTail.width = Number.parseFloat(this.iframe.width);
3275
+ this.mouseTail.height = Number.parseFloat(this.iframe.height);
3276
+ this.mouseTail.classList.add("replayer-mouse-tail");
3277
+ this.wrapper.insertBefore(this.mouseTail, this.iframe);
3278
+ }
3279
+ this.mouseTail.style.display = "inherit";
3280
+ }
3281
+ }
3282
+ }
3283
+ getActivityIntervals() {
3284
+ if (this.activityIntervals.length == 0) {
3285
+ const allIntervals = [];
3286
+ const metadata = this.getMetaData();
3287
+ const userInteractionEvents = [
3288
+ { timestamp: metadata.startTime },
3289
+ ...this.service.state.context.events.filter((ev) => this.isUserInteraction(ev)),
3290
+ { timestamp: metadata.endTime }
3291
+ ];
3292
+ for (let i = 1; i < userInteractionEvents.length; i++) {
3293
+ const currentInterval2 = userInteractionEvents[i - 1];
3294
+ const _event = userInteractionEvents[i];
3295
+ if (_event.timestamp - currentInterval2.timestamp > SKIP_TIME_THRESHOLD) {
3296
+ allIntervals.push({
3297
+ startTime: currentInterval2.timestamp,
3298
+ endTime: _event.timestamp,
3299
+ duration: _event.timestamp - currentInterval2.timestamp,
3300
+ active: false
3301
+ });
3302
+ } else {
3303
+ allIntervals.push({
3304
+ startTime: currentInterval2.timestamp,
3305
+ endTime: _event.timestamp,
3306
+ duration: _event.timestamp - currentInterval2.timestamp,
3307
+ active: true
3308
+ });
3309
+ }
3310
+ }
3311
+ const mergedIntervals = [];
3312
+ let currentInterval = allIntervals[0];
3313
+ for (let i = 1; i < allIntervals.length; i++) {
3314
+ if (allIntervals[i].active != allIntervals[i - 1].active) {
3315
+ mergedIntervals.push({
3316
+ startTime: currentInterval.startTime,
3317
+ endTime: allIntervals[i - 1].endTime,
3318
+ duration: allIntervals[i - 1].endTime - currentInterval.startTime,
3319
+ active: allIntervals[i - 1].active
3320
+ });
3321
+ currentInterval = allIntervals[i];
3322
+ }
3323
+ }
3324
+ if (currentInterval && allIntervals.length > 0) {
3325
+ mergedIntervals.push({
3326
+ startTime: currentInterval.startTime,
3327
+ endTime: allIntervals[allIntervals.length - 1].endTime,
3328
+ duration: allIntervals[allIntervals.length - 1].endTime - currentInterval.startTime,
3329
+ active: allIntervals[allIntervals.length - 1].active
3330
+ });
3331
+ }
3332
+ currentInterval = mergedIntervals[0];
3333
+ for (let i = 1; i < mergedIntervals.length; i++) {
3334
+ if (!mergedIntervals[i].active && mergedIntervals[i].duration > this.config.inactiveThreshold * metadata.totalTime || !mergedIntervals[i - 1].active && mergedIntervals[i - 1].duration > this.config.inactiveThreshold * metadata.totalTime) {
3335
+ this.activityIntervals.push({
3336
+ startTime: currentInterval.startTime,
3337
+ endTime: mergedIntervals[i - 1].endTime,
3338
+ duration: mergedIntervals[i - 1].endTime - currentInterval.startTime,
3339
+ active: mergedIntervals[i - 1].active
3340
+ });
3341
+ currentInterval = mergedIntervals[i];
3342
+ }
3343
+ }
3344
+ if (currentInterval && mergedIntervals.length > 0) {
3345
+ this.activityIntervals.push({
3346
+ startTime: currentInterval.startTime,
3347
+ endTime: mergedIntervals[mergedIntervals.length - 1].endTime,
3348
+ duration: mergedIntervals[mergedIntervals.length - 1].endTime - currentInterval.startTime,
3349
+ active: mergedIntervals[mergedIntervals.length - 1].active
3350
+ });
3351
+ }
3352
+ }
3353
+ return this.activityIntervals;
3354
+ }
3355
+ getMetaData() {
3356
+ const firstEvent = this.service.state.context.events[0];
3357
+ const lastEvent = this.service.state.context.events[this.service.state.context.events.length - 1];
3358
+ return {
3359
+ startTime: firstEvent.timestamp,
3360
+ endTime: lastEvent.timestamp,
3361
+ totalTime: lastEvent.timestamp - firstEvent.timestamp
3362
+ };
3363
+ }
3364
+ getCurrentTime() {
3365
+ return this.timer.timeOffset + this.getTimeOffset();
3366
+ }
3367
+ getTimeOffset() {
3368
+ const { baselineTime, events } = this.service.state.context;
3369
+ return baselineTime - events[0].timestamp;
3370
+ }
3371
+ getMirror() {
3372
+ return this.mirror;
3373
+ }
3374
+ play(timeOffset = 0) {
3375
+ var _a, _b;
3376
+ if (this.service.state.matches("paused")) {
3377
+ this.service.send({ type: "PLAY", payload: { timeOffset } });
3378
+ } else {
3379
+ this.service.send({ type: "PAUSE" });
3380
+ this.service.send({ type: "PLAY", payload: { timeOffset } });
3381
+ }
3382
+ (_b = (_a = this.iframe.contentDocument) == null ? void 0 : _a.getElementsByTagName("html")[0]) == null ? void 0 : _b.classList.remove("rrweb-paused");
3383
+ this.emitter.emit(ReplayerEvents.Start);
3384
+ this.handleInactivity(this.getMetaData().startTime + timeOffset, true);
3385
+ }
3386
+ pause(timeOffset) {
3387
+ var _a, _b;
3388
+ if (timeOffset === void 0 && this.service.state.matches("playing")) {
3389
+ this.service.send({ type: "PAUSE" });
3390
+ }
3391
+ if (typeof timeOffset === "number") {
3392
+ this.play(timeOffset);
3393
+ this.service.send({ type: "PAUSE" });
3394
+ }
3395
+ (_b = (_a = this.iframe.contentDocument) == null ? void 0 : _a.getElementsByTagName("html")[0]) == null ? void 0 : _b.classList.add("rrweb-paused");
3396
+ this.emitter.emit(ReplayerEvents.Pause);
3397
+ }
3398
+ resume(timeOffset = 0) {
3399
+ console.warn(`The 'resume' will be departed in 1.0. Please use 'play' method which has the same interface.`);
3400
+ this.play(timeOffset);
3401
+ this.emitter.emit(ReplayerEvents.Resume);
3402
+ }
3403
+ startLive(baselineTime) {
3404
+ this.service.send({ type: "TO_LIVE", payload: { baselineTime } });
3405
+ }
3406
+ addEvent(rawEvent) {
3407
+ const event = this.config.unpackFn ? this.config.unpackFn(rawEvent) : rawEvent;
3408
+ if (indicatesTouchDevice(event)) {
3409
+ this.mouse.classList.add("touch-device");
3410
+ }
3411
+ Promise.resolve().then(() => this.service.send({ type: "ADD_EVENT", payload: { event } }));
3412
+ }
3413
+ replaceEvents(events) {
3414
+ for (const event of events) {
3415
+ if (indicatesTouchDevice(event)) {
3416
+ this.mouse.classList.add("touch-device");
3417
+ break;
3418
+ }
3419
+ }
3420
+ this.service.send({ type: "REPLACE_EVENTS", payload: { events } });
3421
+ }
3422
+ enableInteract() {
3423
+ this.iframe.setAttribute("scrolling", "auto");
3424
+ this.iframe.style.pointerEvents = "auto";
3425
+ }
3426
+ disableInteract() {
3427
+ this.iframe.setAttribute("scrolling", "no");
3428
+ this.iframe.style.pointerEvents = "none";
3429
+ }
3430
+ resetCache() {
3431
+ this.cache = createCache();
3432
+ }
3433
+ setupDom() {
3434
+ this.wrapper = document.createElement("div");
3435
+ this.wrapper.classList.add("replayer-wrapper");
3436
+ this.config.root.appendChild(this.wrapper);
3437
+ this.mouse = document.createElement("div");
3438
+ this.mouse.classList.add("replayer-mouse");
3439
+ this.wrapper.appendChild(this.mouse);
3440
+ if (this.config.mouseTail !== false) {
3441
+ this.mouseTail = document.createElement("canvas");
3442
+ this.mouseTail.classList.add("replayer-mouse-tail");
3443
+ this.mouseTail.style.display = "inherit";
3444
+ this.wrapper.appendChild(this.mouseTail);
3445
+ }
3446
+ this.iframe = document.createElement("iframe");
3447
+ const attributes = ["allow-same-origin"];
3448
+ if (this.config.UNSAFE_replayCanvas) {
3449
+ attributes.push("allow-scripts");
3450
+ }
3451
+ this.iframe.style.display = "none";
3452
+ this.iframe.setAttribute("sandbox", attributes.join(" "));
3453
+ this.disableInteract();
3454
+ this.wrapper.appendChild(this.iframe);
3455
+ if (this.iframe.contentWindow && this.iframe.contentDocument) {
3456
+ polyfill$1(this.iframe.contentWindow, this.iframe.contentDocument);
3457
+ polyfill(this.iframe.contentWindow);
3458
+ }
3459
+ }
3460
+ handleResize(dimension) {
3461
+ this.iframe.style.display = "inherit";
3462
+ for (const el of [this.mouseTail, this.iframe]) {
3463
+ if (!el) {
3464
+ continue;
3465
+ }
3466
+ el.setAttribute("width", String(dimension.width));
3467
+ el.setAttribute("height", String(dimension.height));
3468
+ }
3469
+ }
3470
+ applyEventsSynchronously(events) {
3471
+ for (const event of events) {
3472
+ switch (event.type) {
3473
+ case EventType.DomContentLoaded:
3474
+ case EventType.Load:
3475
+ case EventType.Custom:
3476
+ continue;
3477
+ case EventType.FullSnapshot:
3478
+ case EventType.Meta:
3479
+ case EventType.Plugin:
3480
+ case EventType.IncrementalSnapshot:
3481
+ break;
3482
+ }
3483
+ const castFn = this.getCastFn(event, true);
3484
+ castFn();
3485
+ }
3486
+ if (this.touchActive === true) {
3487
+ this.mouse.classList.add("touch-active");
3488
+ } else if (this.touchActive === false) {
3489
+ this.mouse.classList.remove("touch-active");
3490
+ }
3491
+ this.touchActive = null;
3492
+ }
3493
+ getCastFn(event, isSync = false) {
3494
+ let castFn;
3495
+ switch (event.type) {
3496
+ case EventType.DomContentLoaded:
3497
+ case EventType.Load:
3498
+ break;
3499
+ case EventType.Custom:
3500
+ castFn = () => {
3501
+ this.emitter.emit(ReplayerEvents.CustomEvent, event);
3502
+ };
3503
+ break;
3504
+ case EventType.Meta:
3505
+ castFn = () => this.emitter.emit(ReplayerEvents.Resize, {
3506
+ width: event.data.width,
3507
+ height: event.data.height
3508
+ });
3509
+ break;
3510
+ case EventType.FullSnapshot:
3511
+ castFn = () => {
3512
+ if (this.firstFullSnapshot) {
3513
+ if (this.firstFullSnapshot === event) {
3514
+ this.firstFullSnapshot = true;
3515
+ return;
3516
+ }
3517
+ } else {
3518
+ this.firstFullSnapshot = true;
3519
+ }
3520
+ this.rebuildFullSnapshot(event, isSync);
3521
+ this.iframe.contentWindow.scrollTo(event.data.initialOffset);
3522
+ };
3523
+ break;
3524
+ case EventType.IncrementalSnapshot:
3525
+ castFn = () => {
3526
+ this.applyIncremental(event, isSync);
3527
+ if (isSync) {
3528
+ return;
3529
+ }
3530
+ this.handleInactivity(event.timestamp);
3531
+ if (event === this.nextUserInteractionEvent) {
3532
+ this.nextUserInteractionEvent = null;
3533
+ this.backToNormal();
3534
+ }
3535
+ if (this.config.skipInactive && !this.nextUserInteractionEvent) {
3536
+ for (const _event of this.service.state.context.events) {
3537
+ if (_event.timestamp <= event.timestamp) {
3538
+ continue;
3539
+ }
3540
+ if (this.isUserInteraction(_event)) {
3541
+ if (_event.delay - event.delay > SKIP_TIME_THRESHOLD * this.speedService.state.context.timer.speed) {
3542
+ this.nextUserInteractionEvent = _event;
3543
+ }
3544
+ break;
3545
+ }
3546
+ }
3547
+ if (this.nextUserInteractionEvent) {
3548
+ const skipTime = this.nextUserInteractionEvent.delay - event.delay;
3549
+ const payload = {
3550
+ speed: Math.min(Math.round(skipTime / SKIP_TIME_INTERVAL), this.config.maxSpeed)
3551
+ };
3552
+ this.speedService.send({ type: "FAST_FORWARD", payload });
3553
+ this.emitter.emit(ReplayerEvents.SkipStart, payload);
3554
+ }
3555
+ }
3556
+ };
3557
+ break;
3558
+ }
3559
+ const wrappedCastFn = () => {
3560
+ if (castFn) {
3561
+ castFn();
3562
+ }
3563
+ for (const plugin of this.config.plugins || []) {
3564
+ plugin.handler(event, isSync, { replayer: this });
3565
+ }
3566
+ this.service.send({ type: "CAST_EVENT", payload: { event } });
3567
+ const last_index = this.service.state.context.events.length - 1;
3568
+ if (event === this.service.state.context.events[last_index]) {
3569
+ const finish = () => {
3570
+ if (last_index < this.service.state.context.events.length - 1) {
3571
+ return;
3572
+ }
3573
+ this.backToNormal();
3574
+ this.service.send("END");
3575
+ this.emitter.emit(ReplayerEvents.Finish);
3576
+ };
3577
+ if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.MouseMove && event.data.positions.length) {
3578
+ setTimeout(() => {
3579
+ finish();
3580
+ }, Math.max(0, -event.data.positions[0].timeOffset + 50));
3581
+ } else {
3582
+ finish();
3583
+ }
3584
+ }
3585
+ this.emitter.emit(ReplayerEvents.EventCast, event);
3586
+ };
3587
+ return wrappedCastFn;
3588
+ }
3589
+ handleInactivity(timestamp, resetNext) {
3590
+ if (timestamp === this.inactiveEndTimestamp || resetNext) {
3591
+ this.inactiveEndTimestamp = null;
3592
+ this.backToNormal();
3593
+ }
3594
+ if (this.config.skipInactive && !this.inactiveEndTimestamp) {
3595
+ for (const interval of this.getActivityIntervals()) {
3596
+ if (timestamp >= interval.startTime && timestamp < interval.endTime && !interval.active) {
3597
+ this.inactiveEndTimestamp = interval.endTime;
3598
+ break;
3599
+ }
3600
+ }
3601
+ if (this.inactiveEndTimestamp) {
3602
+ const skipTime = this.inactiveEndTimestamp - timestamp;
3603
+ const payload = {
3604
+ speed: skipTime / SKIP_DURATION_LIMIT * this.config.inactiveSkipTime < SKIP_TIME_MIN ? skipTime / SKIP_TIME_MIN : Math.round(Math.max(skipTime, SKIP_DURATION_LIMIT) / this.config.inactiveSkipTime)
3605
+ };
3606
+ this.speedService.send({ type: "FAST_FORWARD", payload });
3607
+ this.emitter.emit(ReplayerEvents.SkipStart, payload);
3608
+ }
3609
+ }
3610
+ }
3611
+ rebuildFullSnapshot(event, isSync = false) {
3612
+ if (!this.iframe.contentDocument) {
3613
+ return console.warn("Looks like your replayer has been destroyed.");
3614
+ }
3615
+ if (Object.keys(this.legacy_missingNodeRetryMap).length) {
3616
+ console.warn("Found unresolved missing node map", this.legacy_missingNodeRetryMap);
3617
+ }
3618
+ this.legacy_missingNodeRetryMap = {};
3619
+ const collected = [];
3620
+ rebuild(event.data.node, {
3621
+ doc: this.iframe.contentDocument,
3622
+ afterAppend: (builtNode) => {
3623
+ this.collectIframeAndAttachDocument(collected, builtNode);
3624
+ },
3625
+ cache: this.cache,
3626
+ mirror: this.mirror
3627
+ });
3628
+ for (const { mutationInQueue, builtNode } of collected) {
3629
+ this.attachDocumentToIframe(mutationInQueue, builtNode);
3630
+ this.newDocumentQueue = this.newDocumentQueue.filter((m) => m !== mutationInQueue);
3631
+ }
3632
+ const { documentElement, head } = this.iframe.contentDocument;
3633
+ this.insertStyleRules(documentElement, head);
3634
+ if (!this.service.state.matches("playing")) {
3635
+ this.iframe.contentDocument.getElementsByTagName("html")[0].classList.add("rrweb-paused");
3636
+ }
3637
+ this.emitter.emit(ReplayerEvents.FullsnapshotRebuilded, event);
3638
+ if (!isSync) {
3639
+ this.waitForStylesheetLoad();
3640
+ }
3641
+ if (this.config.UNSAFE_replayCanvas) {
3642
+ this.preloadAllImages();
3643
+ }
3644
+ }
3645
+ insertStyleRules(documentElement, head) {
3646
+ const injectStylesRules = rules(this.config.blockClass).concat(this.config.insertStyleRules);
3647
+ if (this.config.pauseAnimation) {
3648
+ injectStylesRules.push("html.rrweb-paused *, html.rrweb-paused *:before, html.rrweb-paused *:after { animation-play-state: paused !important; }");
3649
+ }
3650
+ if (this.usingVirtualDom) {
3651
+ const styleEl = this.virtualDom.createElement("style");
3652
+ this.virtualDom.mirror.add(styleEl, getDefaultSN(styleEl, this.virtualDom.unserializedId));
3653
+ documentElement.insertBefore(styleEl, head);
3654
+ for (let idx = 0; idx < injectStylesRules.length; idx++) {
3655
+ styleEl.rules.push({
3656
+ cssText: injectStylesRules[idx],
3657
+ type: StyleRuleType.Insert,
3658
+ index: idx
3659
+ });
3660
+ }
3661
+ } else {
3662
+ const styleEl = document.createElement("style");
3663
+ documentElement.insertBefore(styleEl, head);
3664
+ for (let idx = 0; idx < injectStylesRules.length; idx++) {
3665
+ styleEl.sheet.insertRule(injectStylesRules[idx], idx);
3666
+ }
3667
+ }
3668
+ }
3669
+ attachDocumentToIframe(mutation, iframeEl) {
3670
+ const mirror = this.usingVirtualDom ? this.virtualDom.mirror : this.mirror;
3671
+ const collected = [];
3672
+ buildNodeWithSN(mutation.node, {
3673
+ doc: iframeEl.contentDocument,
3674
+ mirror,
3675
+ hackCss: true,
3676
+ skipChild: false,
3677
+ afterAppend: (builtNode) => {
3678
+ this.collectIframeAndAttachDocument(collected, builtNode);
3679
+ const sn = mirror.getMeta(builtNode);
3680
+ if ((sn == null ? void 0 : sn.type) === NodeType$2.Element && (sn == null ? void 0 : sn.tagName.toUpperCase()) === "HTML") {
3681
+ const { documentElement, head } = iframeEl.contentDocument;
3682
+ this.insertStyleRules(documentElement, head);
3683
+ }
3684
+ },
3685
+ cache: this.cache
3686
+ });
3687
+ for (const { mutationInQueue, builtNode } of collected) {
3688
+ this.attachDocumentToIframe(mutationInQueue, builtNode);
3689
+ this.newDocumentQueue = this.newDocumentQueue.filter((m) => m !== mutationInQueue);
3690
+ }
3691
+ }
3692
+ collectIframeAndAttachDocument(collected, builtNode) {
3693
+ if (isSerializedIframe(builtNode, this.mirror)) {
3694
+ const mutationInQueue = this.newDocumentQueue.find((m) => m.parentId === this.mirror.getId(builtNode));
3695
+ if (mutationInQueue) {
3696
+ collected.push({
3697
+ mutationInQueue,
3698
+ builtNode
3699
+ });
3700
+ }
3701
+ }
3702
+ }
3703
+ waitForStylesheetLoad() {
3704
+ var _a;
3705
+ const head = (_a = this.iframe.contentDocument) == null ? void 0 : _a.head;
3706
+ if (head) {
3707
+ const unloadSheets = /* @__PURE__ */ new Set();
3708
+ let timer;
3709
+ let beforeLoadState = this.service.state;
3710
+ const stateHandler = () => {
3711
+ beforeLoadState = this.service.state;
3712
+ };
3713
+ this.emitter.on(ReplayerEvents.Start, stateHandler);
3714
+ this.emitter.on(ReplayerEvents.Pause, stateHandler);
3715
+ const unsubscribe = () => {
3716
+ this.emitter.off(ReplayerEvents.Start, stateHandler);
3717
+ this.emitter.off(ReplayerEvents.Pause, stateHandler);
3718
+ };
3719
+ head.querySelectorAll('link[rel="stylesheet"]').forEach((css) => {
3720
+ if (!css.sheet) {
3721
+ unloadSheets.add(css);
3722
+ css.addEventListener("load", () => {
3723
+ unloadSheets.delete(css);
3724
+ if (unloadSheets.size === 0 && timer !== -1) {
3725
+ if (beforeLoadState.matches("playing")) {
3726
+ this.play(this.getCurrentTime());
3727
+ }
3728
+ this.emitter.emit(ReplayerEvents.LoadStylesheetEnd);
3729
+ if (timer) {
3730
+ clearTimeout(timer);
3731
+ }
3732
+ unsubscribe();
3733
+ }
3734
+ });
3735
+ }
3736
+ });
3737
+ if (unloadSheets.size > 0) {
3738
+ this.service.send({ type: "PAUSE" });
3739
+ this.emitter.emit(ReplayerEvents.LoadStylesheetStart);
3740
+ timer = setTimeout(() => {
3741
+ if (beforeLoadState.matches("playing")) {
3742
+ this.play(this.getCurrentTime());
3743
+ }
3744
+ timer = -1;
3745
+ unsubscribe();
3746
+ }, this.config.loadTimeout);
3747
+ }
3748
+ }
3749
+ }
3750
+ hasImageArg(args) {
3751
+ for (const arg of args) {
3752
+ if (!arg || typeof arg !== "object") ; else if ("rr_type" in arg && "args" in arg) {
3753
+ if (this.hasImageArg(arg.args))
3754
+ return true;
3755
+ } else if ("rr_type" in arg && arg.rr_type === "HTMLImageElement") {
3756
+ return true;
3757
+ } else if (arg instanceof Array) {
3758
+ if (this.hasImageArg(arg))
3759
+ return true;
3760
+ }
3761
+ }
3762
+ return false;
3763
+ }
3764
+ getImageArgs(args) {
3765
+ const images = [];
3766
+ for (const arg of args) {
3767
+ if (!arg || typeof arg !== "object") ; else if ("rr_type" in arg && "args" in arg) {
3768
+ images.push(...this.getImageArgs(arg.args));
3769
+ } else if ("rr_type" in arg && arg.rr_type === "HTMLImageElement") {
3770
+ images.push(arg.src);
3771
+ } else if (arg instanceof Array) {
3772
+ images.push(...this.getImageArgs(arg));
3773
+ }
3774
+ }
3775
+ return images;
3776
+ }
3777
+ preloadAllImages() {
3778
+ return __async(this, null, function* () {
3779
+ this.service.state;
3780
+ const stateHandler = () => {
3781
+ this.service.state;
3782
+ };
3783
+ this.emitter.on(ReplayerEvents.Start, stateHandler);
3784
+ this.emitter.on(ReplayerEvents.Pause, stateHandler);
3785
+ const promises = [];
3786
+ for (const event of this.service.state.context.events) {
3787
+ if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.CanvasMutation) {
3788
+ promises.push(this.deserializeAndPreloadCanvasEvents(event.data, event));
3789
+ const commands = "commands" in event.data ? event.data.commands : [event.data];
3790
+ commands.forEach((c) => {
3791
+ this.preloadImages(c, event);
3792
+ });
3793
+ }
3794
+ }
3795
+ return Promise.all(promises);
3796
+ });
3797
+ }
3798
+ preloadImages(data, event) {
3799
+ if (data.property === "drawImage" && typeof data.args[0] === "string" && !this.imageMap.has(event)) {
3800
+ const canvas = document.createElement("canvas");
3801
+ const ctx = canvas.getContext("2d");
3802
+ const imgd = ctx == null ? void 0 : ctx.createImageData(canvas.width, canvas.height);
3803
+ imgd == null ? void 0 : imgd.data;
3804
+ JSON.parse(data.args[0]);
3805
+ ctx == null ? void 0 : ctx.putImageData(imgd, 0, 0);
3806
+ }
3807
+ }
3808
+ deserializeAndPreloadCanvasEvents(data, event) {
3809
+ return __async(this, null, function* () {
3810
+ if (!this.canvasEventMap.has(event)) {
3811
+ const status = {
3812
+ isUnchanged: true
3813
+ };
3814
+ if ("commands" in data) {
3815
+ const commands = yield Promise.all(data.commands.map((c) => __async(this, null, function* () {
3816
+ const args = yield Promise.all(c.args.map(deserializeArg(this.imageMap, null, status)));
3817
+ return __spreadProps(__spreadValues({}, c), { args });
3818
+ })));
3819
+ if (status.isUnchanged === false)
3820
+ this.canvasEventMap.set(event, __spreadProps(__spreadValues({}, data), { commands }));
3821
+ } else {
3822
+ const args = yield Promise.all(data.args.map(deserializeArg(this.imageMap, null, status)));
3823
+ if (status.isUnchanged === false)
3824
+ this.canvasEventMap.set(event, __spreadProps(__spreadValues({}, data), { args }));
3825
+ }
3826
+ }
3827
+ });
3828
+ }
3829
+ applyIncremental(e, isSync) {
3830
+ var _a, _b, _c, _d, _e, _f;
3831
+ const { data: d } = e;
3832
+ switch (d.source) {
3833
+ case IncrementalSource.Mutation: {
3834
+ try {
3835
+ this.applyMutation(d, isSync);
3836
+ } catch (error) {
3837
+ this.warn(`Exception in mutation ${error.message || error}`, d);
3838
+ }
3839
+ break;
3840
+ }
3841
+ case IncrementalSource.Drag:
3842
+ case IncrementalSource.TouchMove:
3843
+ case IncrementalSource.MouseMove:
3844
+ if (isSync) {
3845
+ const lastPosition = d.positions[d.positions.length - 1];
3846
+ this.mousePos = {
3847
+ x: lastPosition.x,
3848
+ y: lastPosition.y,
3849
+ id: lastPosition.id,
3850
+ debugData: d
3851
+ };
3852
+ } else {
3853
+ d.positions.forEach((p) => {
3854
+ const action = {
3855
+ doAction: () => {
3856
+ this.moveAndHover(p.x, p.y, p.id, isSync, d);
3857
+ },
3858
+ delay: p.timeOffset + e.timestamp - this.service.state.context.baselineTime
3859
+ };
3860
+ this.timer.addAction(action);
3861
+ });
3862
+ this.timer.addAction({
3863
+ doAction() {
3864
+ },
3865
+ delay: e.delay - ((_a = d.positions[0]) == null ? void 0 : _a.timeOffset)
3866
+ });
3867
+ }
3868
+ break;
3869
+ case IncrementalSource.MouseInteraction: {
3870
+ if (d.id === -1 || isSync) {
3871
+ break;
3872
+ }
3873
+ const event = new Event(MouseInteractions[d.type].toLowerCase());
3874
+ const target = this.mirror.getNode(d.id);
3875
+ if (!target) {
3876
+ return this.debugNodeNotFound(d, d.id);
3877
+ }
3878
+ this.emitter.emit(ReplayerEvents.MouseInteraction, {
3879
+ type: d.type,
3880
+ target
3881
+ });
3882
+ const { triggerFocus } = this.config;
3883
+ switch (d.type) {
3884
+ case MouseInteractions.Blur:
3885
+ if ("blur" in target) {
3886
+ target.blur();
3887
+ }
3888
+ break;
3889
+ case MouseInteractions.Focus:
3890
+ if (triggerFocus && target.focus) {
3891
+ target.focus({
3892
+ preventScroll: true
3893
+ });
3894
+ }
3895
+ break;
3896
+ case MouseInteractions.Click:
3897
+ case MouseInteractions.TouchStart:
3898
+ case MouseInteractions.TouchEnd:
3899
+ if (isSync) {
3900
+ if (d.type === MouseInteractions.TouchStart) {
3901
+ this.touchActive = true;
3902
+ } else if (d.type === MouseInteractions.TouchEnd) {
3903
+ this.touchActive = false;
3904
+ }
3905
+ this.mousePos = {
3906
+ x: d.x,
3907
+ y: d.y,
3908
+ id: d.id,
3909
+ debugData: d
3910
+ };
3911
+ } else {
3912
+ if (d.type === MouseInteractions.TouchStart) {
3913
+ this.tailPositions.length = 0;
3914
+ }
3915
+ this.moveAndHover(d.x, d.y, d.id, isSync, d);
3916
+ if (d.type === MouseInteractions.Click) {
3917
+ this.mouse.classList.remove("active");
3918
+ void this.mouse.offsetWidth;
3919
+ this.mouse.classList.add("active");
3920
+ } else if (d.type === MouseInteractions.TouchStart) {
3921
+ void this.mouse.offsetWidth;
3922
+ this.mouse.classList.add("touch-active");
3923
+ } else if (d.type === MouseInteractions.TouchEnd) {
3924
+ this.mouse.classList.remove("touch-active");
3925
+ }
3926
+ }
3927
+ break;
3928
+ case MouseInteractions.TouchCancel:
3929
+ if (isSync) {
3930
+ this.touchActive = false;
3931
+ } else {
3932
+ this.mouse.classList.remove("touch-active");
3933
+ }
3934
+ break;
3935
+ default:
3936
+ target.dispatchEvent(event);
3937
+ }
3938
+ break;
3939
+ }
3940
+ case IncrementalSource.Scroll: {
3941
+ if (d.id === -1) {
3942
+ break;
3943
+ }
3944
+ if (this.usingVirtualDom) {
3945
+ const target = this.virtualDom.mirror.getNode(d.id);
3946
+ if (!target) {
3947
+ return this.debugNodeNotFound(d, d.id);
3948
+ }
3949
+ target.scrollData = d;
3950
+ break;
3951
+ }
3952
+ this.applyScroll(d, isSync);
3953
+ break;
3954
+ }
3955
+ case IncrementalSource.ViewportResize:
3956
+ this.emitter.emit(ReplayerEvents.Resize, {
3957
+ width: d.width,
3958
+ height: d.height
3959
+ });
3960
+ break;
3961
+ case IncrementalSource.Input: {
3962
+ if (d.id === -1) {
3963
+ break;
3964
+ }
3965
+ if (this.usingVirtualDom) {
3966
+ const target = this.virtualDom.mirror.getNode(d.id);
3967
+ if (!target) {
3968
+ return this.debugNodeNotFound(d, d.id);
3969
+ }
3970
+ target.inputData = d;
3971
+ break;
3972
+ }
3973
+ this.applyInput(d);
3974
+ break;
3975
+ }
3976
+ case IncrementalSource.MediaInteraction: {
3977
+ const target = this.usingVirtualDom ? this.virtualDom.mirror.getNode(d.id) : this.mirror.getNode(d.id);
3978
+ if (!target) {
3979
+ return this.debugNodeNotFound(d, d.id);
3980
+ }
3981
+ const mediaEl = target;
3982
+ try {
3983
+ if (d.currentTime) {
3984
+ mediaEl.currentTime = d.currentTime;
3985
+ }
3986
+ if (d.volume) {
3987
+ mediaEl.volume = d.volume;
3988
+ }
3989
+ if (d.muted) {
3990
+ mediaEl.muted = d.muted;
3991
+ }
3992
+ if (d.type === MediaInteractions.Pause) {
3993
+ mediaEl.pause();
3994
+ }
3995
+ if (d.type === MediaInteractions.Play) {
3996
+ mediaEl.play();
3997
+ }
3998
+ } catch (error) {
3999
+ if (this.config.showWarning) {
4000
+ console.warn(`Failed to replay media interactions: ${error.message || error}`);
4001
+ }
4002
+ }
4003
+ break;
4004
+ }
4005
+ case IncrementalSource.StyleSheetRule: {
4006
+ if (this.usingVirtualDom) {
4007
+ const target = this.virtualDom.mirror.getNode(d.id);
4008
+ if (!target) {
4009
+ return this.debugNodeNotFound(d, d.id);
4010
+ }
4011
+ const rules = target.rules;
4012
+ (_b = d.adds) == null ? void 0 : _b.forEach(({ rule, index: nestedIndex }) => rules == null ? void 0 : rules.push({
4013
+ cssText: rule,
4014
+ index: nestedIndex,
4015
+ type: StyleRuleType.Insert
4016
+ }));
4017
+ (_c = d.removes) == null ? void 0 : _c.forEach(({ index: nestedIndex }) => rules == null ? void 0 : rules.push({ index: nestedIndex, type: StyleRuleType.Remove }));
4018
+ } else {
4019
+ const target = this.mirror.getNode(d.id);
4020
+ if (!target) {
4021
+ return this.debugNodeNotFound(d, d.id);
4022
+ }
4023
+ const styleSheet = target.sheet;
4024
+ (_d = d.adds) == null ? void 0 : _d.forEach(({ rule, index: nestedIndex }) => {
4025
+ try {
4026
+ if (Array.isArray(nestedIndex)) {
4027
+ const { positions, index } = getPositionsAndIndex(nestedIndex);
4028
+ const nestedRule = getNestedRule(styleSheet.cssRules, positions);
4029
+ nestedRule.insertRule(rule, index);
4030
+ } else {
4031
+ const index = nestedIndex === void 0 ? void 0 : Math.min(nestedIndex, styleSheet.cssRules.length);
4032
+ styleSheet.insertRule(rule, index);
4033
+ }
4034
+ } catch (e2) {
4035
+ }
4036
+ });
4037
+ (_e = d.removes) == null ? void 0 : _e.forEach(({ index: nestedIndex }) => {
4038
+ try {
4039
+ if (Array.isArray(nestedIndex)) {
4040
+ const { positions, index } = getPositionsAndIndex(nestedIndex);
4041
+ const nestedRule = getNestedRule(styleSheet.cssRules, positions);
4042
+ nestedRule.deleteRule(index || 0);
4043
+ } else {
4044
+ styleSheet == null ? void 0 : styleSheet.deleteRule(nestedIndex);
4045
+ }
4046
+ } catch (e2) {
4047
+ }
4048
+ });
4049
+ }
4050
+ break;
4051
+ }
4052
+ case IncrementalSource.StyleDeclaration: {
4053
+ if (this.usingVirtualDom) {
4054
+ const target = this.virtualDom.mirror.getNode(d.id);
4055
+ if (!target) {
4056
+ return this.debugNodeNotFound(d, d.id);
4057
+ }
4058
+ const rules = target.rules;
4059
+ d.set && rules.push(__spreadValues({
4060
+ type: StyleRuleType.SetProperty,
4061
+ index: d.index
4062
+ }, d.set));
4063
+ d.remove && rules.push(__spreadValues({
4064
+ type: StyleRuleType.RemoveProperty,
4065
+ index: d.index
4066
+ }, d.remove));
4067
+ } else {
4068
+ const target = this.mirror.getNode(d.id);
4069
+ if (!target) {
4070
+ return this.debugNodeNotFound(d, d.id);
4071
+ }
4072
+ const styleSheet = target.sheet;
4073
+ if (d.set) {
4074
+ const rule = getNestedRule(styleSheet.rules, d.index);
4075
+ rule.style.setProperty(d.set.property, d.set.value, d.set.priority);
4076
+ }
4077
+ if (d.remove) {
4078
+ const rule = getNestedRule(styleSheet.rules, d.index);
4079
+ rule.style.removeProperty(d.remove.property);
4080
+ }
4081
+ }
4082
+ break;
4083
+ }
4084
+ case IncrementalSource.CanvasMutation: {
4085
+ if (!this.config.UNSAFE_replayCanvas) {
4086
+ return;
4087
+ }
4088
+ if (this.usingVirtualDom) {
4089
+ const target = this.virtualDom.mirror.getNode(d.id);
4090
+ if (!target) {
4091
+ return this.debugNodeNotFound(d, d.id);
4092
+ }
4093
+ target.canvasMutations.push({
4094
+ event: e,
4095
+ mutation: d
4096
+ });
4097
+ } else {
4098
+ const target = this.mirror.getNode(d.id);
4099
+ if (!target) {
4100
+ return this.debugNodeNotFound(d, d.id);
4101
+ }
4102
+ canvasMutation({
4103
+ event: e,
4104
+ mutation: d,
4105
+ target,
4106
+ imageMap: this.imageMap,
4107
+ canvasEventMap: this.canvasEventMap,
4108
+ errorHandler: this.warnCanvasMutationFailed.bind(this)
4109
+ });
4110
+ }
4111
+ break;
4112
+ }
4113
+ case IncrementalSource.Font: {
4114
+ try {
4115
+ const fontFace = new FontFace(d.family, d.buffer ? new Uint8Array(JSON.parse(d.fontSource)) : d.fontSource, d.descriptors);
4116
+ (_f = this.iframe.contentDocument) == null ? void 0 : _f.fonts.add(fontFace);
4117
+ } catch (error) {
4118
+ if (this.config.showWarning) {
4119
+ console.warn(error);
4120
+ }
4121
+ }
4122
+ break;
4123
+ }
4124
+ }
4125
+ }
4126
+ applyMutation(d, isSync) {
4127
+ if (this.config.useVirtualDom && !this.usingVirtualDom && isSync) {
4128
+ this.usingVirtualDom = true;
4129
+ buildFromDom(this.iframe.contentDocument, this.mirror, this.virtualDom);
4130
+ if (Object.keys(this.legacy_missingNodeRetryMap).length) {
4131
+ for (const key in this.legacy_missingNodeRetryMap) {
4132
+ try {
4133
+ const value = this.legacy_missingNodeRetryMap[key];
4134
+ const virtualNode = buildFromNode(value.node, this.virtualDom, this.mirror);
4135
+ if (virtualNode)
4136
+ value.node = virtualNode;
4137
+ } catch (error) {
4138
+ if (this.config.showWarning) {
4139
+ console.warn(error);
4140
+ }
4141
+ }
4142
+ }
4143
+ }
4144
+ }
4145
+ const mirror = this.usingVirtualDom ? this.virtualDom.mirror : this.mirror;
4146
+ d.removes.forEach((mutation) => {
4147
+ var _a;
4148
+ const target = mirror.getNode(mutation.id);
4149
+ if (!target) {
4150
+ if (d.removes.find((r) => r.id === mutation.parentId)) {
4151
+ return;
4152
+ }
4153
+ return this.warnNodeNotFound(d, mutation.id);
4154
+ }
4155
+ let parent = mirror.getNode(mutation.parentId);
4156
+ if (!parent) {
4157
+ return this.warnNodeNotFound(d, mutation.parentId);
4158
+ }
4159
+ if (mutation.isShadow && hasShadowRoot(parent)) {
4160
+ parent = parent.shadowRoot;
4161
+ }
4162
+ mirror.removeNodeFromMap(target);
4163
+ if (parent)
4164
+ try {
4165
+ parent.removeChild(target);
4166
+ if (this.usingVirtualDom && target.nodeName === "#text" && parent.nodeName === "STYLE" && ((_a = parent.rules) == null ? void 0 : _a.length) > 0)
4167
+ parent.rules = [];
4168
+ } catch (error) {
4169
+ if (error instanceof DOMException) {
4170
+ this.warn("parent could not remove child in mutation", parent, target, d);
4171
+ } else {
4172
+ throw error;
4173
+ }
4174
+ }
4175
+ });
4176
+ const legacy_missingNodeMap = __spreadValues({}, this.legacy_missingNodeRetryMap);
4177
+ const queue = [];
4178
+ const nextNotInDOM = (mutation) => {
4179
+ let next = null;
4180
+ if (mutation.nextId) {
4181
+ next = mirror.getNode(mutation.nextId);
4182
+ }
4183
+ if (mutation.nextId !== null && mutation.nextId !== void 0 && mutation.nextId !== -1 && !next) {
4184
+ return true;
4185
+ }
4186
+ return false;
4187
+ };
4188
+ const appendNode = (mutation) => {
4189
+ var _a;
4190
+ if (!this.iframe.contentDocument) {
4191
+ return console.warn("Looks like your replayer has been destroyed.");
4192
+ }
4193
+ let parent = mirror.getNode(mutation.parentId);
4194
+ if (!parent) {
4195
+ if (mutation.node.type === NodeType$2.Document) {
4196
+ return this.newDocumentQueue.push(mutation);
4197
+ }
4198
+ return queue.push(mutation);
4199
+ }
4200
+ if (mutation.node.isShadow) {
4201
+ if (!hasShadowRoot(parent)) {
4202
+ parent.attachShadow({ mode: "open" });
4203
+ parent = parent.shadowRoot;
4204
+ } else
4205
+ parent = parent.shadowRoot;
4206
+ }
4207
+ let previous = null;
4208
+ let next = null;
4209
+ if (mutation.previousId) {
4210
+ previous = mirror.getNode(mutation.previousId);
4211
+ }
4212
+ if (mutation.nextId) {
4213
+ next = mirror.getNode(mutation.nextId);
4214
+ }
4215
+ if (nextNotInDOM(mutation)) {
4216
+ return queue.push(mutation);
4217
+ }
4218
+ if (mutation.node.rootId && !mirror.getNode(mutation.node.rootId)) {
4219
+ return;
4220
+ }
4221
+ const targetDoc = mutation.node.rootId ? mirror.getNode(mutation.node.rootId) : this.usingVirtualDom ? this.virtualDom : this.iframe.contentDocument;
4222
+ if (isSerializedIframe(parent, mirror)) {
4223
+ this.attachDocumentToIframe(mutation, parent);
4224
+ return;
4225
+ }
4226
+ const target = buildNodeWithSN(mutation.node, {
4227
+ doc: targetDoc,
4228
+ mirror,
4229
+ skipChild: true,
4230
+ hackCss: true,
4231
+ cache: this.cache
4232
+ });
4233
+ if (mutation.previousId === -1 || mutation.nextId === -1) {
4234
+ legacy_missingNodeMap[mutation.node.id] = {
4235
+ node: target,
4236
+ mutation
4237
+ };
4238
+ return;
4239
+ }
4240
+ const parentSn = mirror.getMeta(parent);
4241
+ if (parentSn && parentSn.type === NodeType$2.Element && parentSn.tagName === "textarea" && mutation.node.type === NodeType$2.Text) {
4242
+ const childNodeArray = Array.isArray(parent.childNodes) ? parent.childNodes : Array.from(parent.childNodes);
4243
+ for (const c of childNodeArray) {
4244
+ if (c.nodeType === parent.TEXT_NODE) {
4245
+ parent.removeChild(c);
4246
+ }
4247
+ }
4248
+ }
4249
+ if (previous && previous.nextSibling && previous.nextSibling.parentNode) {
4250
+ parent.insertBefore(target, previous.nextSibling);
4251
+ } else if (next && next.parentNode) {
4252
+ parent.contains(next) ? parent.insertBefore(target, next) : parent.insertBefore(target, null);
4253
+ } else {
4254
+ if (parent === targetDoc) {
4255
+ while (targetDoc.firstChild) {
4256
+ targetDoc.removeChild(targetDoc.firstChild);
4257
+ }
4258
+ }
4259
+ parent.appendChild(target);
4260
+ }
4261
+ if (this.usingVirtualDom && target.nodeName === "#text" && parent.nodeName === "STYLE" && ((_a = parent.rules) == null ? void 0 : _a.length) > 0)
4262
+ parent.rules = [];
4263
+ if (isSerializedIframe(target, this.mirror)) {
4264
+ const targetId = this.mirror.getId(target);
4265
+ const mutationInQueue = this.newDocumentQueue.find((m) => m.parentId === targetId);
4266
+ if (mutationInQueue) {
4267
+ this.attachDocumentToIframe(mutationInQueue, target);
4268
+ this.newDocumentQueue = this.newDocumentQueue.filter((m) => m !== mutationInQueue);
4269
+ }
4270
+ }
4271
+ if (mutation.previousId || mutation.nextId) {
4272
+ this.legacy_resolveMissingNode(legacy_missingNodeMap, parent, target, mutation);
4273
+ }
4274
+ };
4275
+ d.adds.forEach((mutation) => {
4276
+ appendNode(mutation);
4277
+ });
4278
+ const startTime = Date.now();
4279
+ while (queue.length) {
4280
+ const resolveTrees = queueToResolveTrees(queue);
4281
+ queue.length = 0;
4282
+ if (Date.now() - startTime > 500) {
4283
+ this.warn("Timeout in the loop, please check the resolve tree data:", resolveTrees);
4284
+ break;
4285
+ }
4286
+ for (const tree of resolveTrees) {
4287
+ const parent = mirror.getNode(tree.value.parentId);
4288
+ if (!parent) {
4289
+ this.debug("Drop resolve tree since there is no parent for the root node.", tree);
4290
+ } else {
4291
+ iterateResolveTree(tree, (mutation) => {
4292
+ appendNode(mutation);
4293
+ });
4294
+ }
4295
+ }
4296
+ }
4297
+ if (Object.keys(legacy_missingNodeMap).length) {
4298
+ Object.assign(this.legacy_missingNodeRetryMap, legacy_missingNodeMap);
4299
+ }
4300
+ uniqueTextMutations(d.texts).forEach((mutation) => {
4301
+ var _a;
4302
+ const target = mirror.getNode(mutation.id);
4303
+ if (!target) {
4304
+ if (d.removes.find((r) => r.id === mutation.id)) {
4305
+ return;
4306
+ }
4307
+ return this.warnNodeNotFound(d, mutation.id);
4308
+ }
4309
+ target.textContent = mutation.value;
4310
+ if (this.usingVirtualDom) {
4311
+ const parent = target.parentNode;
4312
+ if (((_a = parent == null ? void 0 : parent.rules) == null ? void 0 : _a.length) > 0)
4313
+ parent.rules = [];
4314
+ }
4315
+ });
4316
+ d.attributes.forEach((mutation) => {
4317
+ const target = mirror.getNode(mutation.id);
4318
+ if (!target) {
4319
+ if (d.removes.find((r) => r.id === mutation.id)) {
4320
+ return;
4321
+ }
4322
+ return this.warnNodeNotFound(d, mutation.id);
4323
+ }
4324
+ for (const attributeName in mutation.attributes) {
4325
+ if (typeof attributeName === "string") {
4326
+ const value = mutation.attributes[attributeName];
4327
+ if (value === null) {
4328
+ target.removeAttribute(attributeName);
4329
+ } else if (typeof value === "string") {
4330
+ try {
4331
+ target.setAttribute(attributeName, value);
4332
+ } catch (error) {
4333
+ if (this.config.showWarning) {
4334
+ console.warn("An error occurred may due to the checkout feature.", error);
4335
+ }
4336
+ }
4337
+ } else if (attributeName === "style") {
4338
+ const styleValues = value;
4339
+ const targetEl = target;
4340
+ for (const s in styleValues) {
4341
+ if (styleValues[s] === false) {
4342
+ targetEl.style.removeProperty(s);
4343
+ } else if (styleValues[s] instanceof Array) {
4344
+ const svp = styleValues[s];
4345
+ targetEl.style.setProperty(s, svp[0], svp[1]);
4346
+ } else {
4347
+ const svs = styleValues[s];
4348
+ targetEl.style.setProperty(s, svs);
4349
+ }
4350
+ }
4351
+ }
4352
+ }
4353
+ }
4354
+ });
4355
+ }
4356
+ applyScroll(d, isSync) {
4357
+ const target = this.mirror.getNode(d.id);
4358
+ if (!target) {
4359
+ return this.debugNodeNotFound(d, d.id);
4360
+ }
4361
+ const sn = this.mirror.getMeta(target);
4362
+ if (target === this.iframe.contentDocument) {
4363
+ this.iframe.contentWindow.scrollTo({
4364
+ top: d.y,
4365
+ left: d.x,
4366
+ behavior: isSync ? "auto" : "smooth"
4367
+ });
4368
+ } else if ((sn == null ? void 0 : sn.type) === NodeType$2.Document) {
4369
+ target.defaultView.scrollTo({
4370
+ top: d.y,
4371
+ left: d.x,
4372
+ behavior: isSync ? "auto" : "smooth"
4373
+ });
4374
+ } else {
4375
+ try {
4376
+ target.scrollTop = d.y;
4377
+ target.scrollLeft = d.x;
4378
+ } catch (error) {
4379
+ }
4380
+ }
4381
+ }
4382
+ applyInput(d) {
4383
+ const target = this.mirror.getNode(d.id);
4384
+ if (!target) {
4385
+ return this.debugNodeNotFound(d, d.id);
4386
+ }
4387
+ try {
4388
+ target.checked = d.isChecked;
4389
+ target.value = d.text;
4390
+ } catch (error) {
4391
+ }
4392
+ }
4393
+ legacy_resolveMissingNode(map, parent, target, targetMutation) {
4394
+ const { previousId, nextId } = targetMutation;
4395
+ const previousInMap = previousId && map[previousId];
4396
+ const nextInMap = nextId && map[nextId];
4397
+ if (previousInMap) {
4398
+ const { node, mutation } = previousInMap;
4399
+ parent.insertBefore(node, target);
4400
+ delete map[mutation.node.id];
4401
+ delete this.legacy_missingNodeRetryMap[mutation.node.id];
4402
+ if (mutation.previousId || mutation.nextId) {
4403
+ this.legacy_resolveMissingNode(map, parent, node, mutation);
4404
+ }
4405
+ }
4406
+ if (nextInMap) {
4407
+ const { node, mutation } = nextInMap;
4408
+ parent.insertBefore(node, target.nextSibling);
4409
+ delete map[mutation.node.id];
4410
+ delete this.legacy_missingNodeRetryMap[mutation.node.id];
4411
+ if (mutation.previousId || mutation.nextId) {
4412
+ this.legacy_resolveMissingNode(map, parent, node, mutation);
4413
+ }
4414
+ }
4415
+ }
4416
+ moveAndHover(x, y, id, isSync, debugData) {
4417
+ const target = this.mirror.getNode(id);
4418
+ if (!target) {
4419
+ return this.debugNodeNotFound(debugData, id);
4420
+ }
4421
+ const base = getBaseDimension(target, this.iframe);
4422
+ const _x = x * base.absoluteScale + base.x;
4423
+ const _y = y * base.absoluteScale + base.y;
4424
+ this.mouse.style.left = `${_x}px`;
4425
+ this.mouse.style.top = `${_y}px`;
4426
+ if (!isSync) {
4427
+ this.drawMouseTail({ x: _x, y: _y });
4428
+ }
4429
+ this.hoverElements(target);
4430
+ }
4431
+ drawMouseTail(position) {
4432
+ if (!this.mouseTail) {
4433
+ return;
4434
+ }
4435
+ const { lineCap, lineWidth, strokeStyle, duration } = this.config.mouseTail === true ? defaultMouseTailConfig : Object.assign({}, defaultMouseTailConfig, this.config.mouseTail);
4436
+ const draw = () => {
4437
+ if (!this.mouseTail) {
4438
+ return;
4439
+ }
4440
+ const ctx = this.mouseTail.getContext("2d");
4441
+ if (!ctx || !this.tailPositions.length) {
4442
+ return;
4443
+ }
4444
+ ctx.clearRect(0, 0, this.mouseTail.width, this.mouseTail.height);
4445
+ ctx.beginPath();
4446
+ ctx.lineWidth = lineWidth;
4447
+ ctx.lineCap = lineCap;
4448
+ ctx.strokeStyle = strokeStyle;
4449
+ ctx.moveTo(this.tailPositions[0].x, this.tailPositions[0].y);
4450
+ this.tailPositions.forEach((p) => ctx.lineTo(p.x, p.y));
4451
+ ctx.stroke();
4452
+ };
4453
+ this.tailPositions.push(position);
4454
+ draw();
4455
+ setTimeout(() => {
4456
+ this.tailPositions = this.tailPositions.filter((p) => p !== position);
4457
+ draw();
4458
+ }, duration / this.speedService.state.context.timer.speed);
4459
+ }
4460
+ hoverElements(el) {
4461
+ var _a;
4462
+ (_a = this.iframe.contentDocument) == null ? void 0 : _a.querySelectorAll(".\\:hover").forEach((hoveredEl) => {
4463
+ hoveredEl.classList.remove(":hover");
4464
+ });
4465
+ let currentEl = el;
4466
+ while (currentEl) {
4467
+ if (currentEl.classList) {
4468
+ currentEl.classList.add(":hover");
4469
+ }
4470
+ currentEl = currentEl.parentElement;
4471
+ }
4472
+ }
4473
+ isUserInteraction(event) {
4474
+ if (event.type !== EventType.IncrementalSnapshot) {
4475
+ return false;
4476
+ }
4477
+ return event.data.source > IncrementalSource.Mutation && event.data.source <= IncrementalSource.Input;
4478
+ }
4479
+ backToNormal() {
4480
+ this.nextUserInteractionEvent = null;
4481
+ if (this.speedService.state.matches("normal")) {
4482
+ return;
4483
+ }
4484
+ this.speedService.send({ type: "BACK_TO_NORMAL" });
4485
+ this.emitter.emit(ReplayerEvents.SkipEnd, {
4486
+ speed: this.speedService.state.context.normalSpeed
4487
+ });
4488
+ }
4489
+ warnNodeNotFound(d, id) {
4490
+ this.warn(`Node with id '${id}' not found. `, d);
4491
+ }
4492
+ warnCanvasMutationFailed(d, error) {
4493
+ this.warn(`Has error on canvas update`, error, "canvas mutation:", d);
4494
+ }
4495
+ debugNodeNotFound(d, id) {
4496
+ this.debug(REPLAY_CONSOLE_PREFIX, `Node with id '${id}' not found. `, d);
4497
+ }
4498
+ warn(...args) {
4499
+ if (!this.config.showWarning) {
4500
+ return;
4501
+ }
4502
+ console.warn(REPLAY_CONSOLE_PREFIX, ...args);
4503
+ }
4504
+ debug(...args) {
4505
+ if (!this.config.showDebug) {
4506
+ return;
4507
+ }
4508
+ console.log(REPLAY_CONSOLE_PREFIX, ...args);
4509
+ }
4510
+ }
4511
+
4512
+ // DEFLATE is a complex format; to read this code, you should probably check the RFC first:
4513
+
4514
+ // aliases for shorter compressed code (most minifers don't do this)
4515
+ var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;
4516
+ // fixed length extra bits
4517
+ var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
4518
+ // fixed distance extra bits
4519
+ // see fleb note
4520
+ var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
4521
+ // code length index map
4522
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
4523
+ // get base, reverse index map from extra bits
4524
+ var freb = function (eb, start) {
4525
+ var b = new u16(31);
4526
+ for (var i = 0; i < 31; ++i) {
4527
+ b[i] = start += 1 << eb[i - 1];
4528
+ }
4529
+ // numbers here are at max 18 bits
4530
+ var r = new u32(b[30]);
4531
+ for (var i = 1; i < 30; ++i) {
4532
+ for (var j = b[i]; j < b[i + 1]; ++j) {
4533
+ r[j] = ((j - b[i]) << 5) | i;
4534
+ }
4535
+ }
4536
+ return [b, r];
4537
+ };
4538
+ var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];
4539
+ // we can ignore the fact that the other numbers are wrong; they never happen anyway
4540
+ fl[28] = 258, revfl[258] = 28;
4541
+ var _b = freb(fdeb, 0), fd = _b[0];
4542
+ // map of value to reverse (assuming 16 bits)
4543
+ var rev = new u16(32768);
4544
+ for (var i = 0; i < 32768; ++i) {
4545
+ // reverse table algorithm from SO
4546
+ var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);
4547
+ x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);
4548
+ x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);
4549
+ rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;
4550
+ }
4551
+ // create huffman tree from u8 "map": index -> code length for code index
4552
+ // mb (max bits) must be at most 15
4553
+ // TODO: optimize/split up?
4554
+ var hMap = (function (cd, mb, r) {
4555
+ var s = cd.length;
4556
+ // index
4557
+ var i = 0;
4558
+ // u16 "map": index -> # of codes with bit length = index
4559
+ var l = new u16(mb);
4560
+ // length of cd must be 288 (total # of codes)
4561
+ for (; i < s; ++i)
4562
+ ++l[cd[i] - 1];
4563
+ // u16 "map": index -> minimum code for bit length = index
4564
+ var le = new u16(mb);
4565
+ for (i = 0; i < mb; ++i) {
4566
+ le[i] = (le[i - 1] + l[i - 1]) << 1;
4567
+ }
4568
+ var co;
4569
+ if (r) {
4570
+ // u16 "map": index -> number of actual bits, symbol for code
4571
+ co = new u16(1 << mb);
4572
+ // bits to remove for reverser
4573
+ var rvb = 15 - mb;
4574
+ for (i = 0; i < s; ++i) {
4575
+ // ignore 0 lengths
4576
+ if (cd[i]) {
4577
+ // num encoding both symbol and bits read
4578
+ var sv = (i << 4) | cd[i];
4579
+ // free bits
4580
+ var r_1 = mb - cd[i];
4581
+ // start value
4582
+ var v = le[cd[i] - 1]++ << r_1;
4583
+ // m is end value
4584
+ for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
4585
+ // every 16 bit value starting with the code yields the same result
4586
+ co[rev[v] >>> rvb] = sv;
4587
+ }
4588
+ }
4589
+ }
4590
+ }
4591
+ else {
4592
+ co = new u16(s);
4593
+ for (i = 0; i < s; ++i)
4594
+ co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);
4595
+ }
4596
+ return co;
4597
+ });
4598
+ // fixed length tree
4599
+ var flt = new u8(288);
4600
+ for (var i = 0; i < 144; ++i)
4601
+ flt[i] = 8;
4602
+ for (var i = 144; i < 256; ++i)
4603
+ flt[i] = 9;
4604
+ for (var i = 256; i < 280; ++i)
4605
+ flt[i] = 7;
4606
+ for (var i = 280; i < 288; ++i)
4607
+ flt[i] = 8;
4608
+ // fixed distance tree
4609
+ var fdt = new u8(32);
4610
+ for (var i = 0; i < 32; ++i)
4611
+ fdt[i] = 5;
4612
+ // fixed length map
4613
+ var flrm = /*#__PURE__*/ hMap(flt, 9, 1);
4614
+ // fixed distance map
4615
+ var fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
4616
+ // find max of array
4617
+ var max = function (a) {
4618
+ var m = a[0];
4619
+ for (var i = 1; i < a.length; ++i) {
4620
+ if (a[i] > m)
4621
+ m = a[i];
4622
+ }
4623
+ return m;
4624
+ };
4625
+ // read d, starting at bit p and mask with m
4626
+ var bits = function (d, p, m) {
4627
+ var o = (p / 8) >> 0;
4628
+ return ((d[o] | (d[o + 1] << 8)) >>> (p & 7)) & m;
4629
+ };
4630
+ // read d, starting at bit p continuing for at least 16 bits
4631
+ var bits16 = function (d, p) {
4632
+ var o = (p / 8) >> 0;
4633
+ return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >>> (p & 7));
4634
+ };
4635
+ // get end of byte
4636
+ var shft = function (p) { return ((p / 8) >> 0) + (p & 7 && 1); };
4637
+ // typed array slice - allows garbage collector to free original reference,
4638
+ // while being more compatible than .slice
4639
+ var slc = function (v, s, e) {
4640
+ if (s == null || s < 0)
4641
+ s = 0;
4642
+ if (e == null || e > v.length)
4643
+ e = v.length;
4644
+ // can't use .constructor in case user-supplied
4645
+ var n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s);
4646
+ n.set(v.subarray(s, e));
4647
+ return n;
4648
+ };
4649
+ // expands raw DEFLATE data
4650
+ var inflt = function (dat, buf, st) {
4651
+ // source length
4652
+ var sl = dat.length;
4653
+ // have to estimate size
4654
+ var noBuf = !buf || st;
4655
+ // no state
4656
+ var noSt = !st || st.i;
4657
+ if (!st)
4658
+ st = {};
4659
+ // Assumes roughly 33% compression ratio average
4660
+ if (!buf)
4661
+ buf = new u8(sl * 3);
4662
+ // ensure buffer can fit at least l elements
4663
+ var cbuf = function (l) {
4664
+ var bl = buf.length;
4665
+ // need to increase size to fit
4666
+ if (l > bl) {
4667
+ // Double or set to necessary, whichever is greater
4668
+ var nbuf = new u8(Math.max(bl * 2, l));
4669
+ nbuf.set(buf);
4670
+ buf = nbuf;
4671
+ }
4672
+ };
4673
+ // last chunk bitpos bytes
4674
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
4675
+ // total bits
4676
+ var tbts = sl * 8;
4677
+ do {
4678
+ if (!lm) {
4679
+ // BFINAL - this is only 1 when last chunk is next
4680
+ st.f = final = bits(dat, pos, 1);
4681
+ // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
4682
+ var type = bits(dat, pos + 1, 3);
4683
+ pos += 3;
4684
+ if (!type) {
4685
+ // go to end of byte boundary
4686
+ var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
4687
+ if (t > sl) {
4688
+ if (noSt)
4689
+ throw 'unexpected EOF';
4690
+ break;
4691
+ }
4692
+ // ensure size
4693
+ if (noBuf)
4694
+ cbuf(bt + l);
4695
+ // Copy over uncompressed data
4696
+ buf.set(dat.subarray(s, t), bt);
4697
+ // Get new bitpos, update byte count
4698
+ st.b = bt += l, st.p = pos = t * 8;
4699
+ continue;
4700
+ }
4701
+ else if (type == 1)
4702
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
4703
+ else if (type == 2) {
4704
+ // literal lengths
4705
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
4706
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
4707
+ pos += 14;
4708
+ // length+distance tree
4709
+ var ldt = new u8(tl);
4710
+ // code length tree
4711
+ var clt = new u8(19);
4712
+ for (var i = 0; i < hcLen; ++i) {
4713
+ // use index map to get real code
4714
+ clt[clim[i]] = bits(dat, pos + i * 3, 7);
4715
+ }
4716
+ pos += hcLen * 3;
4717
+ // code lengths bits
4718
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
4719
+ if (!noSt && pos + tl * (clb + 7) > tbts)
4720
+ break;
4721
+ // code lengths map
4722
+ var clm = hMap(clt, clb, 1);
4723
+ for (var i = 0; i < tl;) {
4724
+ var r = clm[bits(dat, pos, clbmsk)];
4725
+ // bits read
4726
+ pos += r & 15;
4727
+ // symbol
4728
+ var s = r >>> 4;
4729
+ // code length to copy
4730
+ if (s < 16) {
4731
+ ldt[i++] = s;
4732
+ }
4733
+ else {
4734
+ // copy count
4735
+ var c = 0, n = 0;
4736
+ if (s == 16)
4737
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
4738
+ else if (s == 17)
4739
+ n = 3 + bits(dat, pos, 7), pos += 3;
4740
+ else if (s == 18)
4741
+ n = 11 + bits(dat, pos, 127), pos += 7;
4742
+ while (n--)
4743
+ ldt[i++] = c;
4744
+ }
4745
+ }
4746
+ // length tree distance tree
4747
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
4748
+ // max length bits
4749
+ lbt = max(lt);
4750
+ // max dist bits
4751
+ dbt = max(dt);
4752
+ lm = hMap(lt, lbt, 1);
4753
+ dm = hMap(dt, dbt, 1);
4754
+ }
4755
+ else
4756
+ throw 'invalid block type';
4757
+ if (pos > tbts)
4758
+ throw 'unexpected EOF';
4759
+ }
4760
+ // Make sure the buffer can hold this + the largest possible addition
4761
+ // Maximum chunk size (practically, theoretically infinite) is 2^17;
4762
+ if (noBuf)
4763
+ cbuf(bt + 131072);
4764
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
4765
+ var mxa = lbt + dbt + 18;
4766
+ while (noSt || pos + mxa < tbts) {
4767
+ // bits read, code
4768
+ var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;
4769
+ pos += c & 15;
4770
+ if (pos > tbts)
4771
+ throw 'unexpected EOF';
4772
+ if (!c)
4773
+ throw 'invalid length/literal';
4774
+ if (sym < 256)
4775
+ buf[bt++] = sym;
4776
+ else if (sym == 256) {
4777
+ lm = null;
4778
+ break;
4779
+ }
4780
+ else {
4781
+ var add = sym - 254;
4782
+ // no extra bits needed if less
4783
+ if (sym > 264) {
4784
+ // index
4785
+ var i = sym - 257, b = fleb[i];
4786
+ add = bits(dat, pos, (1 << b) - 1) + fl[i];
4787
+ pos += b;
4788
+ }
4789
+ // dist
4790
+ var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;
4791
+ if (!d)
4792
+ throw 'invalid distance';
4793
+ pos += d & 15;
4794
+ var dt = fd[dsym];
4795
+ if (dsym > 3) {
4796
+ var b = fdeb[dsym];
4797
+ dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;
4798
+ }
4799
+ if (pos > tbts)
4800
+ throw 'unexpected EOF';
4801
+ if (noBuf)
4802
+ cbuf(bt + 131072);
4803
+ var end = bt + add;
4804
+ for (; bt < end; bt += 4) {
4805
+ buf[bt] = buf[bt - dt];
4806
+ buf[bt + 1] = buf[bt + 1 - dt];
4807
+ buf[bt + 2] = buf[bt + 2 - dt];
4808
+ buf[bt + 3] = buf[bt + 3 - dt];
4809
+ }
4810
+ bt = end;
4811
+ }
4812
+ }
4813
+ st.l = lm, st.p = pos, st.b = bt;
4814
+ if (lm)
4815
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
4816
+ } while (!final);
4817
+ return bt == buf.length ? buf : slc(buf, 0, bt);
4818
+ };
4819
+ // zlib valid
4820
+ var zlv = function (d) {
4821
+ if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
4822
+ throw 'invalid zlib data';
4823
+ if (d[1] & 32)
4824
+ throw 'invalid zlib data: preset dictionaries not supported';
4825
+ };
4826
+ /**
4827
+ * Expands Zlib data
4828
+ * @param data The data to decompress
4829
+ * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
4830
+ * @returns The decompressed version of the data
4831
+ */
4832
+ function unzlibSync(data, out) {
4833
+ return inflt((zlv(data), data.subarray(2, -4)), out);
4834
+ }
4835
+ /**
4836
+ * Converts a string into a Uint8Array for use with compression/decompression methods
4837
+ * @param str The string to encode
4838
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
4839
+ * not need to be true unless decoding a binary string.
4840
+ * @returns The string encoded in UTF-8/Latin-1 binary
4841
+ */
4842
+ function strToU8(str, latin1) {
4843
+ var l = str.length;
4844
+ if (!latin1 && typeof TextEncoder != 'undefined')
4845
+ return new TextEncoder().encode(str);
4846
+ var ar = new u8(str.length + (str.length >>> 1));
4847
+ var ai = 0;
4848
+ var w = function (v) { ar[ai++] = v; };
4849
+ for (var i = 0; i < l; ++i) {
4850
+ if (ai + 5 > ar.length) {
4851
+ var n = new u8(ai + 8 + ((l - i) << 1));
4852
+ n.set(ar);
4853
+ ar = n;
4854
+ }
4855
+ var c = str.charCodeAt(i);
4856
+ if (c < 128 || latin1)
4857
+ w(c);
4858
+ else if (c < 2048)
4859
+ w(192 | (c >>> 6)), w(128 | (c & 63));
4860
+ else if (c > 55295 && c < 57344)
4861
+ c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),
4862
+ w(240 | (c >>> 18)), w(128 | ((c >>> 12) & 63)), w(128 | ((c >>> 6) & 63)), w(128 | (c & 63));
4863
+ else
4864
+ w(224 | (c >>> 12)), w(128 | ((c >>> 6) & 63)), w(128 | (c & 63));
4865
+ }
4866
+ return slc(ar, 0, ai);
4867
+ }
4868
+ /**
4869
+ * Converts a Uint8Array to a string
4870
+ * @param dat The data to decode to string
4871
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
4872
+ * not need to be true unless encoding to binary string.
4873
+ * @returns The original UTF-8/Latin-1 string
4874
+ */
4875
+ function strFromU8(dat, latin1) {
4876
+ var r = '';
4877
+ if (!latin1 && typeof TextDecoder != 'undefined')
4878
+ return new TextDecoder().decode(dat);
4879
+ for (var i = 0; i < dat.length;) {
4880
+ var c = dat[i++];
4881
+ if (c < 128 || latin1)
4882
+ r += String.fromCharCode(c);
4883
+ else if (c < 224)
4884
+ r += String.fromCharCode((c & 31) << 6 | (dat[i++] & 63));
4885
+ else if (c < 240)
4886
+ r += String.fromCharCode((c & 15) << 12 | (dat[i++] & 63) << 6 | (dat[i++] & 63));
4887
+ else
4888
+ c = ((c & 15) << 18 | (dat[i++] & 63) << 12 | (dat[i++] & 63) << 6 | (dat[i++] & 63)) - 65536,
4889
+ r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));
4890
+ }
4891
+ return r;
4892
+ }
4893
+
4894
+ const MARK = "v1";
4895
+
4896
+ const unpack = (raw) => {
4897
+ if (typeof raw !== "string") {
4898
+ return raw;
4899
+ }
4900
+ try {
4901
+ const e = JSON.parse(raw);
4902
+ if (e.timestamp) {
4903
+ return e;
4904
+ }
4905
+ } catch (error) {
4906
+ }
4907
+ try {
4908
+ const e = JSON.parse(strFromU8(unzlibSync(strToU8(raw, true))));
4909
+ if (e.v === MARK) {
4910
+ return e;
4911
+ }
4912
+ throw new Error(`These events were packed with packer ${e.v} which is incompatible with current packer ${MARK}.`);
4913
+ } catch (error) {
4914
+ console.error(error);
4915
+ throw new Error("Unknown data format.");
4916
+ }
4917
+ };
4918
+
4919
+ exports.Replayer = Replayer;
4920
+ exports.unpack = unpack;
4921
+
4922
+ Object.defineProperty(exports, '__esModule', { value: true });
4923
+
4924
+ return exports;
4925
+
4926
+ })({});