@checkflow/sdk 1.0.6 → 1.0.7

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.
package/dist/index.js CHANGED
@@ -2718,77 +2718,4074 @@ class FeedbackWidget {
2718
2718
  }
2719
2719
  }
2720
2720
 
2721
+ var NodeType;
2722
+ (function (NodeType) {
2723
+ NodeType[NodeType["Document"] = 0] = "Document";
2724
+ NodeType[NodeType["DocumentType"] = 1] = "DocumentType";
2725
+ NodeType[NodeType["Element"] = 2] = "Element";
2726
+ NodeType[NodeType["Text"] = 3] = "Text";
2727
+ NodeType[NodeType["CDATA"] = 4] = "CDATA";
2728
+ NodeType[NodeType["Comment"] = 5] = "Comment";
2729
+ })(NodeType || (NodeType = {}));
2730
+
2731
+ function isElement(n) {
2732
+ return n.nodeType === n.ELEMENT_NODE;
2733
+ }
2734
+ function isShadowRoot(n) {
2735
+ var host = n === null || n === void 0 ? void 0 : n.host;
2736
+ return Boolean((host === null || host === void 0 ? void 0 : host.shadowRoot) === n);
2737
+ }
2738
+ function isNativeShadowDom(shadowRoot) {
2739
+ return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';
2740
+ }
2741
+ function fixBrowserCompatibilityIssuesInCSS(cssText) {
2742
+ if (cssText.includes(' background-clip: text;') &&
2743
+ !cssText.includes(' -webkit-background-clip: text;')) {
2744
+ cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');
2745
+ }
2746
+ return cssText;
2747
+ }
2748
+ function getCssRulesString(s) {
2749
+ try {
2750
+ var rules = s.rules || s.cssRules;
2751
+ return rules
2752
+ ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules).map(getCssRuleString).join(''))
2753
+ : null;
2754
+ }
2755
+ catch (error) {
2756
+ return null;
2757
+ }
2758
+ }
2759
+ function getCssRuleString(rule) {
2760
+ var cssStringified = rule.cssText;
2761
+ if (isCSSImportRule(rule)) {
2762
+ try {
2763
+ cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;
2764
+ }
2765
+ catch (_a) {
2766
+ }
2767
+ }
2768
+ return cssStringified;
2769
+ }
2770
+ function isCSSImportRule(rule) {
2771
+ return 'styleSheet' in rule;
2772
+ }
2773
+ var Mirror = (function () {
2774
+ function Mirror() {
2775
+ this.idNodeMap = new Map();
2776
+ this.nodeMetaMap = new WeakMap();
2777
+ }
2778
+ Mirror.prototype.getId = function (n) {
2779
+ var _a;
2780
+ if (!n)
2781
+ return -1;
2782
+ var id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;
2783
+ return id !== null && id !== void 0 ? id : -1;
2784
+ };
2785
+ Mirror.prototype.getNode = function (id) {
2786
+ return this.idNodeMap.get(id) || null;
2787
+ };
2788
+ Mirror.prototype.getIds = function () {
2789
+ return Array.from(this.idNodeMap.keys());
2790
+ };
2791
+ Mirror.prototype.getMeta = function (n) {
2792
+ return this.nodeMetaMap.get(n) || null;
2793
+ };
2794
+ Mirror.prototype.removeNodeFromMap = function (n) {
2795
+ var _this = this;
2796
+ var id = this.getId(n);
2797
+ this.idNodeMap["delete"](id);
2798
+ if (n.childNodes) {
2799
+ n.childNodes.forEach(function (childNode) {
2800
+ return _this.removeNodeFromMap(childNode);
2801
+ });
2802
+ }
2803
+ };
2804
+ Mirror.prototype.has = function (id) {
2805
+ return this.idNodeMap.has(id);
2806
+ };
2807
+ Mirror.prototype.hasNode = function (node) {
2808
+ return this.nodeMetaMap.has(node);
2809
+ };
2810
+ Mirror.prototype.add = function (n, meta) {
2811
+ var id = meta.id;
2812
+ this.idNodeMap.set(id, n);
2813
+ this.nodeMetaMap.set(n, meta);
2814
+ };
2815
+ Mirror.prototype.replace = function (id, n) {
2816
+ var oldNode = this.getNode(id);
2817
+ if (oldNode) {
2818
+ var meta = this.nodeMetaMap.get(oldNode);
2819
+ if (meta)
2820
+ this.nodeMetaMap.set(n, meta);
2821
+ }
2822
+ this.idNodeMap.set(id, n);
2823
+ };
2824
+ Mirror.prototype.reset = function () {
2825
+ this.idNodeMap = new Map();
2826
+ this.nodeMetaMap = new WeakMap();
2827
+ };
2828
+ return Mirror;
2829
+ }());
2830
+ function createMirror() {
2831
+ return new Mirror();
2832
+ }
2833
+ function maskInputValue(_a) {
2834
+ var maskInputOptions = _a.maskInputOptions, tagName = _a.tagName, type = _a.type, value = _a.value, maskInputFn = _a.maskInputFn;
2835
+ var text = value || '';
2836
+ if (maskInputOptions[tagName.toLowerCase()] ||
2837
+ maskInputOptions[type]) {
2838
+ if (maskInputFn) {
2839
+ text = maskInputFn(text);
2840
+ }
2841
+ else {
2842
+ text = '*'.repeat(text.length);
2843
+ }
2844
+ }
2845
+ return text;
2846
+ }
2847
+ var ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';
2848
+ function is2DCanvasBlank(canvas) {
2849
+ var ctx = canvas.getContext('2d');
2850
+ if (!ctx)
2851
+ return true;
2852
+ var chunkSize = 50;
2853
+ for (var x = 0; x < canvas.width; x += chunkSize) {
2854
+ for (var y = 0; y < canvas.height; y += chunkSize) {
2855
+ var getImageData = ctx.getImageData;
2856
+ var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData
2857
+ ? getImageData[ORIGINAL_ATTRIBUTE_NAME]
2858
+ : getImageData;
2859
+ var pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);
2860
+ if (pixelBuffer.some(function (pixel) { return pixel !== 0; }))
2861
+ return false;
2862
+ }
2863
+ }
2864
+ return true;
2865
+ }
2866
+
2867
+ var _id = 1;
2868
+ var tagNameRegex = new RegExp('[^a-z0-9-_:]');
2869
+ var IGNORED_NODE = -2;
2870
+ function genId() {
2871
+ return _id++;
2872
+ }
2873
+ function getValidTagName(element) {
2874
+ if (element instanceof HTMLFormElement) {
2875
+ return 'form';
2876
+ }
2877
+ var processedTagName = element.tagName.toLowerCase().trim();
2878
+ if (tagNameRegex.test(processedTagName)) {
2879
+ return 'div';
2880
+ }
2881
+ return processedTagName;
2882
+ }
2883
+ function stringifyStyleSheet(sheet) {
2884
+ return sheet.cssRules
2885
+ ? Array.from(sheet.cssRules)
2886
+ .map(function (rule) { return rule.cssText || ''; })
2887
+ .join('')
2888
+ : '';
2889
+ }
2890
+ function extractOrigin(url) {
2891
+ var origin = '';
2892
+ if (url.indexOf('//') > -1) {
2893
+ origin = url.split('/').slice(0, 3).join('/');
2894
+ }
2895
+ else {
2896
+ origin = url.split('/')[0];
2897
+ }
2898
+ origin = origin.split('?')[0];
2899
+ return origin;
2900
+ }
2901
+ var canvasService;
2902
+ var canvasCtx;
2903
+ var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
2904
+ var RELATIVE_PATH = /^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/;
2905
+ var DATA_URI = /^(data:)([^,]*),(.*)/i;
2906
+ function absoluteToStylesheet(cssText, href) {
2907
+ return (cssText || '').replace(URL_IN_CSS_REF, function (origin, quote1, path1, quote2, path2, path3) {
2908
+ var filePath = path1 || path2 || path3;
2909
+ var maybeQuote = quote1 || quote2 || '';
2910
+ if (!filePath) {
2911
+ return origin;
2912
+ }
2913
+ if (!RELATIVE_PATH.test(filePath)) {
2914
+ return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
2915
+ }
2916
+ if (DATA_URI.test(filePath)) {
2917
+ return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
2918
+ }
2919
+ if (filePath[0] === '/') {
2920
+ return "url(".concat(maybeQuote).concat(extractOrigin(href) + filePath).concat(maybeQuote, ")");
2921
+ }
2922
+ var stack = href.split('/');
2923
+ var parts = filePath.split('/');
2924
+ stack.pop();
2925
+ for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
2926
+ var part = parts_1[_i];
2927
+ if (part === '.') {
2928
+ continue;
2929
+ }
2930
+ else if (part === '..') {
2931
+ stack.pop();
2932
+ }
2933
+ else {
2934
+ stack.push(part);
2935
+ }
2936
+ }
2937
+ return "url(".concat(maybeQuote).concat(stack.join('/')).concat(maybeQuote, ")");
2938
+ });
2939
+ }
2940
+ var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
2941
+ var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
2942
+ function getAbsoluteSrcsetString(doc, attributeValue) {
2943
+ if (attributeValue.trim() === '') {
2944
+ return attributeValue;
2945
+ }
2946
+ var pos = 0;
2947
+ function collectCharacters(regEx) {
2948
+ var chars;
2949
+ var match = regEx.exec(attributeValue.substring(pos));
2950
+ if (match) {
2951
+ chars = match[0];
2952
+ pos += chars.length;
2953
+ return chars;
2954
+ }
2955
+ return '';
2956
+ }
2957
+ var output = [];
2958
+ while (true) {
2959
+ collectCharacters(SRCSET_COMMAS_OR_SPACES);
2960
+ if (pos >= attributeValue.length) {
2961
+ break;
2962
+ }
2963
+ var url = collectCharacters(SRCSET_NOT_SPACES);
2964
+ if (url.slice(-1) === ',') {
2965
+ url = absoluteToDoc(doc, url.substring(0, url.length - 1));
2966
+ output.push(url);
2967
+ }
2968
+ else {
2969
+ var descriptorsStr = '';
2970
+ url = absoluteToDoc(doc, url);
2971
+ var inParens = false;
2972
+ while (true) {
2973
+ var c = attributeValue.charAt(pos);
2974
+ if (c === '') {
2975
+ output.push((url + descriptorsStr).trim());
2976
+ break;
2977
+ }
2978
+ else if (!inParens) {
2979
+ if (c === ',') {
2980
+ pos += 1;
2981
+ output.push((url + descriptorsStr).trim());
2982
+ break;
2983
+ }
2984
+ else if (c === '(') {
2985
+ inParens = true;
2986
+ }
2987
+ }
2988
+ else {
2989
+ if (c === ')') {
2990
+ inParens = false;
2991
+ }
2992
+ }
2993
+ descriptorsStr += c;
2994
+ pos += 1;
2995
+ }
2996
+ }
2997
+ }
2998
+ return output.join(', ');
2999
+ }
3000
+ function absoluteToDoc(doc, attributeValue) {
3001
+ if (!attributeValue || attributeValue.trim() === '') {
3002
+ return attributeValue;
3003
+ }
3004
+ var a = doc.createElement('a');
3005
+ a.href = attributeValue;
3006
+ return a.href;
3007
+ }
3008
+ function isSVGElement(el) {
3009
+ return Boolean(el.tagName === 'svg' || el.ownerSVGElement);
3010
+ }
3011
+ function getHref() {
3012
+ var a = document.createElement('a');
3013
+ a.href = '';
3014
+ return a.href;
3015
+ }
3016
+ function transformAttribute(doc, tagName, name, value) {
3017
+ if (name === 'src' ||
3018
+ (name === 'href' && value && !(tagName === 'use' && value[0] === '#'))) {
3019
+ return absoluteToDoc(doc, value);
3020
+ }
3021
+ else if (name === 'xlink:href' && value && value[0] !== '#') {
3022
+ return absoluteToDoc(doc, value);
3023
+ }
3024
+ else if (name === 'background' &&
3025
+ value &&
3026
+ (tagName === 'table' || tagName === 'td' || tagName === 'th')) {
3027
+ return absoluteToDoc(doc, value);
3028
+ }
3029
+ else if (name === 'srcset' && value) {
3030
+ return getAbsoluteSrcsetString(doc, value);
3031
+ }
3032
+ else if (name === 'style' && value) {
3033
+ return absoluteToStylesheet(value, getHref());
3034
+ }
3035
+ else if (tagName === 'object' && name === 'data' && value) {
3036
+ return absoluteToDoc(doc, value);
3037
+ }
3038
+ else {
3039
+ return value;
3040
+ }
3041
+ }
3042
+ function _isBlockedElement(element, blockClass, blockSelector) {
3043
+ if (typeof blockClass === 'string') {
3044
+ if (element.classList.contains(blockClass)) {
3045
+ return true;
3046
+ }
3047
+ }
3048
+ else {
3049
+ for (var eIndex = element.classList.length; eIndex--;) {
3050
+ var className = element.classList[eIndex];
3051
+ if (blockClass.test(className)) {
3052
+ return true;
3053
+ }
3054
+ }
3055
+ }
3056
+ if (blockSelector) {
3057
+ return element.matches(blockSelector);
3058
+ }
3059
+ return false;
3060
+ }
3061
+ function classMatchesRegex(node, regex, checkAncestors) {
3062
+ if (!node)
3063
+ return false;
3064
+ if (node.nodeType !== node.ELEMENT_NODE) {
3065
+ if (!checkAncestors)
3066
+ return false;
3067
+ return classMatchesRegex(node.parentNode, regex, checkAncestors);
3068
+ }
3069
+ for (var eIndex = node.classList.length; eIndex--;) {
3070
+ var className = node.classList[eIndex];
3071
+ if (regex.test(className)) {
3072
+ return true;
3073
+ }
3074
+ }
3075
+ if (!checkAncestors)
3076
+ return false;
3077
+ return classMatchesRegex(node.parentNode, regex, checkAncestors);
3078
+ }
3079
+ function needMaskingText(node, maskTextClass, maskTextSelector) {
3080
+ var el = node.nodeType === node.ELEMENT_NODE
3081
+ ? node
3082
+ : node.parentElement;
3083
+ if (el === null)
3084
+ return false;
3085
+ if (typeof maskTextClass === 'string') {
3086
+ if (el.classList.contains(maskTextClass))
3087
+ return true;
3088
+ if (el.closest(".".concat(maskTextClass)))
3089
+ return true;
3090
+ }
3091
+ else {
3092
+ if (classMatchesRegex(el, maskTextClass, true))
3093
+ return true;
3094
+ }
3095
+ if (maskTextSelector) {
3096
+ if (el.matches(maskTextSelector))
3097
+ return true;
3098
+ if (el.closest(maskTextSelector))
3099
+ return true;
3100
+ }
3101
+ return false;
3102
+ }
3103
+ function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
3104
+ var win = iframeEl.contentWindow;
3105
+ if (!win) {
3106
+ return;
3107
+ }
3108
+ var fired = false;
3109
+ var readyState;
3110
+ try {
3111
+ readyState = win.document.readyState;
3112
+ }
3113
+ catch (error) {
3114
+ return;
3115
+ }
3116
+ if (readyState !== 'complete') {
3117
+ var timer_1 = setTimeout(function () {
3118
+ if (!fired) {
3119
+ listener();
3120
+ fired = true;
3121
+ }
3122
+ }, iframeLoadTimeout);
3123
+ iframeEl.addEventListener('load', function () {
3124
+ clearTimeout(timer_1);
3125
+ fired = true;
3126
+ listener();
3127
+ });
3128
+ return;
3129
+ }
3130
+ var blankUrl = 'about:blank';
3131
+ if (win.location.href !== blankUrl ||
3132
+ iframeEl.src === blankUrl ||
3133
+ iframeEl.src === '') {
3134
+ setTimeout(listener, 0);
3135
+ return iframeEl.addEventListener('load', listener);
3136
+ }
3137
+ iframeEl.addEventListener('load', listener);
3138
+ }
3139
+ function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
3140
+ var fired = false;
3141
+ var styleSheetLoaded;
3142
+ try {
3143
+ styleSheetLoaded = link.sheet;
3144
+ }
3145
+ catch (error) {
3146
+ return;
3147
+ }
3148
+ if (styleSheetLoaded)
3149
+ return;
3150
+ var timer = setTimeout(function () {
3151
+ if (!fired) {
3152
+ listener();
3153
+ fired = true;
3154
+ }
3155
+ }, styleSheetLoadTimeout);
3156
+ link.addEventListener('load', function () {
3157
+ clearTimeout(timer);
3158
+ fired = true;
3159
+ listener();
3160
+ });
3161
+ }
3162
+ function serializeNode(n, options) {
3163
+ var doc = options.doc, mirror = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, inlineStylesheet = options.inlineStylesheet, _a = options.maskInputOptions, maskInputOptions = _a === void 0 ? {} : _a, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, _b = options.dataURLOptions, dataURLOptions = _b === void 0 ? {} : _b, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _c = options.newlyAddedElement, newlyAddedElement = _c === void 0 ? false : _c;
3164
+ var rootId = getRootId(doc, mirror);
3165
+ switch (n.nodeType) {
3166
+ case n.DOCUMENT_NODE:
3167
+ if (n.compatMode !== 'CSS1Compat') {
3168
+ return {
3169
+ type: NodeType.Document,
3170
+ childNodes: [],
3171
+ compatMode: n.compatMode
3172
+ };
3173
+ }
3174
+ else {
3175
+ return {
3176
+ type: NodeType.Document,
3177
+ childNodes: []
3178
+ };
3179
+ }
3180
+ case n.DOCUMENT_TYPE_NODE:
3181
+ return {
3182
+ type: NodeType.DocumentType,
3183
+ name: n.name,
3184
+ publicId: n.publicId,
3185
+ systemId: n.systemId,
3186
+ rootId: rootId
3187
+ };
3188
+ case n.ELEMENT_NODE:
3189
+ return serializeElementNode(n, {
3190
+ doc: doc,
3191
+ blockClass: blockClass,
3192
+ blockSelector: blockSelector,
3193
+ inlineStylesheet: inlineStylesheet,
3194
+ maskInputOptions: maskInputOptions,
3195
+ maskInputFn: maskInputFn,
3196
+ dataURLOptions: dataURLOptions,
3197
+ inlineImages: inlineImages,
3198
+ recordCanvas: recordCanvas,
3199
+ keepIframeSrcFn: keepIframeSrcFn,
3200
+ newlyAddedElement: newlyAddedElement,
3201
+ rootId: rootId
3202
+ });
3203
+ case n.TEXT_NODE:
3204
+ return serializeTextNode(n, {
3205
+ maskTextClass: maskTextClass,
3206
+ maskTextSelector: maskTextSelector,
3207
+ maskTextFn: maskTextFn,
3208
+ rootId: rootId
3209
+ });
3210
+ case n.CDATA_SECTION_NODE:
3211
+ return {
3212
+ type: NodeType.CDATA,
3213
+ textContent: '',
3214
+ rootId: rootId
3215
+ };
3216
+ case n.COMMENT_NODE:
3217
+ return {
3218
+ type: NodeType.Comment,
3219
+ textContent: n.textContent || '',
3220
+ rootId: rootId
3221
+ };
3222
+ default:
3223
+ return false;
3224
+ }
3225
+ }
3226
+ function getRootId(doc, mirror) {
3227
+ if (!mirror.hasNode(doc))
3228
+ return undefined;
3229
+ var docId = mirror.getId(doc);
3230
+ return docId === 1 ? undefined : docId;
3231
+ }
3232
+ function serializeTextNode(n, options) {
3233
+ var _a;
3234
+ var maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, maskTextFn = options.maskTextFn, rootId = options.rootId;
3235
+ var parentTagName = n.parentNode && n.parentNode.tagName;
3236
+ var textContent = n.textContent;
3237
+ var isStyle = parentTagName === 'STYLE' ? true : undefined;
3238
+ var isScript = parentTagName === 'SCRIPT' ? true : undefined;
3239
+ if (isStyle && textContent) {
3240
+ try {
3241
+ if (n.nextSibling || n.previousSibling) {
3242
+ }
3243
+ else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {
3244
+ textContent = stringifyStyleSheet(n.parentNode.sheet);
3245
+ }
3246
+ }
3247
+ catch (err) {
3248
+ console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(err), n);
3249
+ }
3250
+ textContent = absoluteToStylesheet(textContent, getHref());
3251
+ }
3252
+ if (isScript) {
3253
+ textContent = 'SCRIPT_PLACEHOLDER';
3254
+ }
3255
+ if (!isStyle &&
3256
+ !isScript &&
3257
+ textContent &&
3258
+ needMaskingText(n, maskTextClass, maskTextSelector)) {
3259
+ textContent = maskTextFn
3260
+ ? maskTextFn(textContent)
3261
+ : textContent.replace(/[\S]/g, '*');
3262
+ }
3263
+ return {
3264
+ type: NodeType.Text,
3265
+ textContent: textContent || '',
3266
+ isStyle: isStyle,
3267
+ rootId: rootId
3268
+ };
3269
+ }
3270
+ function serializeElementNode(n, options) {
3271
+ var doc = options.doc, blockClass = options.blockClass, blockSelector = options.blockSelector, inlineStylesheet = options.inlineStylesheet, _a = options.maskInputOptions, maskInputOptions = _a === void 0 ? {} : _a, maskInputFn = options.maskInputFn, _b = options.dataURLOptions, dataURLOptions = _b === void 0 ? {} : _b, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _c = options.newlyAddedElement, newlyAddedElement = _c === void 0 ? false : _c, rootId = options.rootId;
3272
+ var needBlock = _isBlockedElement(n, blockClass, blockSelector);
3273
+ var tagName = getValidTagName(n);
3274
+ var attributes = {};
3275
+ var len = n.attributes.length;
3276
+ for (var i = 0; i < len; i++) {
3277
+ var attr = n.attributes[i];
3278
+ attributes[attr.name] = transformAttribute(doc, tagName, attr.name, attr.value);
3279
+ }
3280
+ if (tagName === 'link' && inlineStylesheet) {
3281
+ var stylesheet = Array.from(doc.styleSheets).find(function (s) {
3282
+ return s.href === n.href;
3283
+ });
3284
+ var cssText = null;
3285
+ if (stylesheet) {
3286
+ cssText = getCssRulesString(stylesheet);
3287
+ }
3288
+ if (cssText) {
3289
+ delete attributes.rel;
3290
+ delete attributes.href;
3291
+ attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);
3292
+ }
3293
+ }
3294
+ if (tagName === 'style' &&
3295
+ n.sheet &&
3296
+ !(n.innerText || n.textContent || '').trim().length) {
3297
+ var cssText = getCssRulesString(n.sheet);
3298
+ if (cssText) {
3299
+ attributes._cssText = absoluteToStylesheet(cssText, getHref());
3300
+ }
3301
+ }
3302
+ if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {
3303
+ var value = n.value;
3304
+ var checked = n.checked;
3305
+ if (attributes.type !== 'radio' &&
3306
+ attributes.type !== 'checkbox' &&
3307
+ attributes.type !== 'submit' &&
3308
+ attributes.type !== 'button' &&
3309
+ value) {
3310
+ attributes.value = maskInputValue({
3311
+ type: attributes.type,
3312
+ tagName: tagName,
3313
+ value: value,
3314
+ maskInputOptions: maskInputOptions,
3315
+ maskInputFn: maskInputFn
3316
+ });
3317
+ }
3318
+ else if (checked) {
3319
+ attributes.checked = checked;
3320
+ }
3321
+ }
3322
+ if (tagName === 'option') {
3323
+ if (n.selected && !maskInputOptions['select']) {
3324
+ attributes.selected = true;
3325
+ }
3326
+ else {
3327
+ delete attributes.selected;
3328
+ }
3329
+ }
3330
+ if (tagName === 'canvas' && recordCanvas) {
3331
+ if (n.__context === '2d') {
3332
+ if (!is2DCanvasBlank(n)) {
3333
+ attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
3334
+ }
3335
+ }
3336
+ else if (!('__context' in n)) {
3337
+ var canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
3338
+ var blankCanvas = document.createElement('canvas');
3339
+ blankCanvas.width = n.width;
3340
+ blankCanvas.height = n.height;
3341
+ var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
3342
+ if (canvasDataURL !== blankCanvasDataURL) {
3343
+ attributes.rr_dataURL = canvasDataURL;
3344
+ }
3345
+ }
3346
+ }
3347
+ if (tagName === 'img' && inlineImages) {
3348
+ if (!canvasService) {
3349
+ canvasService = doc.createElement('canvas');
3350
+ canvasCtx = canvasService.getContext('2d');
3351
+ }
3352
+ var image_1 = n;
3353
+ var oldValue_1 = image_1.crossOrigin;
3354
+ image_1.crossOrigin = 'anonymous';
3355
+ var recordInlineImage = function () {
3356
+ try {
3357
+ canvasService.width = image_1.naturalWidth;
3358
+ canvasService.height = image_1.naturalHeight;
3359
+ canvasCtx.drawImage(image_1, 0, 0);
3360
+ attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
3361
+ }
3362
+ catch (err) {
3363
+ console.warn("Cannot inline img src=".concat(image_1.currentSrc, "! Error: ").concat(err));
3364
+ }
3365
+ oldValue_1
3366
+ ? (attributes.crossOrigin = oldValue_1)
3367
+ : image_1.removeAttribute('crossorigin');
3368
+ };
3369
+ if (image_1.complete && image_1.naturalWidth !== 0)
3370
+ recordInlineImage();
3371
+ else
3372
+ image_1.onload = recordInlineImage;
3373
+ }
3374
+ if (tagName === 'audio' || tagName === 'video') {
3375
+ attributes.rr_mediaState = n.paused
3376
+ ? 'paused'
3377
+ : 'played';
3378
+ attributes.rr_mediaCurrentTime = n.currentTime;
3379
+ }
3380
+ if (!newlyAddedElement) {
3381
+ if (n.scrollLeft) {
3382
+ attributes.rr_scrollLeft = n.scrollLeft;
3383
+ }
3384
+ if (n.scrollTop) {
3385
+ attributes.rr_scrollTop = n.scrollTop;
3386
+ }
3387
+ }
3388
+ if (needBlock) {
3389
+ var _d = n.getBoundingClientRect(), width = _d.width, height = _d.height;
3390
+ attributes = {
3391
+ "class": attributes["class"],
3392
+ rr_width: "".concat(width, "px"),
3393
+ rr_height: "".concat(height, "px")
3394
+ };
3395
+ }
3396
+ if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {
3397
+ if (!n.contentDocument) {
3398
+ attributes.rr_src = attributes.src;
3399
+ }
3400
+ delete attributes.src;
3401
+ }
3402
+ return {
3403
+ type: NodeType.Element,
3404
+ tagName: tagName,
3405
+ attributes: attributes,
3406
+ childNodes: [],
3407
+ isSVG: isSVGElement(n) || undefined,
3408
+ needBlock: needBlock,
3409
+ rootId: rootId
3410
+ };
3411
+ }
3412
+ function lowerIfExists(maybeAttr) {
3413
+ if (maybeAttr === undefined) {
3414
+ return '';
3415
+ }
3416
+ else {
3417
+ return maybeAttr.toLowerCase();
3418
+ }
3419
+ }
3420
+ function slimDOMExcluded(sn, slimDOMOptions) {
3421
+ if (slimDOMOptions.comment && sn.type === NodeType.Comment) {
3422
+ return true;
3423
+ }
3424
+ else if (sn.type === NodeType.Element) {
3425
+ if (slimDOMOptions.script &&
3426
+ (sn.tagName === 'script' ||
3427
+ (sn.tagName === 'link' &&
3428
+ sn.attributes.rel === 'preload' &&
3429
+ sn.attributes.as === 'script') ||
3430
+ (sn.tagName === 'link' &&
3431
+ sn.attributes.rel === 'prefetch' &&
3432
+ typeof sn.attributes.href === 'string' &&
3433
+ sn.attributes.href.endsWith('.js')))) {
3434
+ return true;
3435
+ }
3436
+ else if (slimDOMOptions.headFavicon &&
3437
+ ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||
3438
+ (sn.tagName === 'meta' &&
3439
+ (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||
3440
+ lowerIfExists(sn.attributes.name) === 'application-name' ||
3441
+ lowerIfExists(sn.attributes.rel) === 'icon' ||
3442
+ lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||
3443
+ lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {
3444
+ return true;
3445
+ }
3446
+ else if (sn.tagName === 'meta') {
3447
+ if (slimDOMOptions.headMetaDescKeywords &&
3448
+ lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
3449
+ return true;
3450
+ }
3451
+ else if (slimDOMOptions.headMetaSocial &&
3452
+ (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||
3453
+ lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||
3454
+ lowerIfExists(sn.attributes.name) === 'pinterest')) {
3455
+ return true;
3456
+ }
3457
+ else if (slimDOMOptions.headMetaRobots &&
3458
+ (lowerIfExists(sn.attributes.name) === 'robots' ||
3459
+ lowerIfExists(sn.attributes.name) === 'googlebot' ||
3460
+ lowerIfExists(sn.attributes.name) === 'bingbot')) {
3461
+ return true;
3462
+ }
3463
+ else if (slimDOMOptions.headMetaHttpEquiv &&
3464
+ sn.attributes['http-equiv'] !== undefined) {
3465
+ return true;
3466
+ }
3467
+ else if (slimDOMOptions.headMetaAuthorship &&
3468
+ (lowerIfExists(sn.attributes.name) === 'author' ||
3469
+ lowerIfExists(sn.attributes.name) === 'generator' ||
3470
+ lowerIfExists(sn.attributes.name) === 'framework' ||
3471
+ lowerIfExists(sn.attributes.name) === 'publisher' ||
3472
+ lowerIfExists(sn.attributes.name) === 'progid' ||
3473
+ lowerIfExists(sn.attributes.property).match(/^article:/) ||
3474
+ lowerIfExists(sn.attributes.property).match(/^product:/))) {
3475
+ return true;
3476
+ }
3477
+ else if (slimDOMOptions.headMetaVerification &&
3478
+ (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||
3479
+ lowerIfExists(sn.attributes.name) === 'yandex-verification' ||
3480
+ lowerIfExists(sn.attributes.name) === 'csrf-token' ||
3481
+ lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||
3482
+ lowerIfExists(sn.attributes.name) === 'verify-v1' ||
3483
+ lowerIfExists(sn.attributes.name) === 'verification' ||
3484
+ lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {
3485
+ return true;
3486
+ }
3487
+ }
3488
+ }
3489
+ return false;
3490
+ }
3491
+ function serializeNodeWithId(n, options) {
3492
+ var doc = options.doc, mirror = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, _a = options.skipChild, skipChild = _a === void 0 ? false : _a, _b = options.inlineStylesheet, inlineStylesheet = _b === void 0 ? true : _b, _c = options.maskInputOptions, maskInputOptions = _c === void 0 ? {} : _c, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, slimDOMOptions = options.slimDOMOptions, _d = options.dataURLOptions, dataURLOptions = _d === void 0 ? {} : _d, _e = options.inlineImages, inlineImages = _e === void 0 ? false : _e, _f = options.recordCanvas, recordCanvas = _f === void 0 ? false : _f, onSerialize = options.onSerialize, onIframeLoad = options.onIframeLoad, _g = options.iframeLoadTimeout, iframeLoadTimeout = _g === void 0 ? 5000 : _g, onStylesheetLoad = options.onStylesheetLoad, _h = options.stylesheetLoadTimeout, stylesheetLoadTimeout = _h === void 0 ? 5000 : _h, _j = options.keepIframeSrcFn, keepIframeSrcFn = _j === void 0 ? function () { return false; } : _j, _k = options.newlyAddedElement, newlyAddedElement = _k === void 0 ? false : _k;
3493
+ var _l = options.preserveWhiteSpace, preserveWhiteSpace = _l === void 0 ? true : _l;
3494
+ var _serializedNode = serializeNode(n, {
3495
+ doc: doc,
3496
+ mirror: mirror,
3497
+ blockClass: blockClass,
3498
+ blockSelector: blockSelector,
3499
+ maskTextClass: maskTextClass,
3500
+ maskTextSelector: maskTextSelector,
3501
+ inlineStylesheet: inlineStylesheet,
3502
+ maskInputOptions: maskInputOptions,
3503
+ maskTextFn: maskTextFn,
3504
+ maskInputFn: maskInputFn,
3505
+ dataURLOptions: dataURLOptions,
3506
+ inlineImages: inlineImages,
3507
+ recordCanvas: recordCanvas,
3508
+ keepIframeSrcFn: keepIframeSrcFn,
3509
+ newlyAddedElement: newlyAddedElement
3510
+ });
3511
+ if (!_serializedNode) {
3512
+ console.warn(n, 'not serialized');
3513
+ return null;
3514
+ }
3515
+ var id;
3516
+ if (mirror.hasNode(n)) {
3517
+ id = mirror.getId(n);
3518
+ }
3519
+ else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||
3520
+ (!preserveWhiteSpace &&
3521
+ _serializedNode.type === NodeType.Text &&
3522
+ !_serializedNode.isStyle &&
3523
+ !_serializedNode.textContent.replace(/^\s+|\s+$/gm, '').length)) {
3524
+ id = IGNORED_NODE;
3525
+ }
3526
+ else {
3527
+ id = genId();
3528
+ }
3529
+ var serializedNode = Object.assign(_serializedNode, { id: id });
3530
+ mirror.add(n, serializedNode);
3531
+ if (id === IGNORED_NODE) {
3532
+ return null;
3533
+ }
3534
+ if (onSerialize) {
3535
+ onSerialize(n);
3536
+ }
3537
+ var recordChild = !skipChild;
3538
+ if (serializedNode.type === NodeType.Element) {
3539
+ recordChild = recordChild && !serializedNode.needBlock;
3540
+ delete serializedNode.needBlock;
3541
+ var shadowRoot = n.shadowRoot;
3542
+ if (shadowRoot && isNativeShadowDom(shadowRoot))
3543
+ serializedNode.isShadowHost = true;
3544
+ }
3545
+ if ((serializedNode.type === NodeType.Document ||
3546
+ serializedNode.type === NodeType.Element) &&
3547
+ recordChild) {
3548
+ if (slimDOMOptions.headWhitespace &&
3549
+ serializedNode.type === NodeType.Element &&
3550
+ serializedNode.tagName === 'head') {
3551
+ preserveWhiteSpace = false;
3552
+ }
3553
+ var bypassOptions = {
3554
+ doc: doc,
3555
+ mirror: mirror,
3556
+ blockClass: blockClass,
3557
+ blockSelector: blockSelector,
3558
+ maskTextClass: maskTextClass,
3559
+ maskTextSelector: maskTextSelector,
3560
+ skipChild: skipChild,
3561
+ inlineStylesheet: inlineStylesheet,
3562
+ maskInputOptions: maskInputOptions,
3563
+ maskTextFn: maskTextFn,
3564
+ maskInputFn: maskInputFn,
3565
+ slimDOMOptions: slimDOMOptions,
3566
+ dataURLOptions: dataURLOptions,
3567
+ inlineImages: inlineImages,
3568
+ recordCanvas: recordCanvas,
3569
+ preserveWhiteSpace: preserveWhiteSpace,
3570
+ onSerialize: onSerialize,
3571
+ onIframeLoad: onIframeLoad,
3572
+ iframeLoadTimeout: iframeLoadTimeout,
3573
+ onStylesheetLoad: onStylesheetLoad,
3574
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
3575
+ keepIframeSrcFn: keepIframeSrcFn
3576
+ };
3577
+ for (var _i = 0, _m = Array.from(n.childNodes); _i < _m.length; _i++) {
3578
+ var childN = _m[_i];
3579
+ var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
3580
+ if (serializedChildNode) {
3581
+ serializedNode.childNodes.push(serializedChildNode);
3582
+ }
3583
+ }
3584
+ if (isElement(n) && n.shadowRoot) {
3585
+ for (var _o = 0, _p = Array.from(n.shadowRoot.childNodes); _o < _p.length; _o++) {
3586
+ var childN = _p[_o];
3587
+ var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
3588
+ if (serializedChildNode) {
3589
+ isNativeShadowDom(n.shadowRoot) &&
3590
+ (serializedChildNode.isShadow = true);
3591
+ serializedNode.childNodes.push(serializedChildNode);
3592
+ }
3593
+ }
3594
+ }
3595
+ }
3596
+ if (n.parentNode &&
3597
+ isShadowRoot(n.parentNode) &&
3598
+ isNativeShadowDom(n.parentNode)) {
3599
+ serializedNode.isShadow = true;
3600
+ }
3601
+ if (serializedNode.type === NodeType.Element &&
3602
+ serializedNode.tagName === 'iframe') {
3603
+ onceIframeLoaded(n, function () {
3604
+ var iframeDoc = n.contentDocument;
3605
+ if (iframeDoc && onIframeLoad) {
3606
+ var serializedIframeNode = serializeNodeWithId(iframeDoc, {
3607
+ doc: iframeDoc,
3608
+ mirror: mirror,
3609
+ blockClass: blockClass,
3610
+ blockSelector: blockSelector,
3611
+ maskTextClass: maskTextClass,
3612
+ maskTextSelector: maskTextSelector,
3613
+ skipChild: false,
3614
+ inlineStylesheet: inlineStylesheet,
3615
+ maskInputOptions: maskInputOptions,
3616
+ maskTextFn: maskTextFn,
3617
+ maskInputFn: maskInputFn,
3618
+ slimDOMOptions: slimDOMOptions,
3619
+ dataURLOptions: dataURLOptions,
3620
+ inlineImages: inlineImages,
3621
+ recordCanvas: recordCanvas,
3622
+ preserveWhiteSpace: preserveWhiteSpace,
3623
+ onSerialize: onSerialize,
3624
+ onIframeLoad: onIframeLoad,
3625
+ iframeLoadTimeout: iframeLoadTimeout,
3626
+ onStylesheetLoad: onStylesheetLoad,
3627
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
3628
+ keepIframeSrcFn: keepIframeSrcFn
3629
+ });
3630
+ if (serializedIframeNode) {
3631
+ onIframeLoad(n, serializedIframeNode);
3632
+ }
3633
+ }
3634
+ }, iframeLoadTimeout);
3635
+ }
3636
+ if (serializedNode.type === NodeType.Element &&
3637
+ serializedNode.tagName === 'link' &&
3638
+ serializedNode.attributes.rel === 'stylesheet') {
3639
+ onceStylesheetLoaded(n, function () {
3640
+ if (onStylesheetLoad) {
3641
+ var serializedLinkNode = serializeNodeWithId(n, {
3642
+ doc: doc,
3643
+ mirror: mirror,
3644
+ blockClass: blockClass,
3645
+ blockSelector: blockSelector,
3646
+ maskTextClass: maskTextClass,
3647
+ maskTextSelector: maskTextSelector,
3648
+ skipChild: false,
3649
+ inlineStylesheet: inlineStylesheet,
3650
+ maskInputOptions: maskInputOptions,
3651
+ maskTextFn: maskTextFn,
3652
+ maskInputFn: maskInputFn,
3653
+ slimDOMOptions: slimDOMOptions,
3654
+ dataURLOptions: dataURLOptions,
3655
+ inlineImages: inlineImages,
3656
+ recordCanvas: recordCanvas,
3657
+ preserveWhiteSpace: preserveWhiteSpace,
3658
+ onSerialize: onSerialize,
3659
+ onIframeLoad: onIframeLoad,
3660
+ iframeLoadTimeout: iframeLoadTimeout,
3661
+ onStylesheetLoad: onStylesheetLoad,
3662
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
3663
+ keepIframeSrcFn: keepIframeSrcFn
3664
+ });
3665
+ if (serializedLinkNode) {
3666
+ onStylesheetLoad(n, serializedLinkNode);
3667
+ }
3668
+ }
3669
+ }, stylesheetLoadTimeout);
3670
+ }
3671
+ return serializedNode;
3672
+ }
3673
+ function snapshot(n, options) {
3674
+ var _a = options || {}, _b = _a.mirror, mirror = _b === void 0 ? new Mirror() : _b, _c = _a.blockClass, blockClass = _c === void 0 ? 'rr-block' : _c, _d = _a.blockSelector, blockSelector = _d === void 0 ? null : _d, _e = _a.maskTextClass, maskTextClass = _e === void 0 ? 'rr-mask' : _e, _f = _a.maskTextSelector, maskTextSelector = _f === void 0 ? null : _f, _g = _a.inlineStylesheet, inlineStylesheet = _g === void 0 ? true : _g, _h = _a.inlineImages, inlineImages = _h === void 0 ? false : _h, _j = _a.recordCanvas, recordCanvas = _j === void 0 ? false : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? false : _k, maskTextFn = _a.maskTextFn, maskInputFn = _a.maskInputFn, _l = _a.slimDOM, slimDOM = _l === void 0 ? false : _l, dataURLOptions = _a.dataURLOptions, preserveWhiteSpace = _a.preserveWhiteSpace, onSerialize = _a.onSerialize, onIframeLoad = _a.onIframeLoad, iframeLoadTimeout = _a.iframeLoadTimeout, onStylesheetLoad = _a.onStylesheetLoad, stylesheetLoadTimeout = _a.stylesheetLoadTimeout, _m = _a.keepIframeSrcFn, keepIframeSrcFn = _m === void 0 ? function () { return false; } : _m;
3675
+ var maskInputOptions = maskAllInputs === true
3676
+ ? {
3677
+ color: true,
3678
+ date: true,
3679
+ 'datetime-local': true,
3680
+ email: true,
3681
+ month: true,
3682
+ number: true,
3683
+ range: true,
3684
+ search: true,
3685
+ tel: true,
3686
+ text: true,
3687
+ time: true,
3688
+ url: true,
3689
+ week: true,
3690
+ textarea: true,
3691
+ select: true,
3692
+ password: true
3693
+ }
3694
+ : maskAllInputs === false
3695
+ ? {
3696
+ password: true
3697
+ }
3698
+ : maskAllInputs;
3699
+ var slimDOMOptions = slimDOM === true || slimDOM === 'all'
3700
+ ?
3701
+ {
3702
+ script: true,
3703
+ comment: true,
3704
+ headFavicon: true,
3705
+ headWhitespace: true,
3706
+ headMetaDescKeywords: slimDOM === 'all',
3707
+ headMetaSocial: true,
3708
+ headMetaRobots: true,
3709
+ headMetaHttpEquiv: true,
3710
+ headMetaAuthorship: true,
3711
+ headMetaVerification: true
3712
+ }
3713
+ : slimDOM === false
3714
+ ? {}
3715
+ : slimDOM;
3716
+ return serializeNodeWithId(n, {
3717
+ doc: n,
3718
+ mirror: mirror,
3719
+ blockClass: blockClass,
3720
+ blockSelector: blockSelector,
3721
+ maskTextClass: maskTextClass,
3722
+ maskTextSelector: maskTextSelector,
3723
+ skipChild: false,
3724
+ inlineStylesheet: inlineStylesheet,
3725
+ maskInputOptions: maskInputOptions,
3726
+ maskTextFn: maskTextFn,
3727
+ maskInputFn: maskInputFn,
3728
+ slimDOMOptions: slimDOMOptions,
3729
+ dataURLOptions: dataURLOptions,
3730
+ inlineImages: inlineImages,
3731
+ recordCanvas: recordCanvas,
3732
+ preserveWhiteSpace: preserveWhiteSpace,
3733
+ onSerialize: onSerialize,
3734
+ onIframeLoad: onIframeLoad,
3735
+ iframeLoadTimeout: iframeLoadTimeout,
3736
+ onStylesheetLoad: onStylesheetLoad,
3737
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
3738
+ keepIframeSrcFn: keepIframeSrcFn,
3739
+ newlyAddedElement: false
3740
+ });
3741
+ }
3742
+
3743
+ function on(type, fn, target = document) {
3744
+ const options = { capture: true, passive: true };
3745
+ target.addEventListener(type, fn, options);
3746
+ return () => target.removeEventListener(type, fn, options);
3747
+ }
3748
+ const DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +
3749
+ '\r\n' +
3750
+ 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +
3751
+ '\r\n' +
3752
+ 'or you can use record.mirror to access the mirror instance during recording.';
3753
+ let _mirror = {
3754
+ map: {},
3755
+ getId() {
3756
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
3757
+ return -1;
3758
+ },
3759
+ getNode() {
3760
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
3761
+ return null;
3762
+ },
3763
+ removeNodeFromMap() {
3764
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
3765
+ },
3766
+ has() {
3767
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
3768
+ return false;
3769
+ },
3770
+ reset() {
3771
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
3772
+ },
3773
+ };
3774
+ if (typeof window !== 'undefined' && window.Proxy && window.Reflect) {
3775
+ _mirror = new Proxy(_mirror, {
3776
+ get(target, prop, receiver) {
3777
+ if (prop === 'map') {
3778
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
3779
+ }
3780
+ return Reflect.get(target, prop, receiver);
3781
+ },
3782
+ });
3783
+ }
3784
+ function throttle(func, wait, options = {}) {
3785
+ let timeout = null;
3786
+ let previous = 0;
3787
+ return function (...args) {
3788
+ const now = Date.now();
3789
+ if (!previous && options.leading === false) {
3790
+ previous = now;
3791
+ }
3792
+ const remaining = wait - (now - previous);
3793
+ const context = this;
3794
+ if (remaining <= 0 || remaining > wait) {
3795
+ if (timeout) {
3796
+ clearTimeout(timeout);
3797
+ timeout = null;
3798
+ }
3799
+ previous = now;
3800
+ func.apply(context, args);
3801
+ }
3802
+ else if (!timeout && options.trailing !== false) {
3803
+ timeout = setTimeout(() => {
3804
+ previous = options.leading === false ? 0 : Date.now();
3805
+ timeout = null;
3806
+ func.apply(context, args);
3807
+ }, remaining);
3808
+ }
3809
+ };
3810
+ }
3811
+ function hookSetter(target, key, d, isRevoked, win = window) {
3812
+ const original = win.Object.getOwnPropertyDescriptor(target, key);
3813
+ win.Object.defineProperty(target, key, isRevoked
3814
+ ? d
3815
+ : {
3816
+ set(value) {
3817
+ setTimeout(() => {
3818
+ d.set.call(this, value);
3819
+ }, 0);
3820
+ if (original && original.set) {
3821
+ original.set.call(this, value);
3822
+ }
3823
+ },
3824
+ });
3825
+ return () => hookSetter(target, key, original || {}, true);
3826
+ }
3827
+ function patch(source, name, replacement) {
3828
+ try {
3829
+ if (!(name in source)) {
3830
+ return () => {
3831
+ };
3832
+ }
3833
+ const original = source[name];
3834
+ const wrapped = replacement(original);
3835
+ if (typeof wrapped === 'function') {
3836
+ wrapped.prototype = wrapped.prototype || {};
3837
+ Object.defineProperties(wrapped, {
3838
+ __rrweb_original__: {
3839
+ enumerable: false,
3840
+ value: original,
3841
+ },
3842
+ });
3843
+ }
3844
+ source[name] = wrapped;
3845
+ return () => {
3846
+ source[name] = original;
3847
+ };
3848
+ }
3849
+ catch (_a) {
3850
+ return () => {
3851
+ };
3852
+ }
3853
+ }
3854
+ function getWindowHeight() {
3855
+ return (window.innerHeight ||
3856
+ (document.documentElement && document.documentElement.clientHeight) ||
3857
+ (document.body && document.body.clientHeight));
3858
+ }
3859
+ function getWindowWidth() {
3860
+ return (window.innerWidth ||
3861
+ (document.documentElement && document.documentElement.clientWidth) ||
3862
+ (document.body && document.body.clientWidth));
3863
+ }
3864
+ function isBlocked(node, blockClass, blockSelector, checkAncestors) {
3865
+ if (!node) {
3866
+ return false;
3867
+ }
3868
+ const el = node.nodeType === node.ELEMENT_NODE
3869
+ ? node
3870
+ : node.parentElement;
3871
+ if (!el)
3872
+ return false;
3873
+ if (typeof blockClass === 'string') {
3874
+ if (el.classList.contains(blockClass))
3875
+ return true;
3876
+ if (checkAncestors && el.closest('.' + blockClass) !== null)
3877
+ return true;
3878
+ }
3879
+ else {
3880
+ if (classMatchesRegex(el, blockClass, checkAncestors))
3881
+ return true;
3882
+ }
3883
+ if (blockSelector) {
3884
+ if (node.matches(blockSelector))
3885
+ return true;
3886
+ if (checkAncestors && el.closest(blockSelector) !== null)
3887
+ return true;
3888
+ }
3889
+ return false;
3890
+ }
3891
+ function isSerialized(n, mirror) {
3892
+ return mirror.getId(n) !== -1;
3893
+ }
3894
+ function isIgnored(n, mirror) {
3895
+ return mirror.getId(n) === IGNORED_NODE;
3896
+ }
3897
+ function isAncestorRemoved(target, mirror) {
3898
+ if (isShadowRoot(target)) {
3899
+ return false;
3900
+ }
3901
+ const id = mirror.getId(target);
3902
+ if (!mirror.has(id)) {
3903
+ return true;
3904
+ }
3905
+ if (target.parentNode &&
3906
+ target.parentNode.nodeType === target.DOCUMENT_NODE) {
3907
+ return false;
3908
+ }
3909
+ if (!target.parentNode) {
3910
+ return true;
3911
+ }
3912
+ return isAncestorRemoved(target.parentNode, mirror);
3913
+ }
3914
+ function isTouchEvent(event) {
3915
+ return Boolean(event.changedTouches);
3916
+ }
3917
+ function polyfill(win = window) {
3918
+ if ('NodeList' in win && !win.NodeList.prototype.forEach) {
3919
+ win.NodeList.prototype.forEach = Array.prototype
3920
+ .forEach;
3921
+ }
3922
+ if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {
3923
+ win.DOMTokenList.prototype.forEach = Array.prototype
3924
+ .forEach;
3925
+ }
3926
+ if (!Node.prototype.contains) {
3927
+ Node.prototype.contains = (...args) => {
3928
+ let node = args[0];
3929
+ if (!(0 in args)) {
3930
+ throw new TypeError('1 argument is required');
3931
+ }
3932
+ do {
3933
+ if (this === node) {
3934
+ return true;
3935
+ }
3936
+ } while ((node = node && node.parentNode));
3937
+ return false;
3938
+ };
3939
+ }
3940
+ }
3941
+ function isSerializedIframe(n, mirror) {
3942
+ return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));
3943
+ }
3944
+ function isSerializedStylesheet(n, mirror) {
3945
+ return Boolean(n.nodeName === 'LINK' &&
3946
+ n.nodeType === n.ELEMENT_NODE &&
3947
+ n.getAttribute &&
3948
+ n.getAttribute('rel') === 'stylesheet' &&
3949
+ mirror.getMeta(n));
3950
+ }
3951
+ function hasShadowRoot(n) {
3952
+ return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);
3953
+ }
3954
+ class StyleSheetMirror {
3955
+ constructor() {
3956
+ this.id = 1;
3957
+ this.styleIDMap = new WeakMap();
3958
+ this.idStyleMap = new Map();
3959
+ }
3960
+ getId(stylesheet) {
3961
+ var _a;
3962
+ return (_a = this.styleIDMap.get(stylesheet)) !== null && _a !== void 0 ? _a : -1;
3963
+ }
3964
+ has(stylesheet) {
3965
+ return this.styleIDMap.has(stylesheet);
3966
+ }
3967
+ add(stylesheet, id) {
3968
+ if (this.has(stylesheet))
3969
+ return this.getId(stylesheet);
3970
+ let newId;
3971
+ if (id === undefined) {
3972
+ newId = this.id++;
3973
+ }
3974
+ else
3975
+ newId = id;
3976
+ this.styleIDMap.set(stylesheet, newId);
3977
+ this.idStyleMap.set(newId, stylesheet);
3978
+ return newId;
3979
+ }
3980
+ getStyle(id) {
3981
+ return this.idStyleMap.get(id) || null;
3982
+ }
3983
+ reset() {
3984
+ this.styleIDMap = new WeakMap();
3985
+ this.idStyleMap = new Map();
3986
+ this.id = 1;
3987
+ }
3988
+ generateId() {
3989
+ return this.id++;
3990
+ }
3991
+ }
3992
+
3993
+ var EventType = /* @__PURE__ */ ((EventType2) => {
3994
+ EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
3995
+ EventType2[EventType2["Load"] = 1] = "Load";
3996
+ EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
3997
+ EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
3998
+ EventType2[EventType2["Meta"] = 4] = "Meta";
3999
+ EventType2[EventType2["Custom"] = 5] = "Custom";
4000
+ EventType2[EventType2["Plugin"] = 6] = "Plugin";
4001
+ return EventType2;
4002
+ })(EventType || {});
4003
+ var IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {
4004
+ IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
4005
+ IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
4006
+ IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
4007
+ IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
4008
+ IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
4009
+ IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
4010
+ IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
4011
+ IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
4012
+ IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
4013
+ IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
4014
+ IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
4015
+ IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
4016
+ IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
4017
+ IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
4018
+ IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
4019
+ IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
4020
+ return IncrementalSource2;
4021
+ })(IncrementalSource || {});
4022
+ var MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {
4023
+ MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
4024
+ MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
4025
+ MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
4026
+ MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
4027
+ MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
4028
+ MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
4029
+ MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
4030
+ MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
4031
+ MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
4032
+ MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
4033
+ MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
4034
+ return MouseInteractions2;
4035
+ })(MouseInteractions || {});
4036
+ var CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {
4037
+ CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
4038
+ CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
4039
+ CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
4040
+ return CanvasContext2;
4041
+ })(CanvasContext || {});
4042
+
4043
+ function isNodeInLinkedList(n) {
4044
+ return '__ln' in n;
4045
+ }
4046
+ class DoubleLinkedList {
4047
+ constructor() {
4048
+ this.length = 0;
4049
+ this.head = null;
4050
+ }
4051
+ get(position) {
4052
+ if (position >= this.length) {
4053
+ throw new Error('Position outside of list range');
4054
+ }
4055
+ let current = this.head;
4056
+ for (let index = 0; index < position; index++) {
4057
+ current = (current === null || current === void 0 ? void 0 : current.next) || null;
4058
+ }
4059
+ return current;
4060
+ }
4061
+ addNode(n) {
4062
+ const node = {
4063
+ value: n,
4064
+ previous: null,
4065
+ next: null,
4066
+ };
4067
+ n.__ln = node;
4068
+ if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {
4069
+ const current = n.previousSibling.__ln.next;
4070
+ node.next = current;
4071
+ node.previous = n.previousSibling.__ln;
4072
+ n.previousSibling.__ln.next = node;
4073
+ if (current) {
4074
+ current.previous = node;
4075
+ }
4076
+ }
4077
+ else if (n.nextSibling &&
4078
+ isNodeInLinkedList(n.nextSibling) &&
4079
+ n.nextSibling.__ln.previous) {
4080
+ const current = n.nextSibling.__ln.previous;
4081
+ node.previous = current;
4082
+ node.next = n.nextSibling.__ln;
4083
+ n.nextSibling.__ln.previous = node;
4084
+ if (current) {
4085
+ current.next = node;
4086
+ }
4087
+ }
4088
+ else {
4089
+ if (this.head) {
4090
+ this.head.previous = node;
4091
+ }
4092
+ node.next = this.head;
4093
+ this.head = node;
4094
+ }
4095
+ this.length++;
4096
+ }
4097
+ removeNode(n) {
4098
+ const current = n.__ln;
4099
+ if (!this.head) {
4100
+ return;
4101
+ }
4102
+ if (!current.previous) {
4103
+ this.head = current.next;
4104
+ if (this.head) {
4105
+ this.head.previous = null;
4106
+ }
4107
+ }
4108
+ else {
4109
+ current.previous.next = current.next;
4110
+ if (current.next) {
4111
+ current.next.previous = current.previous;
4112
+ }
4113
+ }
4114
+ if (n.__ln) {
4115
+ delete n.__ln;
4116
+ }
4117
+ this.length--;
4118
+ }
4119
+ }
4120
+ const moveKey = (id, parentId) => `${id}@${parentId}`;
4121
+ class MutationBuffer {
4122
+ constructor() {
4123
+ this.frozen = false;
4124
+ this.locked = false;
4125
+ this.texts = [];
4126
+ this.attributes = [];
4127
+ this.removes = [];
4128
+ this.mapRemoves = [];
4129
+ this.movedMap = {};
4130
+ this.addedSet = new Set();
4131
+ this.movedSet = new Set();
4132
+ this.droppedSet = new Set();
4133
+ this.processMutations = (mutations) => {
4134
+ mutations.forEach(this.processMutation);
4135
+ this.emit();
4136
+ };
4137
+ this.emit = () => {
4138
+ if (this.frozen || this.locked) {
4139
+ return;
4140
+ }
4141
+ const adds = [];
4142
+ const addList = new DoubleLinkedList();
4143
+ const getNextId = (n) => {
4144
+ let ns = n;
4145
+ let nextId = IGNORED_NODE;
4146
+ while (nextId === IGNORED_NODE) {
4147
+ ns = ns && ns.nextSibling;
4148
+ nextId = ns && this.mirror.getId(ns);
4149
+ }
4150
+ return nextId;
4151
+ };
4152
+ const pushAdd = (n) => {
4153
+ var _a, _b, _c, _d;
4154
+ let shadowHost = null;
4155
+ if (((_b = (_a = n.getRootNode) === null || _a === void 0 ? void 0 : _a.call(n)) === null || _b === void 0 ? void 0 : _b.nodeType) === Node.DOCUMENT_FRAGMENT_NODE &&
4156
+ n.getRootNode().host)
4157
+ shadowHost = n.getRootNode().host;
4158
+ let rootShadowHost = shadowHost;
4159
+ while (((_d = (_c = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _c === void 0 ? void 0 : _c.call(rootShadowHost)) === null || _d === void 0 ? void 0 : _d.nodeType) ===
4160
+ Node.DOCUMENT_FRAGMENT_NODE &&
4161
+ rootShadowHost.getRootNode().host)
4162
+ rootShadowHost = rootShadowHost.getRootNode().host;
4163
+ const notInDoc = !this.doc.contains(n) &&
4164
+ (!rootShadowHost || !this.doc.contains(rootShadowHost));
4165
+ if (!n.parentNode || notInDoc) {
4166
+ return;
4167
+ }
4168
+ const parentId = isShadowRoot(n.parentNode)
4169
+ ? this.mirror.getId(shadowHost)
4170
+ : this.mirror.getId(n.parentNode);
4171
+ const nextId = getNextId(n);
4172
+ if (parentId === -1 || nextId === -1) {
4173
+ return addList.addNode(n);
4174
+ }
4175
+ const sn = serializeNodeWithId(n, {
4176
+ doc: this.doc,
4177
+ mirror: this.mirror,
4178
+ blockClass: this.blockClass,
4179
+ blockSelector: this.blockSelector,
4180
+ maskTextClass: this.maskTextClass,
4181
+ maskTextSelector: this.maskTextSelector,
4182
+ skipChild: true,
4183
+ newlyAddedElement: true,
4184
+ inlineStylesheet: this.inlineStylesheet,
4185
+ maskInputOptions: this.maskInputOptions,
4186
+ maskTextFn: this.maskTextFn,
4187
+ maskInputFn: this.maskInputFn,
4188
+ slimDOMOptions: this.slimDOMOptions,
4189
+ dataURLOptions: this.dataURLOptions,
4190
+ recordCanvas: this.recordCanvas,
4191
+ inlineImages: this.inlineImages,
4192
+ onSerialize: (currentN) => {
4193
+ if (isSerializedIframe(currentN, this.mirror)) {
4194
+ this.iframeManager.addIframe(currentN);
4195
+ }
4196
+ if (isSerializedStylesheet(currentN, this.mirror)) {
4197
+ this.stylesheetManager.trackLinkElement(currentN);
4198
+ }
4199
+ if (hasShadowRoot(n)) {
4200
+ this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);
4201
+ }
4202
+ },
4203
+ onIframeLoad: (iframe, childSn) => {
4204
+ this.iframeManager.attachIframe(iframe, childSn);
4205
+ this.shadowDomManager.observeAttachShadow(iframe);
4206
+ },
4207
+ onStylesheetLoad: (link, childSn) => {
4208
+ this.stylesheetManager.attachLinkElement(link, childSn);
4209
+ },
4210
+ });
4211
+ if (sn) {
4212
+ adds.push({
4213
+ parentId,
4214
+ nextId,
4215
+ node: sn,
4216
+ });
4217
+ }
4218
+ };
4219
+ while (this.mapRemoves.length) {
4220
+ this.mirror.removeNodeFromMap(this.mapRemoves.shift());
4221
+ }
4222
+ for (const n of Array.from(this.movedSet.values())) {
4223
+ if (isParentRemoved(this.removes, n, this.mirror) &&
4224
+ !this.movedSet.has(n.parentNode)) {
4225
+ continue;
4226
+ }
4227
+ pushAdd(n);
4228
+ }
4229
+ for (const n of Array.from(this.addedSet.values())) {
4230
+ if (!isAncestorInSet(this.droppedSet, n) &&
4231
+ !isParentRemoved(this.removes, n, this.mirror)) {
4232
+ pushAdd(n);
4233
+ }
4234
+ else if (isAncestorInSet(this.movedSet, n)) {
4235
+ pushAdd(n);
4236
+ }
4237
+ else {
4238
+ this.droppedSet.add(n);
4239
+ }
4240
+ }
4241
+ let candidate = null;
4242
+ while (addList.length) {
4243
+ let node = null;
4244
+ if (candidate) {
4245
+ const parentId = this.mirror.getId(candidate.value.parentNode);
4246
+ const nextId = getNextId(candidate.value);
4247
+ if (parentId !== -1 && nextId !== -1) {
4248
+ node = candidate;
4249
+ }
4250
+ }
4251
+ if (!node) {
4252
+ for (let index = addList.length - 1; index >= 0; index--) {
4253
+ const _node = addList.get(index);
4254
+ if (_node) {
4255
+ const parentId = this.mirror.getId(_node.value.parentNode);
4256
+ const nextId = getNextId(_node.value);
4257
+ if (nextId === -1)
4258
+ continue;
4259
+ else if (parentId !== -1) {
4260
+ node = _node;
4261
+ break;
4262
+ }
4263
+ else {
4264
+ const unhandledNode = _node.value;
4265
+ if (unhandledNode.parentNode &&
4266
+ unhandledNode.parentNode.nodeType ===
4267
+ Node.DOCUMENT_FRAGMENT_NODE) {
4268
+ const shadowHost = unhandledNode.parentNode
4269
+ .host;
4270
+ const parentId = this.mirror.getId(shadowHost);
4271
+ if (parentId !== -1) {
4272
+ node = _node;
4273
+ break;
4274
+ }
4275
+ }
4276
+ }
4277
+ }
4278
+ }
4279
+ }
4280
+ if (!node) {
4281
+ while (addList.head) {
4282
+ addList.removeNode(addList.head.value);
4283
+ }
4284
+ break;
4285
+ }
4286
+ candidate = node.previous;
4287
+ addList.removeNode(node.value);
4288
+ pushAdd(node.value);
4289
+ }
4290
+ const payload = {
4291
+ texts: this.texts
4292
+ .map((text) => ({
4293
+ id: this.mirror.getId(text.node),
4294
+ value: text.value,
4295
+ }))
4296
+ .filter((text) => this.mirror.has(text.id)),
4297
+ attributes: this.attributes
4298
+ .map((attribute) => ({
4299
+ id: this.mirror.getId(attribute.node),
4300
+ attributes: attribute.attributes,
4301
+ }))
4302
+ .filter((attribute) => this.mirror.has(attribute.id)),
4303
+ removes: this.removes,
4304
+ adds,
4305
+ };
4306
+ if (!payload.texts.length &&
4307
+ !payload.attributes.length &&
4308
+ !payload.removes.length &&
4309
+ !payload.adds.length) {
4310
+ return;
4311
+ }
4312
+ this.texts = [];
4313
+ this.attributes = [];
4314
+ this.removes = [];
4315
+ this.addedSet = new Set();
4316
+ this.movedSet = new Set();
4317
+ this.droppedSet = new Set();
4318
+ this.movedMap = {};
4319
+ this.mutationCb(payload);
4320
+ };
4321
+ this.processMutation = (m) => {
4322
+ if (isIgnored(m.target, this.mirror)) {
4323
+ return;
4324
+ }
4325
+ switch (m.type) {
4326
+ case 'characterData': {
4327
+ const value = m.target.textContent;
4328
+ if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) &&
4329
+ value !== m.oldValue) {
4330
+ this.texts.push({
4331
+ value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector) && value
4332
+ ? this.maskTextFn
4333
+ ? this.maskTextFn(value)
4334
+ : value.replace(/[\S]/g, '*')
4335
+ : value,
4336
+ node: m.target,
4337
+ });
4338
+ }
4339
+ break;
4340
+ }
4341
+ case 'attributes': {
4342
+ const target = m.target;
4343
+ let value = m.target.getAttribute(m.attributeName);
4344
+ if (m.attributeName === 'value') {
4345
+ value = maskInputValue({
4346
+ maskInputOptions: this.maskInputOptions,
4347
+ tagName: m.target.tagName,
4348
+ type: m.target.getAttribute('type'),
4349
+ value,
4350
+ maskInputFn: this.maskInputFn,
4351
+ });
4352
+ }
4353
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||
4354
+ value === m.oldValue) {
4355
+ return;
4356
+ }
4357
+ let item = this.attributes.find((a) => a.node === m.target);
4358
+ if (target.tagName === 'IFRAME' &&
4359
+ m.attributeName === 'src' &&
4360
+ !this.keepIframeSrcFn(value)) {
4361
+ if (!target.contentDocument) {
4362
+ m.attributeName = 'rr_src';
4363
+ }
4364
+ else {
4365
+ return;
4366
+ }
4367
+ }
4368
+ if (!item) {
4369
+ item = {
4370
+ node: m.target,
4371
+ attributes: {},
4372
+ };
4373
+ this.attributes.push(item);
4374
+ }
4375
+ if (m.attributeName === 'style') {
4376
+ const old = this.doc.createElement('span');
4377
+ if (m.oldValue) {
4378
+ old.setAttribute('style', m.oldValue);
4379
+ }
4380
+ if (item.attributes.style === undefined ||
4381
+ item.attributes.style === null) {
4382
+ item.attributes.style = {};
4383
+ }
4384
+ const styleObj = item.attributes.style;
4385
+ for (const pname of Array.from(target.style)) {
4386
+ const newValue = target.style.getPropertyValue(pname);
4387
+ const newPriority = target.style.getPropertyPriority(pname);
4388
+ if (newValue !== old.style.getPropertyValue(pname) ||
4389
+ newPriority !== old.style.getPropertyPriority(pname)) {
4390
+ if (newPriority === '') {
4391
+ styleObj[pname] = newValue;
4392
+ }
4393
+ else {
4394
+ styleObj[pname] = [newValue, newPriority];
4395
+ }
4396
+ }
4397
+ }
4398
+ for (const pname of Array.from(old.style)) {
4399
+ if (target.style.getPropertyValue(pname) === '') {
4400
+ styleObj[pname] = false;
4401
+ }
4402
+ }
4403
+ }
4404
+ else {
4405
+ item.attributes[m.attributeName] = transformAttribute(this.doc, target.tagName, m.attributeName, value);
4406
+ }
4407
+ break;
4408
+ }
4409
+ case 'childList': {
4410
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, true))
4411
+ return;
4412
+ m.addedNodes.forEach((n) => this.genAdds(n, m.target));
4413
+ m.removedNodes.forEach((n) => {
4414
+ const nodeId = this.mirror.getId(n);
4415
+ const parentId = isShadowRoot(m.target)
4416
+ ? this.mirror.getId(m.target.host)
4417
+ : this.mirror.getId(m.target);
4418
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||
4419
+ isIgnored(n, this.mirror) ||
4420
+ !isSerialized(n, this.mirror)) {
4421
+ return;
4422
+ }
4423
+ if (this.addedSet.has(n)) {
4424
+ deepDelete(this.addedSet, n);
4425
+ this.droppedSet.add(n);
4426
+ }
4427
+ else if (this.addedSet.has(m.target) && nodeId === -1) ;
4428
+ else if (isAncestorRemoved(m.target, this.mirror)) ;
4429
+ else if (this.movedSet.has(n) &&
4430
+ this.movedMap[moveKey(nodeId, parentId)]) {
4431
+ deepDelete(this.movedSet, n);
4432
+ }
4433
+ else {
4434
+ this.removes.push({
4435
+ parentId,
4436
+ id: nodeId,
4437
+ isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)
4438
+ ? true
4439
+ : undefined,
4440
+ });
4441
+ }
4442
+ this.mapRemoves.push(n);
4443
+ });
4444
+ break;
4445
+ }
4446
+ }
4447
+ };
4448
+ this.genAdds = (n, target) => {
4449
+ if (this.mirror.hasNode(n)) {
4450
+ if (isIgnored(n, this.mirror)) {
4451
+ return;
4452
+ }
4453
+ this.movedSet.add(n);
4454
+ let targetId = null;
4455
+ if (target && this.mirror.hasNode(target)) {
4456
+ targetId = this.mirror.getId(target);
4457
+ }
4458
+ if (targetId && targetId !== -1) {
4459
+ this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;
4460
+ }
4461
+ }
4462
+ else {
4463
+ this.addedSet.add(n);
4464
+ this.droppedSet.delete(n);
4465
+ }
4466
+ if (!isBlocked(n, this.blockClass, this.blockSelector, false))
4467
+ n.childNodes.forEach((childN) => this.genAdds(childN));
4468
+ };
4469
+ }
4470
+ init(options) {
4471
+ [
4472
+ 'mutationCb',
4473
+ 'blockClass',
4474
+ 'blockSelector',
4475
+ 'maskTextClass',
4476
+ 'maskTextSelector',
4477
+ 'inlineStylesheet',
4478
+ 'maskInputOptions',
4479
+ 'maskTextFn',
4480
+ 'maskInputFn',
4481
+ 'keepIframeSrcFn',
4482
+ 'recordCanvas',
4483
+ 'inlineImages',
4484
+ 'slimDOMOptions',
4485
+ 'dataURLOptions',
4486
+ 'doc',
4487
+ 'mirror',
4488
+ 'iframeManager',
4489
+ 'stylesheetManager',
4490
+ 'shadowDomManager',
4491
+ 'canvasManager',
4492
+ ].forEach((key) => {
4493
+ this[key] = options[key];
4494
+ });
4495
+ }
4496
+ freeze() {
4497
+ this.frozen = true;
4498
+ this.canvasManager.freeze();
4499
+ }
4500
+ unfreeze() {
4501
+ this.frozen = false;
4502
+ this.canvasManager.unfreeze();
4503
+ this.emit();
4504
+ }
4505
+ isFrozen() {
4506
+ return this.frozen;
4507
+ }
4508
+ lock() {
4509
+ this.locked = true;
4510
+ this.canvasManager.lock();
4511
+ }
4512
+ unlock() {
4513
+ this.locked = false;
4514
+ this.canvasManager.unlock();
4515
+ this.emit();
4516
+ }
4517
+ reset() {
4518
+ this.shadowDomManager.reset();
4519
+ this.canvasManager.reset();
4520
+ }
4521
+ }
4522
+ function deepDelete(addsSet, n) {
4523
+ addsSet.delete(n);
4524
+ n.childNodes.forEach((childN) => deepDelete(addsSet, childN));
4525
+ }
4526
+ function isParentRemoved(removes, n, mirror) {
4527
+ if (removes.length === 0)
4528
+ return false;
4529
+ return _isParentRemoved(removes, n, mirror);
4530
+ }
4531
+ function _isParentRemoved(removes, n, mirror) {
4532
+ const { parentNode } = n;
4533
+ if (!parentNode) {
4534
+ return false;
4535
+ }
4536
+ const parentId = mirror.getId(parentNode);
4537
+ if (removes.some((r) => r.id === parentId)) {
4538
+ return true;
4539
+ }
4540
+ return _isParentRemoved(removes, parentNode, mirror);
4541
+ }
4542
+ function isAncestorInSet(set, n) {
4543
+ if (set.size === 0)
4544
+ return false;
4545
+ return _isAncestorInSet(set, n);
4546
+ }
4547
+ function _isAncestorInSet(set, n) {
4548
+ const { parentNode } = n;
4549
+ if (!parentNode) {
4550
+ return false;
4551
+ }
4552
+ if (set.has(parentNode)) {
4553
+ return true;
4554
+ }
4555
+ return _isAncestorInSet(set, parentNode);
4556
+ }
4557
+
4558
+ const mutationBuffers = [];
4559
+ const isCSSGroupingRuleSupported = typeof CSSGroupingRule !== 'undefined';
4560
+ const isCSSMediaRuleSupported = typeof CSSMediaRule !== 'undefined';
4561
+ const isCSSSupportsRuleSupported = typeof CSSSupportsRule !== 'undefined';
4562
+ const isCSSConditionRuleSupported = typeof CSSConditionRule !== 'undefined';
4563
+ function getEventTarget(event) {
4564
+ try {
4565
+ if ('composedPath' in event) {
4566
+ const path = event.composedPath();
4567
+ if (path.length) {
4568
+ return path[0];
4569
+ }
4570
+ }
4571
+ else if ('path' in event && event.path.length) {
4572
+ return event.path[0];
4573
+ }
4574
+ return event.target;
4575
+ }
4576
+ catch (_a) {
4577
+ return event.target;
4578
+ }
4579
+ }
4580
+ function initMutationObserver(options, rootEl) {
4581
+ var _a, _b;
4582
+ const mutationBuffer = new MutationBuffer();
4583
+ mutationBuffers.push(mutationBuffer);
4584
+ mutationBuffer.init(options);
4585
+ let mutationObserverCtor = window.MutationObserver ||
4586
+ window.__rrMutationObserver;
4587
+ const angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');
4588
+ if (angularZoneSymbol &&
4589
+ window[angularZoneSymbol]) {
4590
+ mutationObserverCtor = window[angularZoneSymbol];
4591
+ }
4592
+ const observer = new mutationObserverCtor(mutationBuffer.processMutations.bind(mutationBuffer));
4593
+ observer.observe(rootEl, {
4594
+ attributes: true,
4595
+ attributeOldValue: true,
4596
+ characterData: true,
4597
+ characterDataOldValue: true,
4598
+ childList: true,
4599
+ subtree: true,
4600
+ });
4601
+ return observer;
4602
+ }
4603
+ function initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {
4604
+ if (sampling.mousemove === false) {
4605
+ return () => {
4606
+ };
4607
+ }
4608
+ const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;
4609
+ const callbackThreshold = typeof sampling.mousemoveCallback === 'number'
4610
+ ? sampling.mousemoveCallback
4611
+ : 500;
4612
+ let positions = [];
4613
+ let timeBaseline;
4614
+ const wrappedCb = throttle((source) => {
4615
+ const totalOffset = Date.now() - timeBaseline;
4616
+ mousemoveCb(positions.map((p) => {
4617
+ p.timeOffset -= totalOffset;
4618
+ return p;
4619
+ }), source);
4620
+ positions = [];
4621
+ timeBaseline = null;
4622
+ }, callbackThreshold);
4623
+ const updatePosition = throttle((evt) => {
4624
+ const target = getEventTarget(evt);
4625
+ const { clientX, clientY } = isTouchEvent(evt)
4626
+ ? evt.changedTouches[0]
4627
+ : evt;
4628
+ if (!timeBaseline) {
4629
+ timeBaseline = Date.now();
4630
+ }
4631
+ positions.push({
4632
+ x: clientX,
4633
+ y: clientY,
4634
+ id: mirror.getId(target),
4635
+ timeOffset: Date.now() - timeBaseline,
4636
+ });
4637
+ wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent
4638
+ ? IncrementalSource.Drag
4639
+ : evt instanceof MouseEvent
4640
+ ? IncrementalSource.MouseMove
4641
+ : IncrementalSource.TouchMove);
4642
+ }, threshold, {
4643
+ trailing: false,
4644
+ });
4645
+ const handlers = [
4646
+ on('mousemove', updatePosition, doc),
4647
+ on('touchmove', updatePosition, doc),
4648
+ on('drag', updatePosition, doc),
4649
+ ];
4650
+ return () => {
4651
+ handlers.forEach((h) => h());
4652
+ };
4653
+ }
4654
+ function initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, sampling, }) {
4655
+ if (sampling.mouseInteraction === false) {
4656
+ return () => {
4657
+ };
4658
+ }
4659
+ const disableMap = sampling.mouseInteraction === true ||
4660
+ sampling.mouseInteraction === undefined
4661
+ ? {}
4662
+ : sampling.mouseInteraction;
4663
+ const handlers = [];
4664
+ const getHandler = (eventKey) => {
4665
+ return (event) => {
4666
+ const target = getEventTarget(event);
4667
+ if (isBlocked(target, blockClass, blockSelector, true)) {
4668
+ return;
4669
+ }
4670
+ const e = isTouchEvent(event) ? event.changedTouches[0] : event;
4671
+ if (!e) {
4672
+ return;
4673
+ }
4674
+ const id = mirror.getId(target);
4675
+ const { clientX, clientY } = e;
4676
+ mouseInteractionCb({
4677
+ type: MouseInteractions[eventKey],
4678
+ id,
4679
+ x: clientX,
4680
+ y: clientY,
4681
+ });
4682
+ };
4683
+ };
4684
+ Object.keys(MouseInteractions)
4685
+ .filter((key) => Number.isNaN(Number(key)) &&
4686
+ !key.endsWith('_Departed') &&
4687
+ disableMap[key] !== false)
4688
+ .forEach((eventKey) => {
4689
+ const eventName = eventKey.toLowerCase();
4690
+ const handler = getHandler(eventKey);
4691
+ handlers.push(on(eventName, handler, doc));
4692
+ });
4693
+ return () => {
4694
+ handlers.forEach((h) => h());
4695
+ };
4696
+ }
4697
+ function initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, sampling, }) {
4698
+ const updatePosition = throttle((evt) => {
4699
+ const target = getEventTarget(evt);
4700
+ if (!target || isBlocked(target, blockClass, blockSelector, true)) {
4701
+ return;
4702
+ }
4703
+ const id = mirror.getId(target);
4704
+ if (target === doc) {
4705
+ const scrollEl = (doc.scrollingElement || doc.documentElement);
4706
+ scrollCb({
4707
+ id,
4708
+ x: scrollEl.scrollLeft,
4709
+ y: scrollEl.scrollTop,
4710
+ });
4711
+ }
4712
+ else {
4713
+ scrollCb({
4714
+ id,
4715
+ x: target.scrollLeft,
4716
+ y: target.scrollTop,
4717
+ });
4718
+ }
4719
+ }, sampling.scroll || 100);
4720
+ return on('scroll', updatePosition, doc);
4721
+ }
4722
+ function initViewportResizeObserver({ viewportResizeCb, }) {
4723
+ let lastH = -1;
4724
+ let lastW = -1;
4725
+ const updateDimension = throttle(() => {
4726
+ const height = getWindowHeight();
4727
+ const width = getWindowWidth();
4728
+ if (lastH !== height || lastW !== width) {
4729
+ viewportResizeCb({
4730
+ width: Number(width),
4731
+ height: Number(height),
4732
+ });
4733
+ lastH = height;
4734
+ lastW = width;
4735
+ }
4736
+ }, 200);
4737
+ return on('resize', updateDimension, window);
4738
+ }
4739
+ function wrapEventWithUserTriggeredFlag(v, enable) {
4740
+ const value = Object.assign({}, v);
4741
+ if (!enable)
4742
+ delete value.userTriggered;
4743
+ return value;
4744
+ }
4745
+ const INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];
4746
+ const lastInputValueMap = new WeakMap();
4747
+ function initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, ignoreClass, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {
4748
+ function eventHandler(event) {
4749
+ let target = getEventTarget(event);
4750
+ const userTriggered = event.isTrusted;
4751
+ if (target && target.tagName === 'OPTION')
4752
+ target = target.parentElement;
4753
+ if (!target ||
4754
+ !target.tagName ||
4755
+ INPUT_TAGS.indexOf(target.tagName) < 0 ||
4756
+ isBlocked(target, blockClass, blockSelector, true)) {
4757
+ return;
4758
+ }
4759
+ const type = target.type;
4760
+ if (target.classList.contains(ignoreClass)) {
4761
+ return;
4762
+ }
4763
+ let text = target.value;
4764
+ let isChecked = false;
4765
+ if (type === 'radio' || type === 'checkbox') {
4766
+ isChecked = target.checked;
4767
+ }
4768
+ else if (maskInputOptions[target.tagName.toLowerCase()] ||
4769
+ maskInputOptions[type]) {
4770
+ text = maskInputValue({
4771
+ maskInputOptions,
4772
+ tagName: target.tagName,
4773
+ type,
4774
+ value: text,
4775
+ maskInputFn,
4776
+ });
4777
+ }
4778
+ cbWithDedup(target, wrapEventWithUserTriggeredFlag({ text, isChecked, userTriggered }, userTriggeredOnInput));
4779
+ const name = target.name;
4780
+ if (type === 'radio' && name && isChecked) {
4781
+ doc
4782
+ .querySelectorAll(`input[type="radio"][name="${name}"]`)
4783
+ .forEach((el) => {
4784
+ if (el !== target) {
4785
+ cbWithDedup(el, wrapEventWithUserTriggeredFlag({
4786
+ text: el.value,
4787
+ isChecked: !isChecked,
4788
+ userTriggered: false,
4789
+ }, userTriggeredOnInput));
4790
+ }
4791
+ });
4792
+ }
4793
+ }
4794
+ function cbWithDedup(target, v) {
4795
+ const lastInputValue = lastInputValueMap.get(target);
4796
+ if (!lastInputValue ||
4797
+ lastInputValue.text !== v.text ||
4798
+ lastInputValue.isChecked !== v.isChecked) {
4799
+ lastInputValueMap.set(target, v);
4800
+ const id = mirror.getId(target);
4801
+ inputCb(Object.assign(Object.assign({}, v), { id }));
4802
+ }
4803
+ }
4804
+ const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];
4805
+ const handlers = events.map((eventName) => on(eventName, eventHandler, doc));
4806
+ const currentWindow = doc.defaultView;
4807
+ if (!currentWindow) {
4808
+ return () => {
4809
+ handlers.forEach((h) => h());
4810
+ };
4811
+ }
4812
+ const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');
4813
+ const hookProperties = [
4814
+ [currentWindow.HTMLInputElement.prototype, 'value'],
4815
+ [currentWindow.HTMLInputElement.prototype, 'checked'],
4816
+ [currentWindow.HTMLSelectElement.prototype, 'value'],
4817
+ [currentWindow.HTMLTextAreaElement.prototype, 'value'],
4818
+ [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],
4819
+ [currentWindow.HTMLOptionElement.prototype, 'selected'],
4820
+ ];
4821
+ if (propertyDescriptor && propertyDescriptor.set) {
4822
+ handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {
4823
+ set() {
4824
+ eventHandler({ target: this });
4825
+ },
4826
+ }, false, currentWindow)));
4827
+ }
4828
+ return () => {
4829
+ handlers.forEach((h) => h());
4830
+ };
4831
+ }
4832
+ function getNestedCSSRulePositions(rule) {
4833
+ const positions = [];
4834
+ function recurse(childRule, pos) {
4835
+ if ((isCSSGroupingRuleSupported &&
4836
+ childRule.parentRule instanceof CSSGroupingRule) ||
4837
+ (isCSSMediaRuleSupported &&
4838
+ childRule.parentRule instanceof CSSMediaRule) ||
4839
+ (isCSSSupportsRuleSupported &&
4840
+ childRule.parentRule instanceof CSSSupportsRule) ||
4841
+ (isCSSConditionRuleSupported &&
4842
+ childRule.parentRule instanceof CSSConditionRule)) {
4843
+ const rules = Array.from(childRule.parentRule.cssRules);
4844
+ const index = rules.indexOf(childRule);
4845
+ pos.unshift(index);
4846
+ }
4847
+ else if (childRule.parentStyleSheet) {
4848
+ const rules = Array.from(childRule.parentStyleSheet.cssRules);
4849
+ const index = rules.indexOf(childRule);
4850
+ pos.unshift(index);
4851
+ }
4852
+ return pos;
4853
+ }
4854
+ return recurse(rule, positions);
4855
+ }
4856
+ function getIdAndStyleId(sheet, mirror, styleMirror) {
4857
+ let id, styleId;
4858
+ if (!sheet)
4859
+ return {};
4860
+ if (sheet.ownerNode)
4861
+ id = mirror.getId(sheet.ownerNode);
4862
+ else
4863
+ styleId = styleMirror.getId(sheet);
4864
+ return {
4865
+ styleId,
4866
+ id,
4867
+ };
4868
+ }
4869
+ function initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {
4870
+ const insertRule = win.CSSStyleSheet.prototype.insertRule;
4871
+ win.CSSStyleSheet.prototype.insertRule = function (rule, index) {
4872
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
4873
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
4874
+ styleSheetRuleCb({
4875
+ id,
4876
+ styleId,
4877
+ adds: [{ rule, index }],
4878
+ });
4879
+ }
4880
+ return insertRule.apply(this, [rule, index]);
4881
+ };
4882
+ const deleteRule = win.CSSStyleSheet.prototype.deleteRule;
4883
+ win.CSSStyleSheet.prototype.deleteRule = function (index) {
4884
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
4885
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
4886
+ styleSheetRuleCb({
4887
+ id,
4888
+ styleId,
4889
+ removes: [{ index }],
4890
+ });
4891
+ }
4892
+ return deleteRule.apply(this, [index]);
4893
+ };
4894
+ let replace;
4895
+ if (win.CSSStyleSheet.prototype.replace) {
4896
+ replace = win.CSSStyleSheet.prototype.replace;
4897
+ win.CSSStyleSheet.prototype.replace = function (text) {
4898
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
4899
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
4900
+ styleSheetRuleCb({
4901
+ id,
4902
+ styleId,
4903
+ replace: text,
4904
+ });
4905
+ }
4906
+ return replace.apply(this, [text]);
4907
+ };
4908
+ }
4909
+ let replaceSync;
4910
+ if (win.CSSStyleSheet.prototype.replaceSync) {
4911
+ replaceSync = win.CSSStyleSheet.prototype.replaceSync;
4912
+ win.CSSStyleSheet.prototype.replaceSync = function (text) {
4913
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
4914
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
4915
+ styleSheetRuleCb({
4916
+ id,
4917
+ styleId,
4918
+ replaceSync: text,
4919
+ });
4920
+ }
4921
+ return replaceSync.apply(this, [text]);
4922
+ };
4923
+ }
4924
+ const supportedNestedCSSRuleTypes = {};
4925
+ if (isCSSGroupingRuleSupported) {
4926
+ supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
4927
+ }
4928
+ else {
4929
+ if (isCSSMediaRuleSupported) {
4930
+ supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
4931
+ }
4932
+ if (isCSSConditionRuleSupported) {
4933
+ supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
4934
+ }
4935
+ if (isCSSSupportsRuleSupported) {
4936
+ supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
4937
+ }
4938
+ }
4939
+ const unmodifiedFunctions = {};
4940
+ Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
4941
+ unmodifiedFunctions[typeKey] = {
4942
+ insertRule: type.prototype.insertRule,
4943
+ deleteRule: type.prototype.deleteRule,
4944
+ };
4945
+ type.prototype.insertRule = function (rule, index) {
4946
+ const { id, styleId } = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
4947
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
4948
+ styleSheetRuleCb({
4949
+ id,
4950
+ styleId,
4951
+ adds: [
4952
+ {
4953
+ rule,
4954
+ index: [
4955
+ ...getNestedCSSRulePositions(this),
4956
+ index || 0,
4957
+ ],
4958
+ },
4959
+ ],
4960
+ });
4961
+ }
4962
+ return unmodifiedFunctions[typeKey].insertRule.apply(this, [rule, index]);
4963
+ };
4964
+ type.prototype.deleteRule = function (index) {
4965
+ const { id, styleId } = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
4966
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
4967
+ styleSheetRuleCb({
4968
+ id,
4969
+ styleId,
4970
+ removes: [
4971
+ { index: [...getNestedCSSRulePositions(this), index] },
4972
+ ],
4973
+ });
4974
+ }
4975
+ return unmodifiedFunctions[typeKey].deleteRule.apply(this, [index]);
4976
+ };
4977
+ });
4978
+ return () => {
4979
+ win.CSSStyleSheet.prototype.insertRule = insertRule;
4980
+ win.CSSStyleSheet.prototype.deleteRule = deleteRule;
4981
+ replace && (win.CSSStyleSheet.prototype.replace = replace);
4982
+ replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
4983
+ Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
4984
+ type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
4985
+ type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
4986
+ });
4987
+ };
4988
+ }
4989
+ function initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {
4990
+ var _a, _b, _c;
4991
+ let hostId = null;
4992
+ if (host.nodeName === '#document')
4993
+ hostId = mirror.getId(host);
4994
+ else
4995
+ hostId = mirror.getId(host.host);
4996
+ const patchTarget = host.nodeName === '#document'
4997
+ ? (_a = host.defaultView) === null || _a === void 0 ? void 0 : _a.Document
4998
+ : (_c = (_b = host.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView) === null || _c === void 0 ? void 0 : _c.ShadowRoot;
4999
+ const originalPropertyDescriptor = Object.getOwnPropertyDescriptor(patchTarget === null || patchTarget === void 0 ? void 0 : patchTarget.prototype, 'adoptedStyleSheets');
5000
+ if (hostId === null ||
5001
+ hostId === -1 ||
5002
+ !patchTarget ||
5003
+ !originalPropertyDescriptor)
5004
+ return () => {
5005
+ };
5006
+ Object.defineProperty(host, 'adoptedStyleSheets', {
5007
+ configurable: originalPropertyDescriptor.configurable,
5008
+ enumerable: originalPropertyDescriptor.enumerable,
5009
+ get() {
5010
+ var _a;
5011
+ return (_a = originalPropertyDescriptor.get) === null || _a === void 0 ? void 0 : _a.call(this);
5012
+ },
5013
+ set(sheets) {
5014
+ var _a;
5015
+ const result = (_a = originalPropertyDescriptor.set) === null || _a === void 0 ? void 0 : _a.call(this, sheets);
5016
+ if (hostId !== null && hostId !== -1) {
5017
+ try {
5018
+ stylesheetManager.adoptStyleSheets(sheets, hostId);
5019
+ }
5020
+ catch (e) {
5021
+ }
5022
+ }
5023
+ return result;
5024
+ },
5025
+ });
5026
+ return () => {
5027
+ Object.defineProperty(host, 'adoptedStyleSheets', {
5028
+ configurable: originalPropertyDescriptor.configurable,
5029
+ enumerable: originalPropertyDescriptor.enumerable,
5030
+ get: originalPropertyDescriptor.get,
5031
+ set: originalPropertyDescriptor.set,
5032
+ });
5033
+ };
5034
+ }
5035
+ function initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {
5036
+ const setProperty = win.CSSStyleDeclaration.prototype.setProperty;
5037
+ win.CSSStyleDeclaration.prototype.setProperty = function (property, value, priority) {
5038
+ var _a;
5039
+ if (ignoreCSSAttributes.has(property)) {
5040
+ return setProperty.apply(this, [property, value, priority]);
5041
+ }
5042
+ const { id, styleId } = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
5043
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
5044
+ styleDeclarationCb({
5045
+ id,
5046
+ styleId,
5047
+ set: {
5048
+ property,
5049
+ value,
5050
+ priority,
5051
+ },
5052
+ index: getNestedCSSRulePositions(this.parentRule),
5053
+ });
5054
+ }
5055
+ return setProperty.apply(this, [property, value, priority]);
5056
+ };
5057
+ const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
5058
+ win.CSSStyleDeclaration.prototype.removeProperty = function (property) {
5059
+ var _a;
5060
+ if (ignoreCSSAttributes.has(property)) {
5061
+ return removeProperty.apply(this, [property]);
5062
+ }
5063
+ const { id, styleId } = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
5064
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
5065
+ styleDeclarationCb({
5066
+ id,
5067
+ styleId,
5068
+ remove: {
5069
+ property,
5070
+ },
5071
+ index: getNestedCSSRulePositions(this.parentRule),
5072
+ });
5073
+ }
5074
+ return removeProperty.apply(this, [property]);
5075
+ };
5076
+ return () => {
5077
+ win.CSSStyleDeclaration.prototype.setProperty = setProperty;
5078
+ win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
5079
+ };
5080
+ }
5081
+ function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, mirror, sampling, }) {
5082
+ const handler = (type) => throttle((event) => {
5083
+ const target = getEventTarget(event);
5084
+ if (!target ||
5085
+ isBlocked(target, blockClass, blockSelector, true)) {
5086
+ return;
5087
+ }
5088
+ const { currentTime, volume, muted, playbackRate, } = target;
5089
+ mediaInteractionCb({
5090
+ type,
5091
+ id: mirror.getId(target),
5092
+ currentTime,
5093
+ volume,
5094
+ muted,
5095
+ playbackRate,
5096
+ });
5097
+ }, sampling.media || 500);
5098
+ const handlers = [
5099
+ on('play', handler(0)),
5100
+ on('pause', handler(1)),
5101
+ on('seeked', handler(2)),
5102
+ on('volumechange', handler(3)),
5103
+ on('ratechange', handler(4)),
5104
+ ];
5105
+ return () => {
5106
+ handlers.forEach((h) => h());
5107
+ };
5108
+ }
5109
+ function initFontObserver({ fontCb, doc }) {
5110
+ const win = doc.defaultView;
5111
+ if (!win) {
5112
+ return () => {
5113
+ };
5114
+ }
5115
+ const handlers = [];
5116
+ const fontMap = new WeakMap();
5117
+ const originalFontFace = win.FontFace;
5118
+ win.FontFace = function FontFace(family, source, descriptors) {
5119
+ const fontFace = new originalFontFace(family, source, descriptors);
5120
+ fontMap.set(fontFace, {
5121
+ family,
5122
+ buffer: typeof source !== 'string',
5123
+ descriptors,
5124
+ fontSource: typeof source === 'string'
5125
+ ? source
5126
+ : JSON.stringify(Array.from(new Uint8Array(source))),
5127
+ });
5128
+ return fontFace;
5129
+ };
5130
+ const restoreHandler = patch(doc.fonts, 'add', function (original) {
5131
+ return function (fontFace) {
5132
+ setTimeout(() => {
5133
+ const p = fontMap.get(fontFace);
5134
+ if (p) {
5135
+ fontCb(p);
5136
+ fontMap.delete(fontFace);
5137
+ }
5138
+ }, 0);
5139
+ return original.apply(this, [fontFace]);
5140
+ };
5141
+ });
5142
+ handlers.push(() => {
5143
+ win.FontFace = originalFontFace;
5144
+ });
5145
+ handlers.push(restoreHandler);
5146
+ return () => {
5147
+ handlers.forEach((h) => h());
5148
+ };
5149
+ }
5150
+ function initSelectionObserver(param) {
5151
+ const { doc, mirror, blockClass, blockSelector, selectionCb } = param;
5152
+ let collapsed = true;
5153
+ const updateSelection = () => {
5154
+ const selection = doc.getSelection();
5155
+ if (!selection || (collapsed && (selection === null || selection === void 0 ? void 0 : selection.isCollapsed)))
5156
+ return;
5157
+ collapsed = selection.isCollapsed || false;
5158
+ const ranges = [];
5159
+ const count = selection.rangeCount || 0;
5160
+ for (let i = 0; i < count; i++) {
5161
+ const range = selection.getRangeAt(i);
5162
+ const { startContainer, startOffset, endContainer, endOffset } = range;
5163
+ const blocked = isBlocked(startContainer, blockClass, blockSelector, true) ||
5164
+ isBlocked(endContainer, blockClass, blockSelector, true);
5165
+ if (blocked)
5166
+ continue;
5167
+ ranges.push({
5168
+ start: mirror.getId(startContainer),
5169
+ startOffset,
5170
+ end: mirror.getId(endContainer),
5171
+ endOffset,
5172
+ });
5173
+ }
5174
+ selectionCb({ ranges });
5175
+ };
5176
+ updateSelection();
5177
+ return on('selectionchange', updateSelection);
5178
+ }
5179
+ function mergeHooks(o, hooks) {
5180
+ const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, selectionCb, } = o;
5181
+ o.mutationCb = (...p) => {
5182
+ if (hooks.mutation) {
5183
+ hooks.mutation(...p);
5184
+ }
5185
+ mutationCb(...p);
5186
+ };
5187
+ o.mousemoveCb = (...p) => {
5188
+ if (hooks.mousemove) {
5189
+ hooks.mousemove(...p);
5190
+ }
5191
+ mousemoveCb(...p);
5192
+ };
5193
+ o.mouseInteractionCb = (...p) => {
5194
+ if (hooks.mouseInteraction) {
5195
+ hooks.mouseInteraction(...p);
5196
+ }
5197
+ mouseInteractionCb(...p);
5198
+ };
5199
+ o.scrollCb = (...p) => {
5200
+ if (hooks.scroll) {
5201
+ hooks.scroll(...p);
5202
+ }
5203
+ scrollCb(...p);
5204
+ };
5205
+ o.viewportResizeCb = (...p) => {
5206
+ if (hooks.viewportResize) {
5207
+ hooks.viewportResize(...p);
5208
+ }
5209
+ viewportResizeCb(...p);
5210
+ };
5211
+ o.inputCb = (...p) => {
5212
+ if (hooks.input) {
5213
+ hooks.input(...p);
5214
+ }
5215
+ inputCb(...p);
5216
+ };
5217
+ o.mediaInteractionCb = (...p) => {
5218
+ if (hooks.mediaInteaction) {
5219
+ hooks.mediaInteaction(...p);
5220
+ }
5221
+ mediaInteractionCb(...p);
5222
+ };
5223
+ o.styleSheetRuleCb = (...p) => {
5224
+ if (hooks.styleSheetRule) {
5225
+ hooks.styleSheetRule(...p);
5226
+ }
5227
+ styleSheetRuleCb(...p);
5228
+ };
5229
+ o.styleDeclarationCb = (...p) => {
5230
+ if (hooks.styleDeclaration) {
5231
+ hooks.styleDeclaration(...p);
5232
+ }
5233
+ styleDeclarationCb(...p);
5234
+ };
5235
+ o.canvasMutationCb = (...p) => {
5236
+ if (hooks.canvasMutation) {
5237
+ hooks.canvasMutation(...p);
5238
+ }
5239
+ canvasMutationCb(...p);
5240
+ };
5241
+ o.fontCb = (...p) => {
5242
+ if (hooks.font) {
5243
+ hooks.font(...p);
5244
+ }
5245
+ fontCb(...p);
5246
+ };
5247
+ o.selectionCb = (...p) => {
5248
+ if (hooks.selection) {
5249
+ hooks.selection(...p);
5250
+ }
5251
+ selectionCb(...p);
5252
+ };
5253
+ }
5254
+ function initObservers(o, hooks = {}) {
5255
+ const currentWindow = o.doc.defaultView;
5256
+ if (!currentWindow) {
5257
+ return () => {
5258
+ };
5259
+ }
5260
+ mergeHooks(o, hooks);
5261
+ const mutationObserver = initMutationObserver(o, o.doc);
5262
+ const mousemoveHandler = initMoveObserver(o);
5263
+ const mouseInteractionHandler = initMouseInteractionObserver(o);
5264
+ const scrollHandler = initScrollObserver(o);
5265
+ const viewportResizeHandler = initViewportResizeObserver(o);
5266
+ const inputHandler = initInputObserver(o);
5267
+ const mediaInteractionHandler = initMediaInteractionObserver(o);
5268
+ const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });
5269
+ const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);
5270
+ const styleDeclarationObserver = initStyleDeclarationObserver(o, {
5271
+ win: currentWindow,
5272
+ });
5273
+ const fontObserver = o.collectFonts
5274
+ ? initFontObserver(o)
5275
+ : () => {
5276
+ };
5277
+ const selectionObserver = initSelectionObserver(o);
5278
+ const pluginHandlers = [];
5279
+ for (const plugin of o.plugins) {
5280
+ pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));
5281
+ }
5282
+ return () => {
5283
+ mutationBuffers.forEach((b) => b.reset());
5284
+ mutationObserver.disconnect();
5285
+ mousemoveHandler();
5286
+ mouseInteractionHandler();
5287
+ scrollHandler();
5288
+ viewportResizeHandler();
5289
+ inputHandler();
5290
+ mediaInteractionHandler();
5291
+ styleSheetObserver();
5292
+ adoptedStyleSheetObserver();
5293
+ styleDeclarationObserver();
5294
+ fontObserver();
5295
+ selectionObserver();
5296
+ pluginHandlers.forEach((h) => h());
5297
+ };
5298
+ }
5299
+
5300
+ class CrossOriginIframeMirror {
5301
+ constructor(generateIdFn) {
5302
+ this.generateIdFn = generateIdFn;
5303
+ this.iframeIdToRemoteIdMap = new WeakMap();
5304
+ this.iframeRemoteIdToIdMap = new WeakMap();
5305
+ }
5306
+ getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
5307
+ const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
5308
+ const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
5309
+ let id = idToRemoteIdMap.get(remoteId);
5310
+ if (!id) {
5311
+ id = this.generateIdFn();
5312
+ idToRemoteIdMap.set(remoteId, id);
5313
+ remoteIdToIdMap.set(id, remoteId);
5314
+ }
5315
+ return id;
5316
+ }
5317
+ getIds(iframe, remoteId) {
5318
+ const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
5319
+ const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
5320
+ return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));
5321
+ }
5322
+ getRemoteId(iframe, id, map) {
5323
+ const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
5324
+ if (typeof id !== 'number')
5325
+ return id;
5326
+ const remoteId = remoteIdToIdMap.get(id);
5327
+ if (!remoteId)
5328
+ return -1;
5329
+ return remoteId;
5330
+ }
5331
+ getRemoteIds(iframe, ids) {
5332
+ const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
5333
+ return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));
5334
+ }
5335
+ reset(iframe) {
5336
+ if (!iframe) {
5337
+ this.iframeIdToRemoteIdMap = new WeakMap();
5338
+ this.iframeRemoteIdToIdMap = new WeakMap();
5339
+ return;
5340
+ }
5341
+ this.iframeIdToRemoteIdMap.delete(iframe);
5342
+ this.iframeRemoteIdToIdMap.delete(iframe);
5343
+ }
5344
+ getIdToRemoteIdMap(iframe) {
5345
+ let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
5346
+ if (!idToRemoteIdMap) {
5347
+ idToRemoteIdMap = new Map();
5348
+ this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
5349
+ }
5350
+ return idToRemoteIdMap;
5351
+ }
5352
+ getRemoteIdToIdMap(iframe) {
5353
+ let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
5354
+ if (!remoteIdToIdMap) {
5355
+ remoteIdToIdMap = new Map();
5356
+ this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
5357
+ }
5358
+ return remoteIdToIdMap;
5359
+ }
5360
+ }
5361
+
5362
+ class IframeManager {
5363
+ constructor(options) {
5364
+ this.iframes = new WeakMap();
5365
+ this.crossOriginIframeMap = new WeakMap();
5366
+ this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);
5367
+ this.mutationCb = options.mutationCb;
5368
+ this.wrappedEmit = options.wrappedEmit;
5369
+ this.stylesheetManager = options.stylesheetManager;
5370
+ this.recordCrossOriginIframes = options.recordCrossOriginIframes;
5371
+ this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
5372
+ this.mirror = options.mirror;
5373
+ if (this.recordCrossOriginIframes) {
5374
+ window.addEventListener('message', this.handleMessage.bind(this));
5375
+ }
5376
+ }
5377
+ addIframe(iframeEl) {
5378
+ this.iframes.set(iframeEl, true);
5379
+ if (iframeEl.contentWindow)
5380
+ this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
5381
+ }
5382
+ addLoadListener(cb) {
5383
+ this.loadListener = cb;
5384
+ }
5385
+ attachIframe(iframeEl, childSn) {
5386
+ var _a;
5387
+ this.mutationCb({
5388
+ adds: [
5389
+ {
5390
+ parentId: this.mirror.getId(iframeEl),
5391
+ nextId: null,
5392
+ node: childSn,
5393
+ },
5394
+ ],
5395
+ removes: [],
5396
+ texts: [],
5397
+ attributes: [],
5398
+ isAttachIframe: true,
5399
+ });
5400
+ (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);
5401
+ if (iframeEl.contentDocument &&
5402
+ iframeEl.contentDocument.adoptedStyleSheets &&
5403
+ iframeEl.contentDocument.adoptedStyleSheets.length > 0)
5404
+ this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
5405
+ }
5406
+ handleMessage(message) {
5407
+ if (message.data.type === 'rrweb') {
5408
+ const iframeSourceWindow = message.source;
5409
+ if (!iframeSourceWindow)
5410
+ return;
5411
+ const iframeEl = this.crossOriginIframeMap.get(message.source);
5412
+ if (!iframeEl)
5413
+ return;
5414
+ const transformedEvent = this.transformCrossOriginEvent(iframeEl, message.data.event);
5415
+ if (transformedEvent)
5416
+ this.wrappedEmit(transformedEvent, message.data.isCheckout);
5417
+ }
5418
+ }
5419
+ transformCrossOriginEvent(iframeEl, e) {
5420
+ var _a;
5421
+ switch (e.type) {
5422
+ case EventType.FullSnapshot: {
5423
+ this.crossOriginIframeMirror.reset(iframeEl);
5424
+ this.crossOriginIframeStyleMirror.reset(iframeEl);
5425
+ this.replaceIdOnNode(e.data.node, iframeEl);
5426
+ return {
5427
+ timestamp: e.timestamp,
5428
+ type: EventType.IncrementalSnapshot,
5429
+ data: {
5430
+ source: IncrementalSource.Mutation,
5431
+ adds: [
5432
+ {
5433
+ parentId: this.mirror.getId(iframeEl),
5434
+ nextId: null,
5435
+ node: e.data.node,
5436
+ },
5437
+ ],
5438
+ removes: [],
5439
+ texts: [],
5440
+ attributes: [],
5441
+ isAttachIframe: true,
5442
+ },
5443
+ };
5444
+ }
5445
+ case EventType.Meta:
5446
+ case EventType.Load:
5447
+ case EventType.DomContentLoaded: {
5448
+ return false;
5449
+ }
5450
+ case EventType.Plugin: {
5451
+ return e;
5452
+ }
5453
+ case EventType.Custom: {
5454
+ this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);
5455
+ return e;
5456
+ }
5457
+ case EventType.IncrementalSnapshot: {
5458
+ switch (e.data.source) {
5459
+ case IncrementalSource.Mutation: {
5460
+ e.data.adds.forEach((n) => {
5461
+ this.replaceIds(n, iframeEl, [
5462
+ 'parentId',
5463
+ 'nextId',
5464
+ 'previousId',
5465
+ ]);
5466
+ this.replaceIdOnNode(n.node, iframeEl);
5467
+ });
5468
+ e.data.removes.forEach((n) => {
5469
+ this.replaceIds(n, iframeEl, ['parentId', 'id']);
5470
+ });
5471
+ e.data.attributes.forEach((n) => {
5472
+ this.replaceIds(n, iframeEl, ['id']);
5473
+ });
5474
+ e.data.texts.forEach((n) => {
5475
+ this.replaceIds(n, iframeEl, ['id']);
5476
+ });
5477
+ return e;
5478
+ }
5479
+ case IncrementalSource.Drag:
5480
+ case IncrementalSource.TouchMove:
5481
+ case IncrementalSource.MouseMove: {
5482
+ e.data.positions.forEach((p) => {
5483
+ this.replaceIds(p, iframeEl, ['id']);
5484
+ });
5485
+ return e;
5486
+ }
5487
+ case IncrementalSource.ViewportResize: {
5488
+ return false;
5489
+ }
5490
+ case IncrementalSource.MediaInteraction:
5491
+ case IncrementalSource.MouseInteraction:
5492
+ case IncrementalSource.Scroll:
5493
+ case IncrementalSource.CanvasMutation:
5494
+ case IncrementalSource.Input: {
5495
+ this.replaceIds(e.data, iframeEl, ['id']);
5496
+ return e;
5497
+ }
5498
+ case IncrementalSource.StyleSheetRule:
5499
+ case IncrementalSource.StyleDeclaration: {
5500
+ this.replaceIds(e.data, iframeEl, ['id']);
5501
+ this.replaceStyleIds(e.data, iframeEl, ['styleId']);
5502
+ return e;
5503
+ }
5504
+ case IncrementalSource.Font: {
5505
+ return e;
5506
+ }
5507
+ case IncrementalSource.Selection: {
5508
+ e.data.ranges.forEach((range) => {
5509
+ this.replaceIds(range, iframeEl, ['start', 'end']);
5510
+ });
5511
+ return e;
5512
+ }
5513
+ case IncrementalSource.AdoptedStyleSheet: {
5514
+ this.replaceIds(e.data, iframeEl, ['id']);
5515
+ this.replaceStyleIds(e.data, iframeEl, ['styleIds']);
5516
+ (_a = e.data.styles) === null || _a === void 0 ? void 0 : _a.forEach((style) => {
5517
+ this.replaceStyleIds(style, iframeEl, ['styleId']);
5518
+ });
5519
+ return e;
5520
+ }
5521
+ }
5522
+ }
5523
+ }
5524
+ }
5525
+ replace(iframeMirror, obj, iframeEl, keys) {
5526
+ for (const key of keys) {
5527
+ if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')
5528
+ continue;
5529
+ if (Array.isArray(obj[key])) {
5530
+ obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
5531
+ }
5532
+ else {
5533
+ obj[key] = iframeMirror.getId(iframeEl, obj[key]);
5534
+ }
5535
+ }
5536
+ return obj;
5537
+ }
5538
+ replaceIds(obj, iframeEl, keys) {
5539
+ return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
5540
+ }
5541
+ replaceStyleIds(obj, iframeEl, keys) {
5542
+ return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
5543
+ }
5544
+ replaceIdOnNode(node, iframeEl) {
5545
+ this.replaceIds(node, iframeEl, ['id']);
5546
+ if ('childNodes' in node) {
5547
+ node.childNodes.forEach((child) => {
5548
+ this.replaceIdOnNode(child, iframeEl);
5549
+ });
5550
+ }
5551
+ }
5552
+ }
5553
+
5554
+ class ShadowDomManager {
5555
+ constructor(options) {
5556
+ this.shadowDoms = new WeakSet();
5557
+ this.restorePatches = [];
5558
+ this.mutationCb = options.mutationCb;
5559
+ this.scrollCb = options.scrollCb;
5560
+ this.bypassOptions = options.bypassOptions;
5561
+ this.mirror = options.mirror;
5562
+ const manager = this;
5563
+ this.restorePatches.push(patch(Element.prototype, 'attachShadow', function (original) {
5564
+ return function (option) {
5565
+ const shadowRoot = original.call(this, option);
5566
+ if (this.shadowRoot)
5567
+ manager.addShadowRoot(this.shadowRoot, this.ownerDocument);
5568
+ return shadowRoot;
5569
+ };
5570
+ }));
5571
+ }
5572
+ addShadowRoot(shadowRoot, doc) {
5573
+ if (!isNativeShadowDom(shadowRoot))
5574
+ return;
5575
+ if (this.shadowDoms.has(shadowRoot))
5576
+ return;
5577
+ this.shadowDoms.add(shadowRoot);
5578
+ initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), { doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);
5579
+ initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror }));
5580
+ setTimeout(() => {
5581
+ if (shadowRoot.adoptedStyleSheets &&
5582
+ shadowRoot.adoptedStyleSheets.length > 0)
5583
+ this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));
5584
+ initAdoptedStyleSheetObserver({
5585
+ mirror: this.mirror,
5586
+ stylesheetManager: this.bypassOptions.stylesheetManager,
5587
+ }, shadowRoot);
5588
+ }, 0);
5589
+ }
5590
+ observeAttachShadow(iframeElement) {
5591
+ if (iframeElement.contentWindow) {
5592
+ const manager = this;
5593
+ this.restorePatches.push(patch(iframeElement.contentWindow.HTMLElement.prototype, 'attachShadow', function (original) {
5594
+ return function (option) {
5595
+ const shadowRoot = original.call(this, option);
5596
+ if (this.shadowRoot)
5597
+ manager.addShadowRoot(this.shadowRoot, iframeElement.contentDocument);
5598
+ return shadowRoot;
5599
+ };
5600
+ }));
5601
+ }
5602
+ }
5603
+ reset() {
5604
+ this.restorePatches.forEach((restorePatch) => restorePatch());
5605
+ this.shadowDoms = new WeakSet();
5606
+ }
5607
+ }
5608
+
5609
+ /*! *****************************************************************************
5610
+ Copyright (c) Microsoft Corporation.
5611
+
5612
+ Permission to use, copy, modify, and/or distribute this software for any
5613
+ purpose with or without fee is hereby granted.
5614
+
5615
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
5616
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
5617
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
5618
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
5619
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
5620
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
5621
+ PERFORMANCE OF THIS SOFTWARE.
5622
+ ***************************************************************************** */
5623
+
5624
+ function __rest(s, e) {
5625
+ var t = {};
5626
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5627
+ t[p] = s[p];
5628
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
5629
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
5630
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
5631
+ t[p[i]] = s[p[i]];
5632
+ }
5633
+ return t;
5634
+ }
5635
+
5636
+ function __awaiter(thisArg, _arguments, P, generator) {
5637
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5638
+ return new (P || (P = Promise))(function (resolve, reject) {
5639
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5640
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
5641
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
5642
+ step((generator = generator.apply(thisArg, [])).next());
5643
+ });
5644
+ }
5645
+
5646
+ /*
5647
+ * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
5648
+ * Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
5649
+ * Released under MIT License
5650
+ */
5651
+ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
5652
+ // Use a lookup table to find the index.
5653
+ var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
5654
+ for (var i = 0; i < chars.length; i++) {
5655
+ lookup[chars.charCodeAt(i)] = i;
5656
+ }
5657
+ var encode = function (arraybuffer) {
5658
+ var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
5659
+ for (i = 0; i < len; i += 3) {
5660
+ base64 += chars[bytes[i] >> 2];
5661
+ base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
5662
+ base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
5663
+ base64 += chars[bytes[i + 2] & 63];
5664
+ }
5665
+ if (len % 3 === 2) {
5666
+ base64 = base64.substring(0, base64.length - 1) + '=';
5667
+ }
5668
+ else if (len % 3 === 1) {
5669
+ base64 = base64.substring(0, base64.length - 2) + '==';
5670
+ }
5671
+ return base64;
5672
+ };
5673
+
5674
+ const canvasVarMap = new Map();
5675
+ function variableListFor(ctx, ctor) {
5676
+ let contextMap = canvasVarMap.get(ctx);
5677
+ if (!contextMap) {
5678
+ contextMap = new Map();
5679
+ canvasVarMap.set(ctx, contextMap);
5680
+ }
5681
+ if (!contextMap.has(ctor)) {
5682
+ contextMap.set(ctor, []);
5683
+ }
5684
+ return contextMap.get(ctor);
5685
+ }
5686
+ const saveWebGLVar = (value, win, ctx) => {
5687
+ if (!value ||
5688
+ !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))
5689
+ return;
5690
+ const name = value.constructor.name;
5691
+ const list = variableListFor(ctx, name);
5692
+ let index = list.indexOf(value);
5693
+ if (index === -1) {
5694
+ index = list.length;
5695
+ list.push(value);
5696
+ }
5697
+ return index;
5698
+ };
5699
+ function serializeArg(value, win, ctx) {
5700
+ if (value instanceof Array) {
5701
+ return value.map((arg) => serializeArg(arg, win, ctx));
5702
+ }
5703
+ else if (value === null) {
5704
+ return value;
5705
+ }
5706
+ else if (value instanceof Float32Array ||
5707
+ value instanceof Float64Array ||
5708
+ value instanceof Int32Array ||
5709
+ value instanceof Uint32Array ||
5710
+ value instanceof Uint8Array ||
5711
+ value instanceof Uint16Array ||
5712
+ value instanceof Int16Array ||
5713
+ value instanceof Int8Array ||
5714
+ value instanceof Uint8ClampedArray) {
5715
+ const name = value.constructor.name;
5716
+ return {
5717
+ rr_type: name,
5718
+ args: [Object.values(value)],
5719
+ };
5720
+ }
5721
+ else if (value instanceof ArrayBuffer) {
5722
+ const name = value.constructor.name;
5723
+ const base64 = encode(value);
5724
+ return {
5725
+ rr_type: name,
5726
+ base64,
5727
+ };
5728
+ }
5729
+ else if (value instanceof DataView) {
5730
+ const name = value.constructor.name;
5731
+ return {
5732
+ rr_type: name,
5733
+ args: [
5734
+ serializeArg(value.buffer, win, ctx),
5735
+ value.byteOffset,
5736
+ value.byteLength,
5737
+ ],
5738
+ };
5739
+ }
5740
+ else if (value instanceof HTMLImageElement) {
5741
+ const name = value.constructor.name;
5742
+ const { src } = value;
5743
+ return {
5744
+ rr_type: name,
5745
+ src,
5746
+ };
5747
+ }
5748
+ else if (value instanceof HTMLCanvasElement) {
5749
+ const name = 'HTMLImageElement';
5750
+ const src = value.toDataURL();
5751
+ return {
5752
+ rr_type: name,
5753
+ src,
5754
+ };
5755
+ }
5756
+ else if (value instanceof ImageData) {
5757
+ const name = value.constructor.name;
5758
+ return {
5759
+ rr_type: name,
5760
+ args: [serializeArg(value.data, win, ctx), value.width, value.height],
5761
+ };
5762
+ }
5763
+ else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {
5764
+ const name = value.constructor.name;
5765
+ const index = saveWebGLVar(value, win, ctx);
5766
+ return {
5767
+ rr_type: name,
5768
+ index: index,
5769
+ };
5770
+ }
5771
+ return value;
5772
+ }
5773
+ const serializeArgs = (args, win, ctx) => {
5774
+ return [...args].map((arg) => serializeArg(arg, win, ctx));
5775
+ };
5776
+ const isInstanceOfWebGLObject = (value, win) => {
5777
+ const webGLConstructorNames = [
5778
+ 'WebGLActiveInfo',
5779
+ 'WebGLBuffer',
5780
+ 'WebGLFramebuffer',
5781
+ 'WebGLProgram',
5782
+ 'WebGLRenderbuffer',
5783
+ 'WebGLShader',
5784
+ 'WebGLShaderPrecisionFormat',
5785
+ 'WebGLTexture',
5786
+ 'WebGLUniformLocation',
5787
+ 'WebGLVertexArrayObject',
5788
+ 'WebGLVertexArrayObjectOES',
5789
+ ];
5790
+ const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');
5791
+ return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));
5792
+ };
5793
+
5794
+ function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
5795
+ const handlers = [];
5796
+ const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
5797
+ for (const prop of props2D) {
5798
+ try {
5799
+ if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {
5800
+ continue;
5801
+ }
5802
+ const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {
5803
+ return function (...args) {
5804
+ if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
5805
+ setTimeout(() => {
5806
+ const recordArgs = serializeArgs([...args], win, this);
5807
+ cb(this.canvas, {
5808
+ type: CanvasContext['2D'],
5809
+ property: prop,
5810
+ args: recordArgs,
5811
+ });
5812
+ }, 0);
5813
+ }
5814
+ return original.apply(this, args);
5815
+ };
5816
+ });
5817
+ handlers.push(restoreHandler);
5818
+ }
5819
+ catch (_a) {
5820
+ const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
5821
+ set(v) {
5822
+ cb(this.canvas, {
5823
+ type: CanvasContext['2D'],
5824
+ property: prop,
5825
+ args: [v],
5826
+ setter: true,
5827
+ });
5828
+ },
5829
+ });
5830
+ handlers.push(hookHandler);
5831
+ }
5832
+ }
5833
+ return () => {
5834
+ handlers.forEach((h) => h());
5835
+ };
5836
+ }
5837
+
5838
+ function initCanvasContextObserver(win, blockClass, blockSelector) {
5839
+ const handlers = [];
5840
+ try {
5841
+ const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {
5842
+ return function (contextType, ...args) {
5843
+ if (!isBlocked(this, blockClass, blockSelector, true)) {
5844
+ if (!('__context' in this))
5845
+ this.__context = contextType;
5846
+ }
5847
+ return original.apply(this, [contextType, ...args]);
5848
+ };
5849
+ });
5850
+ handlers.push(restoreHandler);
5851
+ }
5852
+ catch (_a) {
5853
+ console.error('failed to patch HTMLCanvasElement.prototype.getContext');
5854
+ }
5855
+ return () => {
5856
+ handlers.forEach((h) => h());
5857
+ };
5858
+ }
5859
+
5860
+ function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, mirror, win) {
5861
+ const handlers = [];
5862
+ const props = Object.getOwnPropertyNames(prototype);
5863
+ for (const prop of props) {
5864
+ if ([
5865
+ 'isContextLost',
5866
+ 'canvas',
5867
+ 'drawingBufferWidth',
5868
+ 'drawingBufferHeight',
5869
+ ].includes(prop)) {
5870
+ continue;
5871
+ }
5872
+ try {
5873
+ if (typeof prototype[prop] !== 'function') {
5874
+ continue;
5875
+ }
5876
+ const restoreHandler = patch(prototype, prop, function (original) {
5877
+ return function (...args) {
5878
+ const result = original.apply(this, args);
5879
+ saveWebGLVar(result, win, this);
5880
+ if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
5881
+ const recordArgs = serializeArgs([...args], win, this);
5882
+ const mutation = {
5883
+ type,
5884
+ property: prop,
5885
+ args: recordArgs,
5886
+ };
5887
+ cb(this.canvas, mutation);
5888
+ }
5889
+ return result;
5890
+ };
5891
+ });
5892
+ handlers.push(restoreHandler);
5893
+ }
5894
+ catch (_a) {
5895
+ const hookHandler = hookSetter(prototype, prop, {
5896
+ set(v) {
5897
+ cb(this.canvas, {
5898
+ type,
5899
+ property: prop,
5900
+ args: [v],
5901
+ setter: true,
5902
+ });
5903
+ },
5904
+ });
5905
+ handlers.push(hookHandler);
5906
+ }
5907
+ }
5908
+ return handlers;
5909
+ }
5910
+ function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, mirror) {
5911
+ const handlers = [];
5912
+ handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, mirror, win));
5913
+ if (typeof win.WebGL2RenderingContext !== 'undefined') {
5914
+ handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, mirror, win));
5915
+ }
5916
+ return () => {
5917
+ handlers.forEach((h) => h());
5918
+ };
5919
+ }
5920
+
5921
+ var WorkerClass = null;
5922
+
5923
+ try {
5924
+ var WorkerThreads =
5925
+ typeof module !== 'undefined' && typeof module.require === 'function' && module.require('worker_threads') ||
5926
+ typeof __non_webpack_require__ === 'function' && __non_webpack_require__('worker_threads') ||
5927
+ typeof require === 'function' && require('worker_threads');
5928
+ WorkerClass = WorkerThreads.Worker;
5929
+ } catch(e) {} // eslint-disable-line
5930
+
5931
+ function decodeBase64$1(base64, enableUnicode) {
5932
+ return Buffer.from(base64, 'base64').toString('utf8');
5933
+ }
5934
+
5935
+ function createBase64WorkerFactory$2(base64, sourcemapArg, enableUnicodeArg) {
5936
+ var source = decodeBase64$1(base64);
5937
+ var start = source.indexOf('\n', 10) + 1;
5938
+ var body = source.substring(start) + ('');
5939
+ return function WorkerFactory(options) {
5940
+ return new WorkerClass(body, Object.assign({}, options, { eval: true }));
5941
+ };
5942
+ }
5943
+
5944
+ function decodeBase64(base64, enableUnicode) {
5945
+ var binaryString = atob(base64);
5946
+ return binaryString;
5947
+ }
5948
+
5949
+ function createURL(base64, sourcemapArg, enableUnicodeArg) {
5950
+ var source = decodeBase64(base64);
5951
+ var start = source.indexOf('\n', 10) + 1;
5952
+ var body = source.substring(start) + ('');
5953
+ var blob = new Blob([body], { type: 'application/javascript' });
5954
+ return URL.createObjectURL(blob);
5955
+ }
5956
+
5957
+ function createBase64WorkerFactory$1(base64, sourcemapArg, enableUnicodeArg) {
5958
+ var url;
5959
+ return function WorkerFactory(options) {
5960
+ url = url || createURL(base64);
5961
+ return new Worker(url, options);
5962
+ };
5963
+ }
5964
+
5965
+ var kIsNodeJS = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
5966
+
5967
+ function isNodeJS() {
5968
+ return kIsNodeJS;
5969
+ }
5970
+
5971
+ function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) {
5972
+ if (isNodeJS()) {
5973
+ return createBase64WorkerFactory$2(base64);
5974
+ }
5975
+ return createBase64WorkerFactory$1(base64);
5976
+ }
5977
+
5978
+ var WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=');
5979
+
5980
+ class CanvasManager {
5981
+ constructor(options) {
5982
+ this.pendingCanvasMutations = new Map();
5983
+ this.rafStamps = { latestId: 0, invokeId: null };
5984
+ this.frozen = false;
5985
+ this.locked = false;
5986
+ this.processMutation = (target, mutation) => {
5987
+ const newFrame = this.rafStamps.invokeId &&
5988
+ this.rafStamps.latestId !== this.rafStamps.invokeId;
5989
+ if (newFrame || !this.rafStamps.invokeId)
5990
+ this.rafStamps.invokeId = this.rafStamps.latestId;
5991
+ if (!this.pendingCanvasMutations.has(target)) {
5992
+ this.pendingCanvasMutations.set(target, []);
5993
+ }
5994
+ this.pendingCanvasMutations.get(target).push(mutation);
5995
+ };
5996
+ const { sampling = 'all', win, blockClass, blockSelector, recordCanvas, dataURLOptions, } = options;
5997
+ this.mutationCb = options.mutationCb;
5998
+ this.mirror = options.mirror;
5999
+ if (recordCanvas && sampling === 'all')
6000
+ this.initCanvasMutationObserver(win, blockClass, blockSelector);
6001
+ if (recordCanvas && typeof sampling === 'number')
6002
+ this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
6003
+ dataURLOptions,
6004
+ });
6005
+ }
6006
+ reset() {
6007
+ this.pendingCanvasMutations.clear();
6008
+ this.resetObservers && this.resetObservers();
6009
+ }
6010
+ freeze() {
6011
+ this.frozen = true;
6012
+ }
6013
+ unfreeze() {
6014
+ this.frozen = false;
6015
+ }
6016
+ lock() {
6017
+ this.locked = true;
6018
+ }
6019
+ unlock() {
6020
+ this.locked = false;
6021
+ }
6022
+ initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
6023
+ const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
6024
+ const snapshotInProgressMap = new Map();
6025
+ const worker = new WorkerFactory();
6026
+ worker.onmessage = (e) => {
6027
+ const { id } = e.data;
6028
+ snapshotInProgressMap.set(id, false);
6029
+ if (!('base64' in e.data))
6030
+ return;
6031
+ const { base64, type, width, height } = e.data;
6032
+ this.mutationCb({
6033
+ id,
6034
+ type: CanvasContext['2D'],
6035
+ commands: [
6036
+ {
6037
+ property: 'clearRect',
6038
+ args: [0, 0, width, height],
6039
+ },
6040
+ {
6041
+ property: 'drawImage',
6042
+ args: [
6043
+ {
6044
+ rr_type: 'ImageBitmap',
6045
+ args: [
6046
+ {
6047
+ rr_type: 'Blob',
6048
+ data: [{ rr_type: 'ArrayBuffer', base64 }],
6049
+ type,
6050
+ },
6051
+ ],
6052
+ },
6053
+ 0,
6054
+ 0,
6055
+ ],
6056
+ },
6057
+ ],
6058
+ });
6059
+ };
6060
+ const timeBetweenSnapshots = 1000 / fps;
6061
+ let lastSnapshotTime = 0;
6062
+ let rafId;
6063
+ const getCanvas = () => {
6064
+ const matchedCanvas = [];
6065
+ win.document.querySelectorAll('canvas').forEach((canvas) => {
6066
+ if (!isBlocked(canvas, blockClass, blockSelector, true)) {
6067
+ matchedCanvas.push(canvas);
6068
+ }
6069
+ });
6070
+ return matchedCanvas;
6071
+ };
6072
+ const takeCanvasSnapshots = (timestamp) => {
6073
+ if (lastSnapshotTime &&
6074
+ timestamp - lastSnapshotTime < timeBetweenSnapshots) {
6075
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
6076
+ return;
6077
+ }
6078
+ lastSnapshotTime = timestamp;
6079
+ getCanvas()
6080
+ .forEach((canvas) => __awaiter(this, void 0, void 0, function* () {
6081
+ var _a;
6082
+ const id = this.mirror.getId(canvas);
6083
+ if (snapshotInProgressMap.get(id))
6084
+ return;
6085
+ snapshotInProgressMap.set(id, true);
6086
+ if (['webgl', 'webgl2'].includes(canvas.__context)) {
6087
+ const context = canvas.getContext(canvas.__context);
6088
+ if (((_a = context === null || context === void 0 ? void 0 : context.getContextAttributes()) === null || _a === void 0 ? void 0 : _a.preserveDrawingBuffer) === false) {
6089
+ context === null || context === void 0 ? void 0 : context.clear(context.COLOR_BUFFER_BIT);
6090
+ }
6091
+ }
6092
+ const bitmap = yield createImageBitmap(canvas);
6093
+ worker.postMessage({
6094
+ id,
6095
+ bitmap,
6096
+ width: canvas.width,
6097
+ height: canvas.height,
6098
+ dataURLOptions: options.dataURLOptions,
6099
+ }, [bitmap]);
6100
+ }));
6101
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
6102
+ };
6103
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
6104
+ this.resetObservers = () => {
6105
+ canvasContextReset();
6106
+ cancelAnimationFrame(rafId);
6107
+ };
6108
+ }
6109
+ initCanvasMutationObserver(win, blockClass, blockSelector) {
6110
+ this.startRAFTimestamping();
6111
+ this.startPendingCanvasMutationFlusher();
6112
+ const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
6113
+ const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
6114
+ const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, this.mirror);
6115
+ this.resetObservers = () => {
6116
+ canvasContextReset();
6117
+ canvas2DReset();
6118
+ canvasWebGL1and2Reset();
6119
+ };
6120
+ }
6121
+ startPendingCanvasMutationFlusher() {
6122
+ requestAnimationFrame(() => this.flushPendingCanvasMutations());
6123
+ }
6124
+ startRAFTimestamping() {
6125
+ const setLatestRAFTimestamp = (timestamp) => {
6126
+ this.rafStamps.latestId = timestamp;
6127
+ requestAnimationFrame(setLatestRAFTimestamp);
6128
+ };
6129
+ requestAnimationFrame(setLatestRAFTimestamp);
6130
+ }
6131
+ flushPendingCanvasMutations() {
6132
+ this.pendingCanvasMutations.forEach((values, canvas) => {
6133
+ const id = this.mirror.getId(canvas);
6134
+ this.flushPendingCanvasMutationFor(canvas, id);
6135
+ });
6136
+ requestAnimationFrame(() => this.flushPendingCanvasMutations());
6137
+ }
6138
+ flushPendingCanvasMutationFor(canvas, id) {
6139
+ if (this.frozen || this.locked) {
6140
+ return;
6141
+ }
6142
+ const valuesWithType = this.pendingCanvasMutations.get(canvas);
6143
+ if (!valuesWithType || id === -1)
6144
+ return;
6145
+ const values = valuesWithType.map((value) => {
6146
+ const rest = __rest(value, ["type"]);
6147
+ return rest;
6148
+ });
6149
+ const { type } = valuesWithType[0];
6150
+ this.mutationCb({ id, type, commands: values });
6151
+ this.pendingCanvasMutations.delete(canvas);
6152
+ }
6153
+ }
6154
+
6155
+ class StylesheetManager {
6156
+ constructor(options) {
6157
+ this.trackedLinkElements = new WeakSet();
6158
+ this.styleMirror = new StyleSheetMirror();
6159
+ this.mutationCb = options.mutationCb;
6160
+ this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
6161
+ }
6162
+ attachLinkElement(linkEl, childSn) {
6163
+ if ('_cssText' in childSn.attributes)
6164
+ this.mutationCb({
6165
+ adds: [],
6166
+ removes: [],
6167
+ texts: [],
6168
+ attributes: [
6169
+ {
6170
+ id: childSn.id,
6171
+ attributes: childSn
6172
+ .attributes,
6173
+ },
6174
+ ],
6175
+ });
6176
+ this.trackLinkElement(linkEl);
6177
+ }
6178
+ trackLinkElement(linkEl) {
6179
+ if (this.trackedLinkElements.has(linkEl))
6180
+ return;
6181
+ this.trackedLinkElements.add(linkEl);
6182
+ this.trackStylesheetInLinkElement(linkEl);
6183
+ }
6184
+ adoptStyleSheets(sheets, hostId) {
6185
+ if (sheets.length === 0)
6186
+ return;
6187
+ const adoptedStyleSheetData = {
6188
+ id: hostId,
6189
+ styleIds: [],
6190
+ };
6191
+ const styles = [];
6192
+ for (const sheet of sheets) {
6193
+ let styleId;
6194
+ if (!this.styleMirror.has(sheet)) {
6195
+ styleId = this.styleMirror.add(sheet);
6196
+ const rules = Array.from(sheet.rules || CSSRule);
6197
+ styles.push({
6198
+ styleId,
6199
+ rules: rules.map((r, index) => {
6200
+ return {
6201
+ rule: getCssRuleString(r),
6202
+ index,
6203
+ };
6204
+ }),
6205
+ });
6206
+ }
6207
+ else
6208
+ styleId = this.styleMirror.getId(sheet);
6209
+ adoptedStyleSheetData.styleIds.push(styleId);
6210
+ }
6211
+ if (styles.length > 0)
6212
+ adoptedStyleSheetData.styles = styles;
6213
+ this.adoptedStyleSheetCb(adoptedStyleSheetData);
6214
+ }
6215
+ reset() {
6216
+ this.styleMirror.reset();
6217
+ this.trackedLinkElements = new WeakSet();
6218
+ }
6219
+ trackStylesheetInLinkElement(linkEl) {
6220
+ }
6221
+ }
6222
+
6223
+ function wrapEvent(e) {
6224
+ return Object.assign(Object.assign({}, e), { timestamp: Date.now() });
6225
+ }
6226
+ let wrappedEmit;
6227
+ let takeFullSnapshot;
6228
+ let canvasManager;
6229
+ let recording = false;
6230
+ const mirror = createMirror();
6231
+ function record(options = {}) {
6232
+ const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, ignoreClass = 'rr-ignore', maskTextClass = 'rr-mask', maskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskInputFn, maskTextFn, hooks, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordCanvas = false, recordCrossOriginIframes = false, userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), } = options;
6233
+ const inEmittingFrame = recordCrossOriginIframes
6234
+ ? window.parent === window
6235
+ : true;
6236
+ let passEmitsToParent = false;
6237
+ if (!inEmittingFrame) {
6238
+ try {
6239
+ window.parent.document;
6240
+ passEmitsToParent = false;
6241
+ }
6242
+ catch (e) {
6243
+ passEmitsToParent = true;
6244
+ }
6245
+ }
6246
+ if (inEmittingFrame && !emit) {
6247
+ throw new Error('emit function is required');
6248
+ }
6249
+ if (mousemoveWait !== undefined && sampling.mousemove === undefined) {
6250
+ sampling.mousemove = mousemoveWait;
6251
+ }
6252
+ mirror.reset();
6253
+ const maskInputOptions = maskAllInputs === true
6254
+ ? {
6255
+ color: true,
6256
+ date: true,
6257
+ 'datetime-local': true,
6258
+ email: true,
6259
+ month: true,
6260
+ number: true,
6261
+ range: true,
6262
+ search: true,
6263
+ tel: true,
6264
+ text: true,
6265
+ time: true,
6266
+ url: true,
6267
+ week: true,
6268
+ textarea: true,
6269
+ select: true,
6270
+ password: true,
6271
+ }
6272
+ : _maskInputOptions !== undefined
6273
+ ? _maskInputOptions
6274
+ : { password: true };
6275
+ const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'
6276
+ ? {
6277
+ script: true,
6278
+ comment: true,
6279
+ headFavicon: true,
6280
+ headWhitespace: true,
6281
+ headMetaSocial: true,
6282
+ headMetaRobots: true,
6283
+ headMetaHttpEquiv: true,
6284
+ headMetaVerification: true,
6285
+ headMetaAuthorship: _slimDOMOptions === 'all',
6286
+ headMetaDescKeywords: _slimDOMOptions === 'all',
6287
+ }
6288
+ : _slimDOMOptions
6289
+ ? _slimDOMOptions
6290
+ : {};
6291
+ polyfill();
6292
+ let lastFullSnapshotEvent;
6293
+ let incrementalSnapshotCount = 0;
6294
+ const eventProcessor = (e) => {
6295
+ for (const plugin of plugins || []) {
6296
+ if (plugin.eventProcessor) {
6297
+ e = plugin.eventProcessor(e);
6298
+ }
6299
+ }
6300
+ if (packFn) {
6301
+ e = packFn(e);
6302
+ }
6303
+ return e;
6304
+ };
6305
+ wrappedEmit = (e, isCheckout) => {
6306
+ var _a;
6307
+ if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&
6308
+ e.type !== EventType.FullSnapshot &&
6309
+ !(e.type === EventType.IncrementalSnapshot &&
6310
+ e.data.source === IncrementalSource.Mutation)) {
6311
+ mutationBuffers.forEach((buf) => buf.unfreeze());
6312
+ }
6313
+ if (inEmittingFrame) {
6314
+ emit === null || emit === void 0 ? void 0 : emit(eventProcessor(e), isCheckout);
6315
+ }
6316
+ else if (passEmitsToParent) {
6317
+ const message = {
6318
+ type: 'rrweb',
6319
+ event: eventProcessor(e),
6320
+ isCheckout,
6321
+ };
6322
+ window.parent.postMessage(message, '*');
6323
+ }
6324
+ if (e.type === EventType.FullSnapshot) {
6325
+ lastFullSnapshotEvent = e;
6326
+ incrementalSnapshotCount = 0;
6327
+ }
6328
+ else if (e.type === EventType.IncrementalSnapshot) {
6329
+ if (e.data.source === IncrementalSource.Mutation &&
6330
+ e.data.isAttachIframe) {
6331
+ return;
6332
+ }
6333
+ incrementalSnapshotCount++;
6334
+ const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
6335
+ const exceedTime = checkoutEveryNms &&
6336
+ e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
6337
+ if (exceedCount || exceedTime) {
6338
+ takeFullSnapshot(true);
6339
+ }
6340
+ }
6341
+ };
6342
+ const wrappedMutationEmit = (m) => {
6343
+ wrappedEmit(wrapEvent({
6344
+ type: EventType.IncrementalSnapshot,
6345
+ data: Object.assign({ source: IncrementalSource.Mutation }, m),
6346
+ }));
6347
+ };
6348
+ const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({
6349
+ type: EventType.IncrementalSnapshot,
6350
+ data: Object.assign({ source: IncrementalSource.Scroll }, p),
6351
+ }));
6352
+ const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({
6353
+ type: EventType.IncrementalSnapshot,
6354
+ data: Object.assign({ source: IncrementalSource.CanvasMutation }, p),
6355
+ }));
6356
+ const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit(wrapEvent({
6357
+ type: EventType.IncrementalSnapshot,
6358
+ data: Object.assign({ source: IncrementalSource.AdoptedStyleSheet }, a),
6359
+ }));
6360
+ const stylesheetManager = new StylesheetManager({
6361
+ mutationCb: wrappedMutationEmit,
6362
+ adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,
6363
+ });
6364
+ const iframeManager = new IframeManager({
6365
+ mirror,
6366
+ mutationCb: wrappedMutationEmit,
6367
+ stylesheetManager: stylesheetManager,
6368
+ recordCrossOriginIframes,
6369
+ wrappedEmit,
6370
+ });
6371
+ for (const plugin of plugins || []) {
6372
+ if (plugin.getMirror)
6373
+ plugin.getMirror({
6374
+ nodeMirror: mirror,
6375
+ crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
6376
+ crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,
6377
+ });
6378
+ }
6379
+ canvasManager = new CanvasManager({
6380
+ recordCanvas,
6381
+ mutationCb: wrappedCanvasMutationEmit,
6382
+ win: window,
6383
+ blockClass,
6384
+ blockSelector,
6385
+ mirror,
6386
+ sampling: sampling.canvas,
6387
+ dataURLOptions,
6388
+ });
6389
+ const shadowDomManager = new ShadowDomManager({
6390
+ mutationCb: wrappedMutationEmit,
6391
+ scrollCb: wrappedScrollEmit,
6392
+ bypassOptions: {
6393
+ blockClass,
6394
+ blockSelector,
6395
+ maskTextClass,
6396
+ maskTextSelector,
6397
+ inlineStylesheet,
6398
+ maskInputOptions,
6399
+ dataURLOptions,
6400
+ maskTextFn,
6401
+ maskInputFn,
6402
+ recordCanvas,
6403
+ inlineImages,
6404
+ sampling,
6405
+ slimDOMOptions,
6406
+ iframeManager,
6407
+ stylesheetManager,
6408
+ canvasManager,
6409
+ keepIframeSrcFn,
6410
+ },
6411
+ mirror,
6412
+ });
6413
+ takeFullSnapshot = (isCheckout = false) => {
6414
+ var _a, _b, _c, _d, _e, _f;
6415
+ wrappedEmit(wrapEvent({
6416
+ type: EventType.Meta,
6417
+ data: {
6418
+ href: window.location.href,
6419
+ width: getWindowWidth(),
6420
+ height: getWindowHeight(),
6421
+ },
6422
+ }), isCheckout);
6423
+ stylesheetManager.reset();
6424
+ mutationBuffers.forEach((buf) => buf.lock());
6425
+ const node = snapshot(document, {
6426
+ mirror,
6427
+ blockClass,
6428
+ blockSelector,
6429
+ maskTextClass,
6430
+ maskTextSelector,
6431
+ inlineStylesheet,
6432
+ maskAllInputs: maskInputOptions,
6433
+ maskTextFn,
6434
+ slimDOM: slimDOMOptions,
6435
+ dataURLOptions,
6436
+ recordCanvas,
6437
+ inlineImages,
6438
+ onSerialize: (n) => {
6439
+ if (isSerializedIframe(n, mirror)) {
6440
+ iframeManager.addIframe(n);
6441
+ }
6442
+ if (isSerializedStylesheet(n, mirror)) {
6443
+ stylesheetManager.trackLinkElement(n);
6444
+ }
6445
+ if (hasShadowRoot(n)) {
6446
+ shadowDomManager.addShadowRoot(n.shadowRoot, document);
6447
+ }
6448
+ },
6449
+ onIframeLoad: (iframe, childSn) => {
6450
+ iframeManager.attachIframe(iframe, childSn);
6451
+ shadowDomManager.observeAttachShadow(iframe);
6452
+ },
6453
+ onStylesheetLoad: (linkEl, childSn) => {
6454
+ stylesheetManager.attachLinkElement(linkEl, childSn);
6455
+ },
6456
+ keepIframeSrcFn,
6457
+ });
6458
+ if (!node) {
6459
+ return console.warn('Failed to snapshot the document');
6460
+ }
6461
+ wrappedEmit(wrapEvent({
6462
+ type: EventType.FullSnapshot,
6463
+ data: {
6464
+ node,
6465
+ initialOffset: {
6466
+ left: window.pageXOffset !== undefined
6467
+ ? window.pageXOffset
6468
+ : (document === null || document === void 0 ? void 0 : document.documentElement.scrollLeft) ||
6469
+ ((_b = (_a = document === null || document === void 0 ? void 0 : document.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) ||
6470
+ ((_c = document === null || document === void 0 ? void 0 : document.body) === null || _c === void 0 ? void 0 : _c.scrollLeft) ||
6471
+ 0,
6472
+ top: window.pageYOffset !== undefined
6473
+ ? window.pageYOffset
6474
+ : (document === null || document === void 0 ? void 0 : document.documentElement.scrollTop) ||
6475
+ ((_e = (_d = document === null || document === void 0 ? void 0 : document.body) === null || _d === void 0 ? void 0 : _d.parentElement) === null || _e === void 0 ? void 0 : _e.scrollTop) ||
6476
+ ((_f = document === null || document === void 0 ? void 0 : document.body) === null || _f === void 0 ? void 0 : _f.scrollTop) ||
6477
+ 0,
6478
+ },
6479
+ },
6480
+ }));
6481
+ mutationBuffers.forEach((buf) => buf.unlock());
6482
+ if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)
6483
+ stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
6484
+ };
6485
+ try {
6486
+ const handlers = [];
6487
+ handlers.push(on('DOMContentLoaded', () => {
6488
+ wrappedEmit(wrapEvent({
6489
+ type: EventType.DomContentLoaded,
6490
+ data: {},
6491
+ }));
6492
+ }));
6493
+ const observe = (doc) => {
6494
+ var _a;
6495
+ return initObservers({
6496
+ mutationCb: wrappedMutationEmit,
6497
+ mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({
6498
+ type: EventType.IncrementalSnapshot,
6499
+ data: {
6500
+ source,
6501
+ positions,
6502
+ },
6503
+ })),
6504
+ mouseInteractionCb: (d) => wrappedEmit(wrapEvent({
6505
+ type: EventType.IncrementalSnapshot,
6506
+ data: Object.assign({ source: IncrementalSource.MouseInteraction }, d),
6507
+ })),
6508
+ scrollCb: wrappedScrollEmit,
6509
+ viewportResizeCb: (d) => wrappedEmit(wrapEvent({
6510
+ type: EventType.IncrementalSnapshot,
6511
+ data: Object.assign({ source: IncrementalSource.ViewportResize }, d),
6512
+ })),
6513
+ inputCb: (v) => wrappedEmit(wrapEvent({
6514
+ type: EventType.IncrementalSnapshot,
6515
+ data: Object.assign({ source: IncrementalSource.Input }, v),
6516
+ })),
6517
+ mediaInteractionCb: (p) => wrappedEmit(wrapEvent({
6518
+ type: EventType.IncrementalSnapshot,
6519
+ data: Object.assign({ source: IncrementalSource.MediaInteraction }, p),
6520
+ })),
6521
+ styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({
6522
+ type: EventType.IncrementalSnapshot,
6523
+ data: Object.assign({ source: IncrementalSource.StyleSheetRule }, r),
6524
+ })),
6525
+ styleDeclarationCb: (r) => wrappedEmit(wrapEvent({
6526
+ type: EventType.IncrementalSnapshot,
6527
+ data: Object.assign({ source: IncrementalSource.StyleDeclaration }, r),
6528
+ })),
6529
+ canvasMutationCb: wrappedCanvasMutationEmit,
6530
+ fontCb: (p) => wrappedEmit(wrapEvent({
6531
+ type: EventType.IncrementalSnapshot,
6532
+ data: Object.assign({ source: IncrementalSource.Font }, p),
6533
+ })),
6534
+ selectionCb: (p) => {
6535
+ wrappedEmit(wrapEvent({
6536
+ type: EventType.IncrementalSnapshot,
6537
+ data: Object.assign({ source: IncrementalSource.Selection }, p),
6538
+ }));
6539
+ },
6540
+ blockClass,
6541
+ ignoreClass,
6542
+ maskTextClass,
6543
+ maskTextSelector,
6544
+ maskInputOptions,
6545
+ inlineStylesheet,
6546
+ sampling,
6547
+ recordCanvas,
6548
+ inlineImages,
6549
+ userTriggeredOnInput,
6550
+ collectFonts,
6551
+ doc,
6552
+ maskInputFn,
6553
+ maskTextFn,
6554
+ keepIframeSrcFn,
6555
+ blockSelector,
6556
+ slimDOMOptions,
6557
+ dataURLOptions,
6558
+ mirror,
6559
+ iframeManager,
6560
+ stylesheetManager,
6561
+ shadowDomManager,
6562
+ canvasManager,
6563
+ ignoreCSSAttributes,
6564
+ plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter((p) => p.observer)) === null || _a === void 0 ? void 0 : _a.map((p) => ({
6565
+ observer: p.observer,
6566
+ options: p.options,
6567
+ callback: (payload) => wrappedEmit(wrapEvent({
6568
+ type: EventType.Plugin,
6569
+ data: {
6570
+ plugin: p.name,
6571
+ payload,
6572
+ },
6573
+ })),
6574
+ }))) || [],
6575
+ }, hooks);
6576
+ };
6577
+ iframeManager.addLoadListener((iframeEl) => {
6578
+ handlers.push(observe(iframeEl.contentDocument));
6579
+ });
6580
+ const init = () => {
6581
+ takeFullSnapshot();
6582
+ handlers.push(observe(document));
6583
+ recording = true;
6584
+ };
6585
+ if (document.readyState === 'interactive' ||
6586
+ document.readyState === 'complete') {
6587
+ init();
6588
+ }
6589
+ else {
6590
+ handlers.push(on('load', () => {
6591
+ wrappedEmit(wrapEvent({
6592
+ type: EventType.Load,
6593
+ data: {},
6594
+ }));
6595
+ init();
6596
+ }, window));
6597
+ }
6598
+ return () => {
6599
+ handlers.forEach((h) => h());
6600
+ recording = false;
6601
+ };
6602
+ }
6603
+ catch (error) {
6604
+ console.warn(error);
6605
+ }
6606
+ }
6607
+ record.addCustomEvent = (tag, payload) => {
6608
+ if (!recording) {
6609
+ throw new Error('please add custom event after start recording');
6610
+ }
6611
+ wrappedEmit(wrapEvent({
6612
+ type: EventType.Custom,
6613
+ data: {
6614
+ tag,
6615
+ payload,
6616
+ },
6617
+ }));
6618
+ };
6619
+ record.freezePage = () => {
6620
+ mutationBuffers.forEach((buf) => buf.freeze());
6621
+ };
6622
+ record.takeFullSnapshot = (isCheckout) => {
6623
+ if (!recording) {
6624
+ throw new Error('please take full snapshot after start recording');
6625
+ }
6626
+ takeFullSnapshot(isCheckout);
6627
+ };
6628
+ record.mirror = mirror;
6629
+
2721
6630
  /**
2722
- * Session Recording Module
2723
- * Captures user interactions for replay
6631
+ * Session Recording Module with RRWeb Integration
6632
+ * Records user interactions exactly like Mixpanel does
2724
6633
  */
2725
- const DEFAULT_CONFIG = {
6634
+ const DEFAULT_CONFIG$1 = {
2726
6635
  enabled: true,
2727
- recordMouse: true,
2728
- recordScroll: true,
2729
- recordInput: true,
2730
- recordMutations: true,
2731
- maskInputs: true,
2732
- maskSelectors: ['[type="password"]', '[data-sensitive]', '.sensitive'],
2733
- maxDurationSeconds: 300,
2734
- sampleRate: 1.0,
6636
+ maskAllInputs: true,
6637
+ maskInputOptions: {
6638
+ color: '#D1D5DB',
6639
+ textClass: 'masked-text',
6640
+ colorClass: 'masked-color',
6641
+ },
6642
+ // Mask sensitive inputs with asterisks like Mixpanel
6643
+ maskInputFn: (text, element) => {
6644
+ if (!element || !text)
6645
+ return text;
6646
+ const tagName = element.tagName?.toLowerCase();
6647
+ const inputType = element?.type?.toLowerCase();
6648
+ // Always mask passwords
6649
+ if (inputType === 'password') {
6650
+ return '*'.repeat(Math.min(text.length, 10));
6651
+ }
6652
+ // Mask credit card fields
6653
+ const inputElement = element;
6654
+ if (inputType === 'tel' && (inputElement.autocomplete?.includes('cc-') ||
6655
+ inputElement.name?.toLowerCase().includes('card') ||
6656
+ element.className?.toLowerCase().includes('card'))) {
6657
+ return '*'.repeat(Math.min(text.length, 16));
6658
+ }
6659
+ // Mask email if contains sensitive patterns
6660
+ if (inputType === 'email' || tagName === 'input') {
6661
+ const isSensitive = inputElement.name?.toLowerCase().includes('email') ||
6662
+ element.id?.toLowerCase().includes('email') ||
6663
+ inputElement.placeholder?.toLowerCase().includes('email');
6664
+ if (isSensitive) {
6665
+ const atIndex = text.indexOf('@');
6666
+ if (atIndex > 2) {
6667
+ return text.substring(0, 2) + '*'.repeat(atIndex - 2) + text.substring(atIndex);
6668
+ }
6669
+ }
6670
+ }
6671
+ // Mask other sensitive inputs
6672
+ const sensitivePatterns = ['ssn', 'social', 'security', 'tax', 'id', 'license'];
6673
+ const elementInfo = `${element.name || ''} ${element.id || ''} ${element.className || ''}`.toLowerCase();
6674
+ if (sensitivePatterns.some(pattern => elementInfo.includes(pattern))) {
6675
+ if (text.length <= 4) {
6676
+ return '*'.repeat(text.length);
6677
+ }
6678
+ return text.substring(0, 2) + '*'.repeat(text.length - 4) + text.substring(text.length - 2);
6679
+ }
6680
+ return text;
6681
+ },
6682
+ // Mask sensitive text content
6683
+ maskTextFn: (text, element) => {
6684
+ if (!element || !text)
6685
+ return text;
6686
+ // Check if element has sensitive data attributes or classes
6687
+ const sensitiveMarkers = ['data-sensitive', 'sensitive', 'private', 'confidential'];
6688
+ const elementClasses = element.className?.toLowerCase() || '';
6689
+ const elementAttrs = Array.from(element.attributes || [])
6690
+ .map(attr => attr.name.toLowerCase()).join(' ');
6691
+ if (sensitiveMarkers.some(marker => elementClasses.includes(marker) || elementAttrs.includes(marker))) {
6692
+ return '*'.repeat(Math.min(text.length, 20));
6693
+ }
6694
+ return text;
6695
+ },
6696
+ blockClass: 'cf-block',
6697
+ blockSelector: '.cf-block, [data-cf-block]',
6698
+ ignoreClass: 'cf-ignore',
6699
+ maskTextClass: 'cf-mask-text',
6700
+ maskTextSelector: '.cf-mask-text, [data-sensitive], .sensitive',
6701
+ maskAllText: false,
6702
+ slimDOMOptions: {
6703
+ script: true,
6704
+ comment: true,
6705
+ headFavicon: true,
6706
+ headWhitespace: true,
6707
+ headMetaDescKeywords: true,
6708
+ headMetaSocial: true,
6709
+ headMetaRobots: true,
6710
+ headMetaHttpEquiv: true,
6711
+ headMetaAuthorship: true,
6712
+ headMetaVerification: true,
6713
+ },
6714
+ recordCanvas: true,
6715
+ collectFonts: false,
6716
+ sampling: {
6717
+ mousemove: 50, // Sample every 50ms
6718
+ mouseInteraction: true,
6719
+ scroll: 150, // Sample every 150ms
6720
+ media: 800,
6721
+ input: 'last',
6722
+ },
2735
6723
  };
2736
- class SessionRecording {
6724
+ class SessionRecordingRRWeb {
2737
6725
  constructor(config = {}) {
2738
6726
  this.events = [];
2739
6727
  this.startTime = 0;
2740
6728
  this.isRecording = false;
2741
- this.mutationObserver = null;
2742
- this.listeners = [];
2743
- this.config = { ...DEFAULT_CONFIG, ...config };
6729
+ this.stopFn = null;
6730
+ this.recordingOptions = {};
6731
+ this.config = { ...DEFAULT_CONFIG$1, ...config };
2744
6732
  this.sessionId = this.generateSessionId();
6733
+ this.setupRecordingOptions();
2745
6734
  }
2746
6735
  generateSessionId() {
2747
- return `sess_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
6736
+ return `session_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
6737
+ }
6738
+ setupRecordingOptions() {
6739
+ this.recordingOptions = {
6740
+ emit: (event) => {
6741
+ if (this.isRecording) {
6742
+ this.events.push(event);
6743
+ // Limit buffer size to prevent memory issues
6744
+ if (this.events.length > 50000) {
6745
+ this.events.splice(0, 10000); // Remove oldest 10k events
6746
+ console.warn('🎥 [SessionRecording] Event buffer full, removing old events');
6747
+ }
6748
+ }
6749
+ },
6750
+ maskInputOptions: this.config.maskInputOptions,
6751
+ maskInputFn: this.config.maskInputFn,
6752
+ maskTextFn: this.config.maskTextFn,
6753
+ blockClass: this.config.blockClass,
6754
+ blockSelector: this.config.blockSelector,
6755
+ ignoreClass: this.config.ignoreClass,
6756
+ maskTextClass: this.config.maskTextClass,
6757
+ maskTextSelector: this.config.maskTextSelector,
6758
+ maskAllInputs: this.config.maskAllInputs,
6759
+ maskAllText: this.config.maskAllText,
6760
+ slimDOMOptions: this.config.slimDOMOptions,
6761
+ recordCanvas: this.config.recordCanvas,
6762
+ collectFonts: this.config.collectFonts,
6763
+ sampling: this.config.sampling,
6764
+ plugins: this.config.plugins,
6765
+ };
2748
6766
  }
2749
6767
  /**
2750
- * Start recording the session
6768
+ * Start recording using RRWeb
2751
6769
  */
2752
6770
  start() {
2753
6771
  if (this.isRecording || !this.config.enabled)
2754
6772
  return;
2755
- console.log(' [SessionRecording] Starting session recording...', {
6773
+ console.log('🎥 [SessionRecording] Starting RRWeb recording...', {
2756
6774
  sessionId: this.sessionId,
2757
6775
  config: this.config
2758
6776
  });
2759
6777
  this.isRecording = true;
2760
6778
  this.startTime = Date.now();
2761
6779
  this.events = [];
2762
- // Record initial DOM snapshot
2763
- this.recordSnapshot();
2764
- // Setup event listeners
2765
- if (this.config.recordMouse) {
2766
- this.setupMouseTracking();
2767
- console.log(' [SessionRecording] Mouse tracking enabled');
2768
- }
2769
- if (this.config.recordScroll) {
2770
- this.setupScrollTracking();
2771
- console.log(' [SessionRecording] Scroll tracking enabled');
2772
- }
2773
- if (this.config.recordInput) {
2774
- this.setupInputTracking();
2775
- console.log(' [SessionRecording] Input tracking enabled');
6780
+ try {
6781
+ // Start RRWeb recording
6782
+ this.stopFn = record(this.recordingOptions);
6783
+ console.log('🎥 [SessionRecording] RRWeb recording started successfully');
2776
6784
  }
2777
- if (this.config.recordMutations) {
2778
- this.setupMutationObserver();
2779
- console.log(' [SessionRecording] Mutation observer enabled');
6785
+ catch (error) {
6786
+ console.error('🎥 [SessionRecording] Failed to start recording:', error);
6787
+ this.isRecording = false;
2780
6788
  }
2781
- // Track navigation
2782
- this.setupNavigationTracking();
2783
- // Track resize
2784
- this.setupResizeTracking();
2785
- console.log(' [SessionRecording] Session recording started successfully');
2786
- // Auto-stop after max duration
2787
- setTimeout(() => {
2788
- if (this.isRecording) {
2789
- this.stop();
2790
- }
2791
- }, this.config.maxDurationSeconds * 1000);
2792
6789
  }
2793
6790
  /**
2794
6791
  * Stop recording
@@ -2796,16 +6793,15 @@ class SessionRecording {
2796
6793
  stop() {
2797
6794
  if (!this.isRecording)
2798
6795
  return;
2799
- this.isRecording = false;
2800
- // Remove all event listeners
2801
- this.listeners.forEach(({ element, event, handler }) => {
2802
- element.removeEventListener(event, handler);
6796
+ console.log('🎥 [SessionRecording] Stopping recording...', {
6797
+ sessionId: this.sessionId,
6798
+ eventCount: this.events.length,
6799
+ duration: this.getDuration()
2803
6800
  });
2804
- this.listeners = [];
2805
- // Disconnect mutation observer
2806
- if (this.mutationObserver) {
2807
- this.mutationObserver.disconnect();
2808
- this.mutationObserver = null;
6801
+ this.isRecording = false;
6802
+ if (this.stopFn) {
6803
+ this.stopFn();
6804
+ this.stopFn = null;
2809
6805
  }
2810
6806
  }
2811
6807
  /**
@@ -2815,18 +6811,24 @@ class SessionRecording {
2815
6811
  return this.sessionId;
2816
6812
  }
2817
6813
  /**
2818
- * Get recorded events
6814
+ * Get recorded events (RRWeb format)
2819
6815
  */
2820
6816
  getEvents() {
2821
6817
  return [...this.events];
2822
6818
  }
2823
6819
  /**
2824
- * Get recording duration in seconds
6820
+ * Get recording duration in milliseconds
2825
6821
  */
2826
- getDuration() {
6822
+ getDurationMs() {
2827
6823
  if (!this.startTime)
2828
6824
  return 0;
2829
- return Math.round((Date.now() - this.startTime) / 1000);
6825
+ return Date.now() - this.startTime;
6826
+ }
6827
+ /**
6828
+ * Get recording duration in seconds
6829
+ */
6830
+ getDuration() {
6831
+ return Math.round(this.getDurationMs() / 1000);
2830
6832
  }
2831
6833
  /**
2832
6834
  * Clear events (for chunked uploads)
@@ -2835,13 +6837,26 @@ class SessionRecording {
2835
6837
  this.events = [];
2836
6838
  }
2837
6839
  /**
2838
- * Get recording data for submission
6840
+ * Get events since last clear (for incremental uploads)
6841
+ */
6842
+ getEventsSinceLast(count = 1000) {
6843
+ if (this.events.length <= count) {
6844
+ const allEvents = [...this.events];
6845
+ this.clearEvents();
6846
+ return allEvents;
6847
+ }
6848
+ const batch = this.events.splice(0, count);
6849
+ return batch;
6850
+ }
6851
+ /**
6852
+ * Get recording data for submission (compatible with backend)
2839
6853
  */
2840
6854
  getRecordingData() {
2841
6855
  console.log('🎥 [SessionRecording] getRecordingData called:', {
2842
6856
  eventCount: this.events.length,
2843
6857
  sessionId: this.sessionId,
2844
6858
  duration: this.getDuration(),
6859
+ durationMs: this.getDurationMs(),
2845
6860
  isRecording: this.isRecording,
2846
6861
  startTime: this.startTime
2847
6862
  });
@@ -2852,290 +6867,87 @@ class SessionRecording {
2852
6867
  const data = {
2853
6868
  events: [...this.events],
2854
6869
  sessionId: this.sessionId,
2855
- duration: this.getDuration(),
6870
+ duration: this.getDurationMs(), // Return milliseconds for precision
2856
6871
  };
2857
6872
  console.log('🎥 [SessionRecording] Returning recording data:', {
2858
6873
  eventCount: data.events.length,
2859
6874
  duration: data.duration,
2860
- firstEventType: data.events[0]?.type,
2861
- lastEventType: data.events[data.events.length - 1]?.type
6875
+ firstEvent: data.events[0]?.type,
6876
+ lastEvent: data.events[data.events.length - 1]?.type,
6877
+ hasSnapshot: data.events.some(e => e.type === 2), // Meta event type for snapshot
6878
+ hasMutations: data.events.some(e => e.type === 3), // Mutation event
6879
+ hasMouseMoves: data.events.some(e => e.type === 3), // Mouse move event
2862
6880
  });
2863
6881
  return data;
2864
6882
  }
2865
- addEvent(type, data) {
2866
- // Sample rate filtering
2867
- if (Math.random() > this.config.sampleRate)
2868
- return;
2869
- this.events.push({
2870
- type,
2871
- timestamp: Date.now() - this.startTime,
2872
- data,
2873
- });
2874
- // Limit event buffer size
2875
- if (this.events.length > 10000) {
2876
- this.events.shift();
2877
- }
6883
+ /**
6884
+ * Check if currently recording
6885
+ */
6886
+ isCurrentlyRecording() {
6887
+ return this.isRecording;
2878
6888
  }
2879
- recordSnapshot() {
2880
- // Record initial page state
2881
- this.addEvent('mutation', {
2882
- action: 'snapshot',
2883
- html: this.sanitizeHTML(document.documentElement.outerHTML),
2884
- url: window.location.href,
2885
- title: document.title,
2886
- viewport: {
2887
- width: window.innerWidth,
2888
- height: window.innerHeight,
2889
- },
2890
- });
2891
- }
2892
- setupMouseTracking() {
2893
- let lastX = 0, lastY = 0;
2894
- let throttleTimer = null;
2895
- const handler = (e) => {
2896
- // Throttle to ~30fps
2897
- if (throttleTimer)
2898
- return;
2899
- throttleTimer = window.setTimeout(() => {
2900
- throttleTimer = null;
2901
- }, 33);
2902
- // Only record if position changed significantly
2903
- if (Math.abs(e.clientX - lastX) > 5 || Math.abs(e.clientY - lastY) > 5) {
2904
- lastX = e.clientX;
2905
- lastY = e.clientY;
2906
- this.addEvent('mouse', {
2907
- action: 'move',
2908
- x: e.clientX,
2909
- y: e.clientY,
2910
- });
2911
- }
2912
- };
2913
- const clickHandler = (e) => {
2914
- this.addEvent('mouse', {
2915
- action: 'click',
2916
- x: e.clientX,
2917
- y: e.clientY,
2918
- target: this.getElementSelector(e.target),
2919
- });
2920
- };
2921
- document.addEventListener('mousemove', handler, { passive: true });
2922
- document.addEventListener('click', clickHandler, { passive: true });
2923
- this.listeners.push({ element: document, event: 'mousemove', handler: handler }, { element: document, event: 'click', handler: clickHandler });
2924
- }
2925
- setupScrollTracking() {
2926
- let throttleTimer = null;
2927
- const handler = () => {
2928
- if (throttleTimer)
2929
- return;
2930
- throttleTimer = window.setTimeout(() => {
2931
- throttleTimer = null;
2932
- }, 100);
2933
- this.addEvent('scroll', {
2934
- x: window.scrollX,
2935
- y: window.scrollY,
2936
- });
2937
- };
2938
- window.addEventListener('scroll', handler, { passive: true });
2939
- this.listeners.push({ element: window, event: 'scroll', handler });
2940
- }
2941
- setupInputTracking() {
2942
- const handler = (e) => {
2943
- const target = e.target;
2944
- if (!target.tagName)
2945
- return;
2946
- const isSensitive = this.isSensitiveElement(target);
2947
- this.addEvent('input', {
2948
- selector: this.getElementSelector(target),
2949
- value: isSensitive ? '********' : target.value?.substring(0, 100),
2950
- type: target.type || 'text',
2951
- });
2952
- };
2953
- document.addEventListener('input', handler, { passive: true });
2954
- this.listeners.push({ element: document, event: 'input', handler });
2955
- }
2956
- setupMutationObserver() {
2957
- this.mutationObserver = new MutationObserver((mutations) => {
2958
- const changes = [];
2959
- mutations.forEach((mutation) => {
2960
- if (mutation.type === 'childList') {
2961
- mutation.addedNodes.forEach((node) => {
2962
- if (node.nodeType === Node.ELEMENT_NODE) {
2963
- changes.push({
2964
- action: 'add',
2965
- target: this.getElementSelector(mutation.target),
2966
- html: this.sanitizeHTML(node.outerHTML || ''),
2967
- });
2968
- }
2969
- });
2970
- mutation.removedNodes.forEach((node) => {
2971
- if (node.nodeType === Node.ELEMENT_NODE) {
2972
- changes.push({
2973
- action: 'remove',
2974
- target: this.getElementSelector(mutation.target),
2975
- selector: this.getElementSelector(node),
2976
- });
2977
- }
2978
- });
2979
- }
2980
- else if (mutation.type === 'attributes') {
2981
- changes.push({
2982
- action: 'attribute',
2983
- target: this.getElementSelector(mutation.target),
2984
- attribute: mutation.attributeName,
2985
- value: mutation.target.getAttribute(mutation.attributeName),
2986
- });
2987
- }
2988
- });
2989
- if (changes.length > 0) {
2990
- this.addEvent('mutation', { changes });
2991
- }
2992
- });
2993
- this.mutationObserver.observe(document.body, {
2994
- childList: true,
2995
- subtree: true,
2996
- attributes: true,
2997
- attributeFilter: ['class', 'style', 'src', 'href'],
2998
- });
2999
- }
3000
- setupNavigationTracking() {
3001
- const handler = () => {
3002
- this.addEvent('navigation', {
3003
- url: window.location.href,
3004
- title: document.title,
3005
- });
3006
- };
3007
- window.addEventListener('popstate', handler);
3008
- this.listeners.push({ element: window, event: 'popstate', handler });
3009
- }
3010
- setupResizeTracking() {
3011
- let throttleTimer = null;
3012
- const handler = () => {
3013
- if (throttleTimer)
3014
- return;
3015
- throttleTimer = window.setTimeout(() => {
3016
- throttleTimer = null;
3017
- }, 200);
3018
- this.addEvent('resize', {
3019
- width: window.innerWidth,
3020
- height: window.innerHeight,
3021
- });
3022
- };
3023
- window.addEventListener('resize', handler, { passive: true });
3024
- this.listeners.push({ element: window, event: 'resize', handler });
3025
- }
3026
- getElementSelector(element) {
3027
- if (!element || !element.tagName)
3028
- return '';
3029
- const parts = [];
3030
- let current = element;
3031
- while (current && current.tagName !== 'HTML') {
3032
- let selector = current.tagName.toLowerCase();
3033
- if (current.id) {
3034
- selector += `#${current.id}`;
3035
- parts.unshift(selector);
3036
- break;
3037
- }
3038
- else if (current.className && typeof current.className === 'string') {
3039
- const classes = current.className.trim().split(/\s+/).slice(0, 2);
3040
- if (classes.length > 0 && classes[0]) {
3041
- selector += `.${classes.join('.')}`;
3042
- }
3043
- }
3044
- parts.unshift(selector);
3045
- current = current.parentElement;
3046
- }
3047
- return parts.slice(-4).join(' > ');
3048
- }
3049
- isSensitiveElement(element) {
3050
- if (this.config.maskInputs) {
3051
- const type = element.getAttribute('type');
3052
- if (type === 'password' || type === 'credit-card')
3053
- return true;
3054
- }
3055
- return this.config.maskSelectors.some((selector) => {
3056
- try {
3057
- return element.matches(selector);
3058
- }
3059
- catch {
3060
- return false;
3061
- }
3062
- });
3063
- }
3064
- sanitizeHTML(html) {
3065
- // Remove script contents
3066
- html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '<script></script>');
3067
- // Mask sensitive inputs
3068
- if (this.config.maskInputs) {
3069
- html = html.replace(/(<input[^>]*type=["']password["'][^>]*value=["'])[^"']*["']/gi, '$1••••••••"');
3070
- }
3071
- // Truncate if too large
3072
- if (html.length > 500000) {
3073
- html = html.substring(0, 500000) + '<!-- truncated -->';
3074
- }
3075
- return html;
3076
- }
3077
- }
3078
-
3079
- /**
3080
- * CheckFlow Privacy Module Types
3081
- * Configuration and types for automatic PII masking
3082
- */
3083
- const DEFAULT_PRIVACY_CONFIG = {
3084
- enabled: true,
3085
- autoMask: {
3086
- emails: true,
3087
- creditCards: true,
3088
- phoneNumbers: true,
3089
- passwords: true,
3090
- socialSecurity: true,
3091
- ipAddresses: false,
3092
- customPatterns: [],
3093
- },
3094
- excludeSelectors: [],
3095
- includeSelectors: [],
3096
- maskChar: '•',
3097
- maskLength: 'preserve',
3098
- fixedMaskLength: 8,
3099
- };
3100
- const SENSITIVE_INPUT_TYPES = [
3101
- 'password',
3102
- 'email',
3103
- 'tel',
3104
- 'credit-card',
3105
- 'cc-number',
3106
- 'cc-csc',
3107
- 'cc-exp',
3108
- ];
3109
- const SENSITIVE_AUTOCOMPLETE_VALUES = [
3110
- 'cc-number',
3111
- 'cc-csc',
3112
- 'cc-exp',
3113
- 'cc-exp-month',
3114
- 'cc-exp-year',
3115
- 'cc-name',
3116
- 'cc-type',
3117
- 'new-password',
3118
- 'current-password',
3119
- ];
3120
-
3121
- /**
3122
- * CheckFlow Privacy Detector
3123
- * Regex patterns for detecting PII (Personally Identifiable Information)
3124
- */
3125
- const PATTERNS = {
3126
- email: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
3127
- creditCard: /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})\b/g,
3128
- creditCardSpaced: /\b(?:\d{4}[-\s]?){3}\d{4}\b/g,
3129
- phone: /(?:\+?1[-.\s]?)?(?:\([0-9]{3}\)|[0-9]{3})[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b/g,
3130
- phoneFR: /(?:(?:\+|00)33|0)\s*[1-9](?:[\s.-]*\d{2}){4}/g,
3131
- ssn: /\b\d{3}[-]?\d{2}[-]?\d{4}\b/g,
3132
- ipv4: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,
3133
- ipv6: /\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b/g,
3134
- };
3135
- class PrivacyDetector {
3136
- constructor(customPatterns = []) {
3137
- this.customPatterns = [];
3138
- this.customPatterns = customPatterns;
6889
+ }
6890
+
6891
+ /**
6892
+ * CheckFlow Privacy Module Types
6893
+ * Configuration and types for automatic PII masking
6894
+ */
6895
+ const DEFAULT_PRIVACY_CONFIG = {
6896
+ enabled: true,
6897
+ autoMask: {
6898
+ emails: true,
6899
+ creditCards: true,
6900
+ phoneNumbers: true,
6901
+ passwords: true,
6902
+ socialSecurity: true,
6903
+ ipAddresses: false,
6904
+ customPatterns: [],
6905
+ },
6906
+ excludeSelectors: [],
6907
+ includeSelectors: [],
6908
+ maskChar: '•',
6909
+ maskLength: 'preserve',
6910
+ fixedMaskLength: 8,
6911
+ };
6912
+ const SENSITIVE_INPUT_TYPES = [
6913
+ 'password',
6914
+ 'email',
6915
+ 'tel',
6916
+ 'credit-card',
6917
+ 'cc-number',
6918
+ 'cc-csc',
6919
+ 'cc-exp',
6920
+ ];
6921
+ const SENSITIVE_AUTOCOMPLETE_VALUES = [
6922
+ 'cc-number',
6923
+ 'cc-csc',
6924
+ 'cc-exp',
6925
+ 'cc-exp-month',
6926
+ 'cc-exp-year',
6927
+ 'cc-name',
6928
+ 'cc-type',
6929
+ 'new-password',
6930
+ 'current-password',
6931
+ ];
6932
+
6933
+ /**
6934
+ * CheckFlow Privacy Detector
6935
+ * Regex patterns for detecting PII (Personally Identifiable Information)
6936
+ */
6937
+ const PATTERNS = {
6938
+ email: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
6939
+ creditCard: /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})\b/g,
6940
+ creditCardSpaced: /\b(?:\d{4}[-\s]?){3}\d{4}\b/g,
6941
+ phone: /(?:\+?1[-.\s]?)?(?:\([0-9]{3}\)|[0-9]{3})[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b/g,
6942
+ phoneFR: /(?:(?:\+|00)33|0)\s*[1-9](?:[\s.-]*\d{2}){4}/g,
6943
+ ssn: /\b\d{3}[-]?\d{2}[-]?\d{4}\b/g,
6944
+ ipv4: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,
6945
+ ipv6: /\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b/g,
6946
+ };
6947
+ class PrivacyDetector {
6948
+ constructor(customPatterns = []) {
6949
+ this.customPatterns = [];
6950
+ this.customPatterns = customPatterns;
3139
6951
  }
3140
6952
  /**
3141
6953
  * Add a custom pattern
@@ -4280,7 +8092,7 @@ class CheckFlow {
4280
8092
  }
4281
8093
  // Start session recording
4282
8094
  if (this.options.captureSessionRecording !== false) {
4283
- this.sessionRecording = new SessionRecording();
8095
+ this.sessionRecording = new SessionRecordingRRWeb();
4284
8096
  this.sessionRecording.start();
4285
8097
  this.log('Session recording started');
4286
8098
  }
@@ -4565,6 +8377,364 @@ function createCheckFlow(apiKey, options) {
4565
8377
  return new CheckFlow(apiKey, options).init();
4566
8378
  }
4567
8379
 
8380
+ /**
8381
+ * Session Recording Module
8382
+ * Captures user interactions for replay
8383
+ */
8384
+ const DEFAULT_CONFIG = {
8385
+ enabled: true,
8386
+ recordMouse: true,
8387
+ recordScroll: true,
8388
+ recordInput: true,
8389
+ recordMutations: true,
8390
+ maskInputs: true,
8391
+ maskSelectors: ['[type="password"]', '[data-sensitive]', '.sensitive'],
8392
+ maxDurationSeconds: 300,
8393
+ sampleRate: 1.0,
8394
+ };
8395
+ class SessionRecording {
8396
+ constructor(config = {}) {
8397
+ this.events = [];
8398
+ this.startTime = 0;
8399
+ this.isRecording = false;
8400
+ this.mutationObserver = null;
8401
+ this.listeners = [];
8402
+ this.config = { ...DEFAULT_CONFIG, ...config };
8403
+ this.sessionId = this.generateSessionId();
8404
+ }
8405
+ generateSessionId() {
8406
+ return `sess_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
8407
+ }
8408
+ /**
8409
+ * Start recording the session
8410
+ */
8411
+ start() {
8412
+ if (this.isRecording || !this.config.enabled)
8413
+ return;
8414
+ console.log(' [SessionRecording] Starting session recording...', {
8415
+ sessionId: this.sessionId,
8416
+ config: this.config
8417
+ });
8418
+ this.isRecording = true;
8419
+ this.startTime = Date.now();
8420
+ this.events = [];
8421
+ // Record initial DOM snapshot
8422
+ this.recordSnapshot();
8423
+ // Setup event listeners
8424
+ if (this.config.recordMouse) {
8425
+ this.setupMouseTracking();
8426
+ console.log(' [SessionRecording] Mouse tracking enabled');
8427
+ }
8428
+ if (this.config.recordScroll) {
8429
+ this.setupScrollTracking();
8430
+ console.log(' [SessionRecording] Scroll tracking enabled');
8431
+ }
8432
+ if (this.config.recordInput) {
8433
+ this.setupInputTracking();
8434
+ console.log(' [SessionRecording] Input tracking enabled');
8435
+ }
8436
+ if (this.config.recordMutations) {
8437
+ this.setupMutationObserver();
8438
+ console.log(' [SessionRecording] Mutation observer enabled');
8439
+ }
8440
+ // Track navigation
8441
+ this.setupNavigationTracking();
8442
+ // Track resize
8443
+ this.setupResizeTracking();
8444
+ console.log(' [SessionRecording] Session recording started successfully');
8445
+ // Auto-stop after max duration
8446
+ setTimeout(() => {
8447
+ if (this.isRecording) {
8448
+ this.stop();
8449
+ }
8450
+ }, this.config.maxDurationSeconds * 1000);
8451
+ }
8452
+ /**
8453
+ * Stop recording
8454
+ */
8455
+ stop() {
8456
+ if (!this.isRecording)
8457
+ return;
8458
+ this.isRecording = false;
8459
+ // Remove all event listeners
8460
+ this.listeners.forEach(({ element, event, handler }) => {
8461
+ element.removeEventListener(event, handler);
8462
+ });
8463
+ this.listeners = [];
8464
+ // Disconnect mutation observer
8465
+ if (this.mutationObserver) {
8466
+ this.mutationObserver.disconnect();
8467
+ this.mutationObserver = null;
8468
+ }
8469
+ }
8470
+ /**
8471
+ * Get session ID
8472
+ */
8473
+ getSessionId() {
8474
+ return this.sessionId;
8475
+ }
8476
+ /**
8477
+ * Get recorded events
8478
+ */
8479
+ getEvents() {
8480
+ return [...this.events];
8481
+ }
8482
+ /**
8483
+ * Get recording duration in seconds
8484
+ */
8485
+ getDuration() {
8486
+ if (!this.startTime)
8487
+ return 0;
8488
+ return Math.round((Date.now() - this.startTime) / 1000);
8489
+ }
8490
+ /**
8491
+ * Clear events (for chunked uploads)
8492
+ */
8493
+ clearEvents() {
8494
+ this.events = [];
8495
+ }
8496
+ /**
8497
+ * Get recording data for submission
8498
+ */
8499
+ getRecordingData() {
8500
+ console.log('🎥 [SessionRecording] getRecordingData called:', {
8501
+ eventCount: this.events.length,
8502
+ sessionId: this.sessionId,
8503
+ duration: this.getDuration(),
8504
+ isRecording: this.isRecording,
8505
+ startTime: this.startTime
8506
+ });
8507
+ if (this.events.length === 0) {
8508
+ console.warn('🎥 [SessionRecording] No events to return');
8509
+ return null;
8510
+ }
8511
+ const data = {
8512
+ events: [...this.events],
8513
+ sessionId: this.sessionId,
8514
+ duration: this.getDuration(),
8515
+ };
8516
+ console.log('🎥 [SessionRecording] Returning recording data:', {
8517
+ eventCount: data.events.length,
8518
+ duration: data.duration,
8519
+ firstEventType: data.events[0]?.type,
8520
+ lastEventType: data.events[data.events.length - 1]?.type
8521
+ });
8522
+ return data;
8523
+ }
8524
+ addEvent(type, data) {
8525
+ // Sample rate filtering
8526
+ if (Math.random() > this.config.sampleRate)
8527
+ return;
8528
+ this.events.push({
8529
+ type,
8530
+ timestamp: Date.now() - this.startTime,
8531
+ data,
8532
+ });
8533
+ // Limit event buffer size
8534
+ if (this.events.length > 10000) {
8535
+ this.events.shift();
8536
+ }
8537
+ }
8538
+ recordSnapshot() {
8539
+ // Record initial page state
8540
+ this.addEvent('mutation', {
8541
+ action: 'snapshot',
8542
+ html: this.sanitizeHTML(document.documentElement.outerHTML),
8543
+ url: window.location.href,
8544
+ title: document.title,
8545
+ viewport: {
8546
+ width: window.innerWidth,
8547
+ height: window.innerHeight,
8548
+ },
8549
+ });
8550
+ }
8551
+ setupMouseTracking() {
8552
+ let lastX = 0, lastY = 0;
8553
+ let throttleTimer = null;
8554
+ const handler = (e) => {
8555
+ // Throttle to ~30fps
8556
+ if (throttleTimer)
8557
+ return;
8558
+ throttleTimer = window.setTimeout(() => {
8559
+ throttleTimer = null;
8560
+ }, 33);
8561
+ // Only record if position changed significantly
8562
+ if (Math.abs(e.clientX - lastX) > 5 || Math.abs(e.clientY - lastY) > 5) {
8563
+ lastX = e.clientX;
8564
+ lastY = e.clientY;
8565
+ this.addEvent('mouse', {
8566
+ action: 'move',
8567
+ x: e.clientX,
8568
+ y: e.clientY,
8569
+ });
8570
+ }
8571
+ };
8572
+ const clickHandler = (e) => {
8573
+ this.addEvent('mouse', {
8574
+ action: 'click',
8575
+ x: e.clientX,
8576
+ y: e.clientY,
8577
+ target: this.getElementSelector(e.target),
8578
+ });
8579
+ };
8580
+ document.addEventListener('mousemove', handler, { passive: true });
8581
+ document.addEventListener('click', clickHandler, { passive: true });
8582
+ this.listeners.push({ element: document, event: 'mousemove', handler: handler }, { element: document, event: 'click', handler: clickHandler });
8583
+ }
8584
+ setupScrollTracking() {
8585
+ let throttleTimer = null;
8586
+ const handler = () => {
8587
+ if (throttleTimer)
8588
+ return;
8589
+ throttleTimer = window.setTimeout(() => {
8590
+ throttleTimer = null;
8591
+ }, 100);
8592
+ this.addEvent('scroll', {
8593
+ x: window.scrollX,
8594
+ y: window.scrollY,
8595
+ });
8596
+ };
8597
+ window.addEventListener('scroll', handler, { passive: true });
8598
+ this.listeners.push({ element: window, event: 'scroll', handler });
8599
+ }
8600
+ setupInputTracking() {
8601
+ const handler = (e) => {
8602
+ const target = e.target;
8603
+ if (!target.tagName)
8604
+ return;
8605
+ const isSensitive = this.isSensitiveElement(target);
8606
+ this.addEvent('input', {
8607
+ selector: this.getElementSelector(target),
8608
+ value: isSensitive ? '********' : target.value?.substring(0, 100),
8609
+ type: target.type || 'text',
8610
+ });
8611
+ };
8612
+ document.addEventListener('input', handler, { passive: true });
8613
+ this.listeners.push({ element: document, event: 'input', handler });
8614
+ }
8615
+ setupMutationObserver() {
8616
+ this.mutationObserver = new MutationObserver((mutations) => {
8617
+ const changes = [];
8618
+ mutations.forEach((mutation) => {
8619
+ if (mutation.type === 'childList') {
8620
+ mutation.addedNodes.forEach((node) => {
8621
+ if (node.nodeType === Node.ELEMENT_NODE) {
8622
+ changes.push({
8623
+ action: 'add',
8624
+ target: this.getElementSelector(mutation.target),
8625
+ html: this.sanitizeHTML(node.outerHTML || ''),
8626
+ });
8627
+ }
8628
+ });
8629
+ mutation.removedNodes.forEach((node) => {
8630
+ if (node.nodeType === Node.ELEMENT_NODE) {
8631
+ changes.push({
8632
+ action: 'remove',
8633
+ target: this.getElementSelector(mutation.target),
8634
+ selector: this.getElementSelector(node),
8635
+ });
8636
+ }
8637
+ });
8638
+ }
8639
+ else if (mutation.type === 'attributes') {
8640
+ changes.push({
8641
+ action: 'attribute',
8642
+ target: this.getElementSelector(mutation.target),
8643
+ attribute: mutation.attributeName,
8644
+ value: mutation.target.getAttribute(mutation.attributeName),
8645
+ });
8646
+ }
8647
+ });
8648
+ if (changes.length > 0) {
8649
+ this.addEvent('mutation', { changes });
8650
+ }
8651
+ });
8652
+ this.mutationObserver.observe(document.body, {
8653
+ childList: true,
8654
+ subtree: true,
8655
+ attributes: true,
8656
+ attributeFilter: ['class', 'style', 'src', 'href'],
8657
+ });
8658
+ }
8659
+ setupNavigationTracking() {
8660
+ const handler = () => {
8661
+ this.addEvent('navigation', {
8662
+ url: window.location.href,
8663
+ title: document.title,
8664
+ });
8665
+ };
8666
+ window.addEventListener('popstate', handler);
8667
+ this.listeners.push({ element: window, event: 'popstate', handler });
8668
+ }
8669
+ setupResizeTracking() {
8670
+ let throttleTimer = null;
8671
+ const handler = () => {
8672
+ if (throttleTimer)
8673
+ return;
8674
+ throttleTimer = window.setTimeout(() => {
8675
+ throttleTimer = null;
8676
+ }, 200);
8677
+ this.addEvent('resize', {
8678
+ width: window.innerWidth,
8679
+ height: window.innerHeight,
8680
+ });
8681
+ };
8682
+ window.addEventListener('resize', handler, { passive: true });
8683
+ this.listeners.push({ element: window, event: 'resize', handler });
8684
+ }
8685
+ getElementSelector(element) {
8686
+ if (!element || !element.tagName)
8687
+ return '';
8688
+ const parts = [];
8689
+ let current = element;
8690
+ while (current && current.tagName !== 'HTML') {
8691
+ let selector = current.tagName.toLowerCase();
8692
+ if (current.id) {
8693
+ selector += `#${current.id}`;
8694
+ parts.unshift(selector);
8695
+ break;
8696
+ }
8697
+ else if (current.className && typeof current.className === 'string') {
8698
+ const classes = current.className.trim().split(/\s+/).slice(0, 2);
8699
+ if (classes.length > 0 && classes[0]) {
8700
+ selector += `.${classes.join('.')}`;
8701
+ }
8702
+ }
8703
+ parts.unshift(selector);
8704
+ current = current.parentElement;
8705
+ }
8706
+ return parts.slice(-4).join(' > ');
8707
+ }
8708
+ isSensitiveElement(element) {
8709
+ if (this.config.maskInputs) {
8710
+ const type = element.getAttribute('type');
8711
+ if (type === 'password' || type === 'credit-card')
8712
+ return true;
8713
+ }
8714
+ return this.config.maskSelectors.some((selector) => {
8715
+ try {
8716
+ return element.matches(selector);
8717
+ }
8718
+ catch {
8719
+ return false;
8720
+ }
8721
+ });
8722
+ }
8723
+ sanitizeHTML(html) {
8724
+ // Remove script contents
8725
+ html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '<script></script>');
8726
+ // Mask sensitive inputs
8727
+ if (this.config.maskInputs) {
8728
+ html = html.replace(/(<input[^>]*type=["']password["'][^>]*value=["'])[^"']*["']/gi, '$1••••••••"');
8729
+ }
8730
+ // Truncate if too large
8731
+ if (html.length > 500000) {
8732
+ html = html.substring(0, 500000) + '<!-- truncated -->';
8733
+ }
8734
+ return html;
8735
+ }
8736
+ }
8737
+
4568
8738
  const CheckFlowContext = react.createContext(null);
4569
8739
  function CheckFlowProvider({ apiKey, options = {}, children }) {
4570
8740
  const [checkflow, setCheckflow] = react.useState(null);