PluginProbe
Elementor Website Builder – more than just a page builder / 4.3.2
Elementor Website Builder – more than just a page builder v4.3.2
4.3.2 4.3.1 4.3.0 4.3.0-beta3 4.3.0-beta2 4.3.0-beta1 4.2.4 4.2.3 4.2.2 4.2.1 4.2.0 4.1.5 4.2.0-beta2 4.2.0-dev2 4.2.0-beta1 4.1.4 4.1.3 4.1.2 4.1.1 4.1.0 4.1.0-beta3 4.1.0-dev3 4.0.9 4.1.0-beta2 4.1.0-dev2 All 455 releases
elementor / assets / js / common.js

common.js in Elementor Website Builder – more than just a page builder 4.3.2, at assets/js/common.js

24,351 lines 867.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function(_reduxjs_toolkit, _wordpress_i18n) {
2
3 //#region \0rolldown/runtime.js
4 var __create = Object.create;
5 var __defProp$2 = Object.defineProperty;
6 var __name = (target, value) => __defProp$2(target, "name", {
7 value,
8 configurable: true
9 });
10 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11 var __getOwnPropNames = Object.getOwnPropertyNames;
12 var __getProtoOf = Object.getPrototypeOf;
13 var __hasOwnProp = Object.prototype.hasOwnProperty;
14 var __esmMin = (fn, res, err) => () => {
15 if (err) throw err[0];
16 try {
17 return fn && (res = fn(fn = 0)), res;
18 } catch (e) {
19 throw err = [e], e;
20 }
21 };
22 var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
23 var __exportAll = (all, no_symbols) => {
24 let target = {};
25 for (var name in all) {
26 __defProp$2(target, name, {
27 get: all[name],
28 enumerable: true
29 });
30 }
31 if (!no_symbols) {
32 __defProp$2(target, Symbol.toStringTag, { value: "Module" });
33 }
34 return target;
35 };
36 var __copyProps = (to, from, except, desc) => {
37 if (from && typeof from === "object" || typeof from === "function") {
38 for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
39 key = keys[i];
40 if (!__hasOwnProp.call(to, key) && key !== except) {
41 __defProp$2(to, key, {
42 get: ((k) => from[k]).bind(null, key),
43 enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
44 });
45 }
46 }
47 }
48 return to;
49 };
50 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp$2(target, "default", {
51 value: mod,
52 enumerable: true
53 }) : target, mod));
54
55 //#endregion
56
57 //#region node_modules/@babel/runtime/helpers/esm/classCallCheck.js
58 function _classCallCheck(a, n) {
59 if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
60 }
61
62 //#endregion
63 //#region node_modules/@babel/runtime/helpers/esm/typeof.js
64 function _typeof(o) {
65 "@babel/helpers - typeof";
66 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
67 return typeof o;
68 } : function(o) {
69 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
70 }, _typeof(o);
71 }
72 var init_typeof = __esmMin((() => {}));
73
74 //#endregion
75 //#region node_modules/@babel/runtime/helpers/esm/toPrimitive.js
76 function toPrimitive(t, r) {
77 if ("object" != _typeof(t) || !t) return t;
78 var e = t[Symbol.toPrimitive];
79 if (void 0 !== e) {
80 var i = e.call(t, r || "default");
81 if ("object" != _typeof(i)) return i;
82 throw new TypeError("@@toPrimitive must return a primitive value.");
83 }
84 return ("string" === r ? String : Number)(t);
85 }
86 var init_toPrimitive = __esmMin((() => {
87 init_typeof();
88 }));
89
90 //#endregion
91 //#region node_modules/@babel/runtime/helpers/esm/toPropertyKey.js
92 function toPropertyKey(t) {
93 var i = toPrimitive(t, "string");
94 return "symbol" == _typeof(i) ? i : i + "";
95 }
96 var init_toPropertyKey = __esmMin((() => {
97 init_typeof();
98 init_toPrimitive();
99 }));
100
101 //#endregion
102 //#region node_modules/@babel/runtime/helpers/esm/createClass.js
103 init_toPropertyKey();
104 function _defineProperties$1(e, r) {
105 for (var t = 0; t < r.length; t++) {
106 var o = r[t];
107 o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);
108 }
109 }
110 __name(_defineProperties$1, "_defineProperties");
111 function _createClass(e, r, t) {
112 return r && _defineProperties$1(e.prototype, r), t && _defineProperties$1(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e;
113 }
114
115 //#endregion
116 //#region node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
117 function _assertThisInitialized(e) {
118 if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
119 return e;
120 }
121
122 //#endregion
123 //#region node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js
124 init_typeof();
125 function _possibleConstructorReturn(t, e) {
126 if (e && ("object" == _typeof(e) || "function" == typeof e)) return e;
127 if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
128 return _assertThisInitialized(t);
129 }
130
131 //#endregion
132 //#region node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js
133 function _getPrototypeOf(t) {
134 return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(t) {
135 return t.__proto__ || Object.getPrototypeOf(t);
136 }, _getPrototypeOf(t);
137 }
138
139 //#endregion
140 //#region node_modules/@babel/runtime/helpers/esm/superPropBase.js
141 function _superPropBase(t, o) {
142 for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t)););
143 return t;
144 }
145
146 //#endregion
147 //#region node_modules/@babel/runtime/helpers/esm/get.js
148 function _get() {
149 return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function(e, t, r) {
150 var p = _superPropBase(e, t);
151 if (p) {
152 var n = Object.getOwnPropertyDescriptor(p, t);
153 return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
154 }
155 }, _get.apply(null, arguments);
156 }
157
158 //#endregion
159 //#region node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
160 function _setPrototypeOf(t, e) {
161 return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t, e) {
162 return t.__proto__ = e, t;
163 }, _setPrototypeOf(t, e);
164 }
165
166 //#endregion
167 //#region node_modules/@babel/runtime/helpers/esm/inherits.js
168 function _inherits$1(t, e) {
169 if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
170 t.prototype = Object.create(e && e.prototype, { constructor: {
171 value: t,
172 writable: !0,
173 configurable: !0
174 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e);
175 }
176 __name(_inherits$1, "_inherits");
177
178 //#endregion
179 //#region core/common/assets/js/utils/helpers.js
180 var Helpers = /*#__PURE__*/ function() {
181 function Helpers() {
182 _classCallCheck(this, Helpers);
183 }
184 return _createClass(Helpers, [
185 {
186 key: "consoleWarn",
187 value: function consoleWarn() {
188 var _elementorDevTools;
189 (_elementorDevTools = elementorDevTools).consoleWarn.apply(_elementorDevTools, arguments);
190 elementorDevTools.deprecation.deprecated("elementorCommon.helpers.consoleWarn()", "3.7.0", "elementorDevTools.consoleWarn()");
191 }
192 },
193 {
194 key: "consoleError",
195 value: function consoleError(message) {
196 console.error(message);
197 elementorDevTools.deprecation.deprecated("elementorCommon.helpers.consoleError()", "3.7.0", "console.error()");
198 }
199 },
200 {
201 key: "cloneObject",
202 value: function cloneObject(object) {
203 return JSON.parse(JSON.stringify(object));
204 }
205 },
206 {
207 key: "upperCaseWords",
208 value: function upperCaseWords(string) {
209 return (string + "").replace(/^(.)|\s+(.)/g, function($1) {
210 return $1.toUpperCase();
211 });
212 }
213 },
214 {
215 key: "getUniqueId",
216 value: function getUniqueId() {
217 return Math.random().toString(16).substr(2, 7);
218 }
219 }
220 ]);
221 }();
222
223 //#endregion
224 //#region core/common/assets/js/utils/storage.js
225 function _callSuper$34(t, o, e) {
226 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$35() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
227 }
228 __name(_callSuper$34, "_callSuper");
229 function _isNativeReflectConstruct$35() {
230 try {
231 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
232 } catch (t) {}
233 return (_isNativeReflectConstruct$35 = function _isNativeReflectConstruct() {
234 return !!t;
235 })();
236 }
237 __name(_isNativeReflectConstruct$35, "_isNativeReflectConstruct");
238 var _default$11 = /*#__PURE__*/ function(_elementorModules$Mod) {
239 function _default() {
240 _classCallCheck(this, _default);
241 return _callSuper$34(this, _default, arguments);
242 }
243 _inherits$1(_default, _elementorModules$Mod);
244 return _createClass(_default, [
245 {
246 key: "get",
247 value: function get(key, options) {
248 options = options || {};
249 var storage;
250 try {
251 storage = options.session ? sessionStorage : localStorage;
252 } catch (e) {
253 return key ? void 0 : {};
254 }
255 var elementorStorage = storage.getItem("elementor");
256 if (elementorStorage) elementorStorage = JSON.parse(elementorStorage);
257 else elementorStorage = {};
258 if (!elementorStorage.__expiration) elementorStorage.__expiration = {};
259 var expiration = elementorStorage.__expiration;
260 var expirationToCheck = [];
261 if (key) {
262 if (expiration[key]) expirationToCheck = [key];
263 } else expirationToCheck = Object.keys(expiration);
264 var entryExpired = false;
265 expirationToCheck.forEach(function(expirationKey) {
266 if (new Date(expiration[expirationKey]) < /* @__PURE__ */ new Date()) {
267 delete elementorStorage[expirationKey];
268 delete expiration[expirationKey];
269 entryExpired = true;
270 }
271 });
272 if (entryExpired) this.save(elementorStorage, options.session);
273 if (key) return elementorStorage[key];
274 return elementorStorage;
275 }
276 },
277 {
278 key: "set",
279 value: function set(key, value, options) {
280 options = options || {};
281 var elementorStorage = this.get(null, options);
282 elementorStorage[key] = value;
283 if (options.lifetimeInSeconds) {
284 var date = /* @__PURE__ */ new Date();
285 date.setTime(date.getTime() + options.lifetimeInSeconds * 1e3);
286 elementorStorage.__expiration[key] = date.getTime();
287 }
288 this.save(elementorStorage, options.session);
289 }
290 },
291 {
292 key: "save",
293 value: function save(object, session) {
294 var storage;
295 try {
296 storage = session ? sessionStorage : localStorage;
297 } catch (e) {
298 return;
299 }
300 storage.setItem("elementor", JSON.stringify(object));
301 }
302 }
303 ]);
304 }(elementorModules.Module);
305
306 //#endregion
307 //#region core/common/assets/js/utils/debug.js
308 var require_debug = /* @__PURE__ */ __commonJSMin(((exports, module) => {
309 var Debug = function Debug() {
310 var self = this;
311 var errorStack = [];
312 var settings = {};
313 var elements = {};
314 var initSettings = function initSettings() {
315 settings = {
316 debounceDelay: 500,
317 urlsToWatch: ["elementor/assets"]
318 };
319 };
320 var initElements = function initElements() {
321 elements.$window = jQuery(window);
322 };
323 var onError = function onError(event) {
324 var _event$originalEvent;
325 var error = (_event$originalEvent = event.originalEvent) === null || _event$originalEvent === void 0 ? void 0 : _event$originalEvent.error;
326 if (!error) return;
327 var isInWatchList = false;
328 var urlsToWatch = settings.urlsToWatch;
329 jQuery.each(urlsToWatch, function() {
330 if (-1 !== error.stack.indexOf(this)) {
331 isInWatchList = true;
332 return false;
333 }
334 });
335 if (!isInWatchList) return;
336 self.addError({
337 type: error.name,
338 message: error.message,
339 url: event.originalEvent.filename,
340 line: event.originalEvent.lineno,
341 column: event.originalEvent.colno
342 });
343 };
344 var bindEvents = function bindEvents() {
345 elements.$window.on("error", onError);
346 };
347 var init = function init() {
348 initSettings();
349 initElements();
350 bindEvents();
351 self.sendErrors = _.debounce(self.sendErrors, settings.debounceDelay);
352 };
353 this.addURLToWatch = function(url) {
354 settings.urlsToWatch.push(url);
355 };
356 this.addCustomError = function(error, category, tag) {
357 var errorInfo = {
358 type: error.name,
359 message: error.message,
360 url: error.fileName || error.sourceURL,
361 line: error.lineNumber || error.line,
362 column: error.columnNumber || error.column,
363 customFields: {
364 category: category || "general",
365 tag
366 }
367 };
368 if (!errorInfo.url) {
369 var stackInfo = error.stack.match(/\n {4}at (.*?(?=:(\d+):(\d+)))/);
370 if (stackInfo) {
371 errorInfo.url = stackInfo[1];
372 errorInfo.line = stackInfo[2];
373 errorInfo.column = stackInfo[3];
374 }
375 }
376 this.addError(errorInfo);
377 };
378 this.addError = function(errorParams) {
379 var defaultParams = {
380 type: "Error",
381 timestamp: Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3),
382 message: null,
383 url: null,
384 line: null,
385 column: null,
386 customFields: {}
387 };
388 errorStack.push(jQuery.extend(true, defaultParams, errorParams));
389 self.sendErrors();
390 };
391 this.sendErrors = function() {
392 elements.$window.off("error", onError);
393 jQuery.ajax({
394 url: elementorCommon.config.ajax.url,
395 method: "POST",
396 data: {
397 action: "elementor_js_log",
398 _nonce: elementorCommon.ajax.getSettings("nonce"),
399 data: errorStack
400 },
401 success: function success() {
402 errorStack = [];
403 elements.$window.on("error", onError);
404 }
405 });
406 };
407 init();
408 };
409 module.exports = Debug;
410 }));
411
412 //#endregion
413 //#region node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js
414 var import_debug = /* @__PURE__ */ __toESM(require_debug());
415 function _arrayWithHoles(r) {
416 if (Array.isArray(r)) return r;
417 }
418
419 //#endregion
420 //#region node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js
421 function _iterableToArrayLimit(r, l) {
422 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
423 if (null != t) {
424 var e;
425 var n;
426 var i;
427 var u;
428 var a = [];
429 var f = !0;
430 var o = !1;
431 try {
432 if (i = (t = t.call(r)).next, 0 === l) {
433 if (Object(t) !== t) return;
434 f = !1;
435 } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
436 } catch (r) {
437 o = !0, n = r;
438 } finally {
439 try {
440 if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
441 } finally {
442 if (o) throw n;
443 }
444 }
445 return a;
446 }
447 }
448
449 //#endregion
450 //#region node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js
451 function _arrayLikeToArray$1(r, a) {
452 (null == a || a > r.length) && (a = r.length);
453 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
454 return n;
455 }
456 __name(_arrayLikeToArray$1, "_arrayLikeToArray");
457
458 //#endregion
459 //#region node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js
460 function _unsupportedIterableToArray$1(r, a) {
461 if (r) {
462 if ("string" == typeof r) return _arrayLikeToArray$1(r, a);
463 var t = {}.toString.call(r).slice(8, -1);
464 return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$1(r, a) : void 0;
465 }
466 }
467 __name(_unsupportedIterableToArray$1, "_unsupportedIterableToArray");
468
469 //#endregion
470 //#region node_modules/@babel/runtime/helpers/esm/nonIterableRest.js
471 function _nonIterableRest() {
472 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
473 }
474
475 //#endregion
476 //#region node_modules/@babel/runtime/helpers/esm/slicedToArray.js
477 function _slicedToArray(r, e) {
478 return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray$1(r, e) || _nonIterableRest();
479 }
480
481 //#endregion
482 //#region core/common/modules/ajax/assets/js/ajax.js
483 function _callSuper$33(t, o, e) {
484 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$34() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
485 }
486 __name(_callSuper$33, "_callSuper");
487 function _isNativeReflectConstruct$34() {
488 try {
489 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
490 } catch (t) {}
491 return (_isNativeReflectConstruct$34 = function _isNativeReflectConstruct() {
492 return !!t;
493 })();
494 }
495 __name(_isNativeReflectConstruct$34, "_isNativeReflectConstruct");
496 var _default$10 = /*#__PURE__*/ function(_elementorModules$Mod) {
497 function _default() {
498 var _this;
499 _classCallCheck(this, _default);
500 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
501 _this = _callSuper$33(this, _default, [].concat(args));
502 _this.requests = {};
503 _this.cache = {};
504 _this.initRequestConstants();
505 _this.debounceSendBatch = _.debounce(_this.sendBatch.bind(_this), 500);
506 return _this;
507 }
508 _inherits$1(_default, _elementorModules$Mod);
509 return _createClass(_default, [
510 {
511 key: "getDefaultSettings",
512 value: function getDefaultSettings() {
513 return {
514 ajaxParams: {
515 type: "POST",
516 url: elementorCommon.config.ajax.url,
517 data: {},
518 dataType: "json"
519 },
520 actionPrefix: "elementor_"
521 };
522 }
523 },
524 {
525 key: "initRequestConstants",
526 value: function initRequestConstants() {
527 this.requestConstants = { _nonce: this.getSettings("nonce") };
528 }
529 },
530 {
531 key: "addRequestConstant",
532 value: function addRequestConstant(key, value) {
533 this.requestConstants[key] = value;
534 }
535 },
536 {
537 key: "getCacheKey",
538 value: function getCacheKey(request) {
539 return JSON.stringify({
540 unique_id: request.unique_id,
541 data: request.data
542 });
543 }
544 },
545 {
546 key: "loadObjects",
547 value: function loadObjects(options) {
548 var _this2 = this;
549 var dataCollection = {};
550 var deferredArray = [];
551 if (options.before) options.before();
552 options.ids.forEach(function(objectId) {
553 deferredArray.push(_this2.load({
554 action: options.action,
555 unique_id: options.data.unique_id + objectId,
556 data: jQuery.extend({ id: objectId }, options.data)
557 }).done(function(data) {
558 return dataCollection = jQuery.extend(dataCollection, data);
559 }));
560 });
561 jQuery.when.apply(jQuery, deferredArray).done(function() {
562 return options.success(dataCollection);
563 });
564 }
565 },
566 {
567 key: "load",
568 value: function load(request, immediately) {
569 var _this3 = this;
570 if (!request.unique_id) request.unique_id = request.action;
571 if (request.before) request.before();
572 var deferred;
573 var cacheKey = this.getCacheKey(request);
574 if (_.has(this.cache, cacheKey)) deferred = jQuery.Deferred().done(request.success).resolve(this.cache[cacheKey]);
575 else {
576 var _request$error;
577 deferred = this.addRequest(request.action, {
578 data: request.data,
579 unique_id: request.unique_id,
580 success: function success(data) {
581 return _this3.cache[cacheKey] = data;
582 },
583 error: (_request$error = request.error) !== null && _request$error !== void 0 ? _request$error : function() {}
584 }, immediately).done(request.success);
585 }
586 return deferred;
587 }
588 },
589 {
590 key: "cancelRequest",
591 value: function cancelRequest(requestId) {
592 var request = this.requests[requestId];
593 if (!request) return null;
594 if (request.options.deferred.jqXhr) return request.options.deferred.jqXhr.abort("Request canceled");
595 if (request.options.deferred) return request.options.deferred.reject("Request canceled");
596 }
597 },
598 {
599 key: "addRequest",
600 value: function addRequest(action, options, immediately) {
601 options = options || {};
602 if (!options.unique_id) options.unique_id = action;
603 options.deferred = jQuery.Deferred().done(options.success).fail(options.error).always(options.complete);
604 var request = {
605 action,
606 options
607 };
608 if (immediately) {
609 var requests = {};
610 requests[options.unique_id] = request;
611 options.deferred.jqXhr = this.sendBatch(requests);
612 } else {
613 var pendingRequest = this.requests[options.unique_id];
614 if (pendingRequest) {
615 if (this.getCacheKey(pendingRequest.options) === this.getCacheKey(options)) {
616 pendingRequest.options.deferred.done(function(data) {
617 return options.deferred.resolve(data);
618 }).fail(function(data) {
619 return options.deferred.reject(data);
620 });
621 return options.deferred;
622 }
623 pendingRequest.options.deferred.reject("Request replaced");
624 }
625 this.requests[options.unique_id] = request;
626 this.debounceSendBatch();
627 }
628 return options.deferred;
629 }
630 },
631 {
632 key: "sendBatch",
633 value: function sendBatch(requests) {
634 var actions = {};
635 if (!requests) {
636 requests = this.requests;
637 this.requests = {};
638 }
639 Object.entries(requests).forEach(function(_ref) {
640 var _ref2 = _slicedToArray(_ref, 2);
641 var id = _ref2[0];
642 var request = _ref2[1];
643 return actions[id] = {
644 action: request.action,
645 data: request.options.data
646 };
647 });
648 return this.send("ajax", {
649 data: { actions: JSON.stringify(actions) },
650 success: function success(data) {
651 Object.entries(data.responses).forEach(function(_ref3) {
652 var _ref4 = _slicedToArray(_ref3, 2);
653 var id = _ref4[0];
654 var response = _ref4[1];
655 var options = requests[id].options;
656 if (options) {
657 if (response.success) options.deferred.resolve(response.data);
658 else if (!response.success) options.deferred.reject(response.data);
659 }
660 });
661 },
662 error: function error(data) {
663 return Object.values(requests).forEach(function(args) {
664 if (args.options) args.options.deferred.reject(data);
665 });
666 }
667 });
668 }
669 },
670 {
671 key: "prepareSend",
672 value: function prepareSend(action, options) {
673 var _this4 = this;
674 var settings = this.getSettings();
675 var ajaxParams = elementorCommon.helpers.cloneObject(settings.ajaxParams);
676 options = options || {};
677 action = settings.actionPrefix + action;
678 jQuery.extend(ajaxParams, options);
679 var requestConstants = elementorCommon.helpers.cloneObject(this.requestConstants);
680 requestConstants.action = action;
681 var isFormData = ajaxParams.data instanceof FormData;
682 Object.entries(requestConstants).forEach(function(_ref5) {
683 var _ref6 = _slicedToArray(_ref5, 2);
684 var key = _ref6[0];
685 var value = _ref6[1];
686 if (isFormData) ajaxParams.data.append(key, value);
687 else ajaxParams.data[key] = value;
688 });
689 var successCallback = ajaxParams.success;
690 var errorCallback = ajaxParams.error;
691 if (successCallback || errorCallback) {
692 ajaxParams.success = function(response) {
693 if (response.success && successCallback) successCallback(response.data);
694 if (!response.success && errorCallback) errorCallback(response.data);
695 };
696 if (errorCallback) ajaxParams.error = function(data) {
697 return errorCallback(data);
698 };
699 else ajaxParams.error = function(xmlHttpRequest) {
700 if (xmlHttpRequest.readyState || "abort" !== xmlHttpRequest.statusText) _this4.trigger("request:unhandledError", xmlHttpRequest);
701 };
702 }
703 return ajaxParams;
704 }
705 },
706 {
707 key: "send",
708 value: function send(action, options) {
709 return jQuery.ajax(this.prepareSend(action, options));
710 }
711 },
712 {
713 key: "addRequestCache",
714 value: function addRequestCache(request, data) {
715 var cacheKey = this.getCacheKey(request);
716 this.cache[cacheKey] = data;
717 }
718 },
719 {
720 key: "invalidateCache",
721 value: function invalidateCache(request) {
722 var cacheKey = this.getCacheKey(request);
723 delete this.cache[cacheKey];
724 }
725 }
726 ]);
727 }(elementorModules.Module);
728
729 //#endregion
730 //#region node_modules/@babel/runtime/helpers/esm/defineProperty.js
731 function _defineProperty(e, r, t) {
732 return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
733 value: t,
734 enumerable: !0,
735 configurable: !0,
736 writable: !0
737 }) : e[r] = t, e;
738 }
739 var init_defineProperty = __esmMin((() => {
740 init_toPropertyKey();
741 }));
742
743 //#endregion
744 //#region assets/dev/js/modules/imports/instance-type.js
745 init_defineProperty();
746 function _superPropGet$7(t, o, e, r) {
747 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
748 return 2 & r && "function" == typeof p ? function(t) {
749 return p.apply(e, t);
750 } : p;
751 }
752 __name(_superPropGet$7, "_superPropGet");
753 var InstanceType = /*#__PURE__*/ function() {
754 function InstanceType() {
755 var _this = this;
756 _classCallCheck(this, InstanceType);
757 var target = this instanceof InstanceType ? this.constructor : void 0;
758 var prototypes = [];
759 while (target.__proto__ && target.__proto__.name) {
760 prototypes.push(target.__proto__);
761 target = target.__proto__;
762 }
763 prototypes.reverse().forEach(function(proto) {
764 return _this instanceof proto;
765 });
766 }
767 return _createClass(InstanceType, null, [{
768 key: Symbol.hasInstance,
769 value: function value(target) {
770 /**
771 * This is function extending being called each time JS uses instanceOf, since babel use it each time it create new class
772 * its give's opportunity to mange capabilities of instanceOf operator.
773 * saving current class each time will give option later to handle instanceOf manually.
774 */
775 var result = _superPropGet$7(InstanceType, Symbol.hasInstance, this, 2)([target]);
776 if (target && !target.constructor.getInstanceType) return result;
777 if (target) {
778 if (!target.instanceTypes) target.instanceTypes = [];
779 if (!result) {
780 if (this.getInstanceType() === target.constructor.getInstanceType()) result = true;
781 }
782 if (result) {
783 var name = this.getInstanceType === InstanceType.getInstanceType ? "BaseInstanceType" : this.getInstanceType();
784 if (-1 === target.instanceTypes.indexOf(name)) target.instanceTypes.push(name);
785 }
786 }
787 if (!result && target) result = target.instanceTypes && Array.isArray(target.instanceTypes) && -1 !== target.instanceTypes.indexOf(this.getInstanceType());
788 return result;
789 }
790 }, {
791 key: "getInstanceType",
792 value: function getInstanceType() {
793 elementorModules.ForceMethodImplementation();
794 }
795 }]);
796 }();
797
798 //#endregion
799 //#region assets/dev/js/editor/utils/is-instanceof.js
800 function _createForOfIteratorHelper(r, e) {
801 var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
802 if (!t) {
803 if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
804 t && (r = t);
805 var _n = 0;
806 var F = function F() {};
807 return {
808 s: F,
809 n: function n() {
810 return _n >= r.length ? { done: !0 } : {
811 done: !1,
812 value: r[_n++]
813 };
814 },
815 e: function e(r) {
816 throw r;
817 },
818 f: F
819 };
820 }
821 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
822 }
823 var o;
824 var a = !0;
825 var u = !1;
826 return {
827 s: function s() {
828 t = t.call(r);
829 },
830 n: function n() {
831 var r = t.next();
832 return a = r.done, r;
833 },
834 e: function e(r) {
835 u = !0, o = r;
836 },
837 f: function f() {
838 try {
839 a || null == t.return || t.return();
840 } finally {
841 if (u) throw o;
842 }
843 }
844 };
845 }
846 function _unsupportedIterableToArray(r, a) {
847 if (r) {
848 if ("string" == typeof r) return _arrayLikeToArray(r, a);
849 var t = {}.toString.call(r).slice(8, -1);
850 return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
851 }
852 }
853 function _arrayLikeToArray(r, a) {
854 (null == a || a > r.length) && (a = r.length);
855 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
856 return n;
857 }
858 /**
859 * Some FileAPI objects such as FileList, DataTransferItem and DataTransferItemList has inconsistency with the retrieved
860 * object (from events, etc.) and the actual JavaScript object so a regular instanceof doesn't work. This function can
861 * check whether it's instanceof by using the objects constructor and prototype names.
862 *
863 * @param object
864 * @param constructors
865 * @return {boolean}
866 */
867 var is_instanceof_default = /* @__PURE__ */ __name((function(object, constructors) {
868 constructors = Array.isArray(constructors) ? constructors : [constructors];
869 var _iterator = _createForOfIteratorHelper(constructors);
870 var _step;
871 try {
872 for (_iterator.s(); !(_step = _iterator.n()).done;) {
873 var constructor = _step.value;
874 if (object.constructor.name === constructor.prototype[Symbol.toStringTag]) return true;
875 }
876 } catch (err) {
877 _iterator.e(err);
878 } finally {
879 _iterator.f();
880 }
881 return false;
882 }), "default");
883
884 //#endregion
885 //#region assets/dev/js/modules/imports/args-object.js
886 init_typeof();
887 function _callSuper$32(t, o, e) {
888 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$33() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
889 }
890 __name(_callSuper$32, "_callSuper");
891 function _isNativeReflectConstruct$33() {
892 try {
893 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
894 } catch (t) {}
895 return (_isNativeReflectConstruct$33 = function _isNativeReflectConstruct() {
896 return !!t;
897 })();
898 }
899 __name(_isNativeReflectConstruct$33, "_isNativeReflectConstruct");
900 var ArgsObject = /*#__PURE__*/ function(_InstanceType) {
901 /**
902 * Function constructor().
903 *
904 * Create ArgsObject.
905 *
906 * @param {{}} args
907 */
908 function ArgsObject(args) {
909 var _this;
910 _classCallCheck(this, ArgsObject);
911 _this = _callSuper$32(this, ArgsObject);
912 _this.args = args;
913 return _this;
914 }
915 /**
916 * Function requireArgument().
917 *
918 * Validate property in args.
919 *
920 * @param {string} property
921 * @param {{}} args
922 *
923 * @throws {Error}
924 */
925 _inherits$1(ArgsObject, _InstanceType);
926 return _createClass(ArgsObject, [
927 {
928 key: "requireArgument",
929 value: function requireArgument(property) {
930 var args = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this.args;
931 if (!Object.prototype.hasOwnProperty.call(args, property)) throw Error("".concat(property, " is required."));
932 }
933 },
934 {
935 key: "requireArgumentType",
936 value: function requireArgumentType(property, type) {
937 var args = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : this.args;
938 this.requireArgument(property, args);
939 if (_typeof(args[property]) !== type) throw Error("".concat(property, " invalid type: ").concat(type, "."));
940 }
941 },
942 {
943 key: "requireArgumentInstance",
944 value: function requireArgumentInstance(property, instance) {
945 var args = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : this.args;
946 this.requireArgument(property, args);
947 if (!(args[property] instanceof instance) && !is_instanceof_default(args[property], instance)) throw Error("".concat(property, " invalid instance."));
948 }
949 },
950 {
951 key: "requireArgumentConstructor",
952 value: function requireArgumentConstructor(property, type) {
953 var args = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : this.args;
954 this.requireArgument(property, args);
955 if (args[property].constructor.toString() !== type.prototype.constructor.toString()) throw Error("".concat(property, " invalid constructor type."));
956 }
957 }
958 ], [{
959 key: "getInstanceType",
960 value: function getInstanceType() {
961 return "ArgsObject";
962 }
963 }]);
964 }(InstanceType);
965
966 //#endregion
967 //#region modules/web-cli/assets/js/utils/console.js
968 var Console = /*#__PURE__*/ function() {
969 function Console() {
970 _classCallCheck(this, Console);
971 }
972 return _createClass(Console, null, [{
973 key: "error",
974 value: function error(message) {
975 if ($e.devTools) $e.devTools.log.error(message);
976 if (!(message instanceof $e.modules.HookBreak)) console.error(message);
977 }
978 }, {
979 key: "warn",
980 value: function warn() {
981 var _console;
982 var style = "font-size: 12px; background-image: url(\"".concat(elementorWebCliConfig.urls.assets, "images/logo-icon.png\"); background-repeat: no-repeat; background-size: contain;");
983 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
984 args.unshift("%c %c", style, "");
985 (_console = console).warn.apply(_console, args);
986 }
987 }]);
988 }();
989
990 //#endregion
991 //#region modules/web-cli/assets/js/utils/deprecation.js
992 /**
993 * @typedef {Object} Version
994 * @property {number} major1 The first number
995 * @property {number} major2 The second number
996 * @property {number} minor The third number
997 * @property {string} build The fourth number
998 */
999 var softDeprecated = function softDeprecated(name, version, replacement) {
1000 if (elementorWebCliConfig.isDebug) deprecatedMessage("soft", name, version, replacement);
1001 };
1002 var hardDeprecated = function hardDeprecated(name, version, replacement) {
1003 deprecatedMessage("hard", name, version, replacement);
1004 };
1005 var deprecatedMessage = function deprecatedMessage(type, name, version, replacement) {
1006 var message = "`".concat(name, "` is ").concat(type, " deprecated since ").concat(version);
1007 if (replacement) message += " - Use `".concat(replacement, "` instead");
1008 Console.warn(message);
1009 };
1010 var Deprecation = /*#__PURE__*/ function() {
1011 function Deprecation() {
1012 _classCallCheck(this, Deprecation);
1013 }
1014 return _createClass(Deprecation, null, [
1015 {
1016 key: "deprecated",
1017 value: function deprecated(name, version, replacement) {
1018 if (this.isHardDeprecated(version)) hardDeprecated(name, version, replacement);
1019 else softDeprecated(name, version, replacement);
1020 }
1021 },
1022 {
1023 key: "parseVersion",
1024 value: function parseVersion(version) {
1025 var versionParts = version.split(".");
1026 if (versionParts.length < 3 || versionParts.length > 4) throw new RangeError("Invalid Semantic Version string provided");
1027 var _versionParts = _slicedToArray(versionParts, 4);
1028 var major1 = _versionParts[0];
1029 var major2 = _versionParts[1];
1030 var minor = _versionParts[2];
1031 var _versionParts$ = _versionParts[3];
1032 return {
1033 major1: parseInt(major1),
1034 major2: parseInt(major2),
1035 minor: parseInt(minor),
1036 build: _versionParts$ === void 0 ? "" : _versionParts$
1037 };
1038 }
1039 },
1040 {
1041 key: "getTotalMajor",
1042 value: function getTotalMajor(versionObj) {
1043 var total = parseInt("".concat(versionObj.major1).concat(versionObj.major2, "0"));
1044 total = Number((total / 10).toFixed(0));
1045 if (versionObj.major2 > 9) total = versionObj.major2 - 9;
1046 return total;
1047 }
1048 },
1049 {
1050 key: "compareVersion",
1051 value: function compareVersion(version1, version2) {
1052 var _this = this;
1053 return [this.parseVersion(version1), this.parseVersion(version2)].map(function(versionObj) {
1054 return _this.getTotalMajor(versionObj);
1055 }).reduce(function(acc, major) {
1056 return acc - major;
1057 });
1058 }
1059 },
1060 {
1061 key: "isSoftDeprecated",
1062 value: function isSoftDeprecated(version) {
1063 return this.compareVersion(version, elementorWebCliConfig.version) <= 4;
1064 }
1065 },
1066 {
1067 key: "isHardDeprecated",
1068 value: function isHardDeprecated(version) {
1069 var total = this.compareVersion(version, elementorWebCliConfig.version);
1070 return total < 0 || total >= 8;
1071 }
1072 }
1073 ]);
1074 }();
1075
1076 //#endregion
1077 //#region modules/web-cli/assets/js/modules/command-infra.js
1078 function _callSuper$31(t, o, e) {
1079 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$32() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1080 }
1081 __name(_callSuper$31, "_callSuper");
1082 function _isNativeReflectConstruct$32() {
1083 try {
1084 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1085 } catch (t) {}
1086 return (_isNativeReflectConstruct$32 = function _isNativeReflectConstruct() {
1087 return !!t;
1088 })();
1089 }
1090 __name(_isNativeReflectConstruct$32, "_isNativeReflectConstruct");
1091 /**
1092 * @typedef {import('../modules/component-base')} ComponentBase
1093 */
1094 var CommandInfra = /*#__PURE__*/ function(_ArgsObject) {
1095 /**
1096 * Function constructor().
1097 *
1098 * Create Commands Base.
1099 *
1100 * @param {{}} args
1101 */
1102 function CommandInfra() {
1103 var _this;
1104 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1105 _classCallCheck(this, CommandInfra);
1106 _this = _callSuper$31(this, CommandInfra, [args]);
1107 if (!_this.constructor.registerConfig) throw RangeError("Doing it wrong: Each command type should have `registerConfig`.");
1108 _this.command = _this.constructor.getCommand();
1109 _this.component = _this.constructor.getComponent();
1110 _this.initialize(args);
1111 args = _this.args;
1112 _this.validateArgs(args);
1113 return _this;
1114 }
1115 /**
1116 * Function initialize().
1117 *
1118 * Initialize command, called after construction.
1119 *
1120 * @param {{}} args
1121 */
1122 _inherits$1(CommandInfra, _ArgsObject);
1123 return _createClass(CommandInfra, [
1124 {
1125 key: "currentCommand",
1126 get: function get() {
1127 Deprecation.deprecated("this.currentCommand", "3.7.0", "this.command");
1128 return this.command;
1129 }
1130 },
1131 {
1132 key: "initialize",
1133 value: function initialize() {
1134 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1135 }
1136 },
1137 {
1138 key: "validateArgs",
1139 value: function validateArgs() {
1140 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1141 }
1142 },
1143 {
1144 key: "apply",
1145 value: function apply() {
1146 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1147 elementorModules.ForceMethodImplementation();
1148 }
1149 },
1150 {
1151 key: "run",
1152 value: function run() {
1153 return this.apply(this.args);
1154 }
1155 },
1156 {
1157 key: "onBeforeRun",
1158 value: function onBeforeRun() {
1159 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1160 }
1161 },
1162 {
1163 key: "onAfterRun",
1164 value: function onAfterRun() {
1165 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1166 arguments.length > 1 && arguments[1];
1167 }
1168 },
1169 {
1170 key: "onBeforeApply",
1171 value: function onBeforeApply() {
1172 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1173 }
1174 },
1175 {
1176 key: "onAfterApply",
1177 value: function onAfterApply() {
1178 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1179 arguments.length > 1 && arguments[1];
1180 }
1181 },
1182 {
1183 key: "onCatchApply",
1184 value: function onCatchApply(e) {}
1185 }
1186 ], [
1187 {
1188 key: "getInstanceType",
1189 value: function getInstanceType() {
1190 return "CommandInfra";
1191 }
1192 },
1193 {
1194 key: "getInfo",
1195 value: function getInfo() {
1196 return {};
1197 }
1198 },
1199 {
1200 key: "getCommand",
1201 value: function getCommand() {
1202 return this.registerConfig.command;
1203 }
1204 },
1205 {
1206 key: "getComponent",
1207 value: function getComponent() {
1208 return this.registerConfig.component;
1209 }
1210 },
1211 {
1212 key: "setRegisterConfig",
1213 value: function setRegisterConfig(config) {
1214 this.registerConfig = Object.freeze(config);
1215 }
1216 }
1217 ]);
1218 }(ArgsObject);
1219 /**
1220 * @type {Object}
1221 */
1222 _defineProperty(CommandInfra, "registerConfig", null);
1223
1224 //#endregion
1225 //#region modules/web-cli/assets/js/modules/command-base.js
1226 function _callSuper$30(t, o, e) {
1227 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$31() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1228 }
1229 __name(_callSuper$30, "_callSuper");
1230 function _isNativeReflectConstruct$31() {
1231 try {
1232 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1233 } catch (t) {}
1234 return (_isNativeReflectConstruct$31 = function _isNativeReflectConstruct() {
1235 return !!t;
1236 })();
1237 }
1238 __name(_isNativeReflectConstruct$31, "_isNativeReflectConstruct");
1239 /**
1240 * @name $e.modules.CommandBase
1241 */
1242 var CommandBase = /*#__PURE__*/ function(_CommandInfra) {
1243 function CommandBase() {
1244 _classCallCheck(this, CommandBase);
1245 return _callSuper$30(this, CommandBase, arguments);
1246 }
1247 _inherits$1(CommandBase, _CommandInfra);
1248 return _createClass(CommandBase, [
1249 {
1250 key: "onBeforeRun",
1251 value: function onBeforeRun() {
1252 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1253 $e.hooks.runUIBefore(this.command, args);
1254 }
1255 },
1256 {
1257 key: "onAfterRun",
1258 value: function onAfterRun() {
1259 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1260 var result = arguments.length > 1 ? arguments[1] : void 0;
1261 $e.hooks.runUIAfter(this.command, args, result);
1262 }
1263 },
1264 {
1265 key: "onBeforeApply",
1266 value: function onBeforeApply() {
1267 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1268 $e.hooks.runDataDependency(this.command, args);
1269 }
1270 },
1271 {
1272 key: "onAfterApply",
1273 value: function onAfterApply() {
1274 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1275 var result = arguments.length > 1 ? arguments[1] : void 0;
1276 return $e.hooks.runDataAfter(this.command, args, result);
1277 }
1278 },
1279 {
1280 key: "onCatchApply",
1281 value: function onCatchApply(e) {
1282 this.runCatchHooks(e);
1283 }
1284 },
1285 {
1286 key: "runCatchHooks",
1287 value: function runCatchHooks(e) {
1288 $e.hooks.runDataCatch(this.command, this.args, e);
1289 $e.hooks.runUICatch(this.command, this.args, e);
1290 }
1291 },
1292 {
1293 key: "requireContainer",
1294 value: function requireContainer() {
1295 var _this = this;
1296 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.args;
1297 Deprecation.deprecated("requireContainer()", "3.7.0", "Extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase`");
1298 if (!args.container && !args.containers) throw Error("container or containers are required.");
1299 if (args.container && args.containers) throw Error("container and containers cannot go together please select one of them.");
1300 (args.containers || [args.container]).forEach(function(container) {
1301 _this.requireArgumentInstance("container", elementorModules.editor.Container, { container });
1302 });
1303 }
1304 }
1305 ], [{
1306 key: "getInstanceType",
1307 value: function getInstanceType() {
1308 return "CommandBase";
1309 }
1310 }]);
1311 }(CommandInfra);
1312
1313 //#endregion
1314 //#region modules/web-cli/assets/js/modules/command-callback-base.js
1315 function _callSuper$29(t, o, e) {
1316 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$30() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1317 }
1318 __name(_callSuper$29, "_callSuper");
1319 function _isNativeReflectConstruct$30() {
1320 try {
1321 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1322 } catch (t) {}
1323 return (_isNativeReflectConstruct$30 = function _isNativeReflectConstruct() {
1324 return !!t;
1325 })();
1326 }
1327 __name(_isNativeReflectConstruct$30, "_isNativeReflectConstruct");
1328 /**
1329 * To support pure callbacks in the API(commands.js), to ensure they have registered with the proper context.
1330 */
1331 var CommandCallbackBase = /*#__PURE__*/ function(_CommandBase) {
1332 function CommandCallbackBase() {
1333 _classCallCheck(this, CommandCallbackBase);
1334 return _callSuper$29(this, CommandCallbackBase, arguments);
1335 }
1336 _inherits$1(CommandCallbackBase, _CommandBase);
1337 return _createClass(CommandCallbackBase, [{
1338 key: "apply",
1339 value: function apply() {
1340 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1341 return this.constructor.getCallback()(args);
1342 }
1343 }], [{
1344 key: "getInstanceType",
1345 value: function getInstanceType() {
1346 return "CommandCallbackBase";
1347 }
1348 }, {
1349 key: "getCallback",
1350 value: function getCallback() {
1351 return this.registerConfig.callback;
1352 }
1353 }]);
1354 }(CommandBase);
1355
1356 //#endregion
1357 //#region assets/dev/js/modules/imports/module.js
1358 var require_module = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1359 init_typeof();
1360 var Module = function Module() {
1361 var $ = jQuery;
1362 var instanceParams = arguments;
1363 var self = this;
1364 var events = {};
1365 var settings;
1366 var ensureClosureMethods = function ensureClosureMethods() {
1367 $.each(self, function(methodName) {
1368 var oldMethod = self[methodName];
1369 if ("function" !== typeof oldMethod) return;
1370 self[methodName] = function() {
1371 return oldMethod.apply(self, arguments);
1372 };
1373 });
1374 };
1375 var initSettings = function initSettings() {
1376 settings = self.getDefaultSettings();
1377 var instanceSettings = instanceParams[0];
1378 if (instanceSettings) $.extend(true, settings, instanceSettings);
1379 };
1380 var init = function init() {
1381 self.__construct.apply(self, instanceParams);
1382 ensureClosureMethods();
1383 initSettings();
1384 self.trigger("init");
1385 };
1386 this.getItems = function(items, itemKey) {
1387 if (itemKey) {
1388 var keyStack = itemKey.split(".");
1389 var currentKey = keyStack.splice(0, 1);
1390 if (!keyStack.length) return items[currentKey];
1391 if (!items[currentKey]) return;
1392 return this.getItems(items[currentKey], keyStack.join("."));
1393 }
1394 return items;
1395 };
1396 this.getSettings = function(setting) {
1397 return this.getItems(settings, setting);
1398 };
1399 this.setSettings = function(settingKey, value, settingsContainer) {
1400 if (!settingsContainer) settingsContainer = settings;
1401 if ("object" === _typeof(settingKey)) {
1402 $.extend(settingsContainer, settingKey);
1403 return self;
1404 }
1405 var keyStack = settingKey.split(".");
1406 var currentKey = keyStack.splice(0, 1);
1407 if (!keyStack.length) {
1408 settingsContainer[currentKey] = value;
1409 return self;
1410 }
1411 if (!settingsContainer[currentKey]) settingsContainer[currentKey] = {};
1412 return self.setSettings(keyStack.join("."), value, settingsContainer[currentKey]);
1413 };
1414 this.getErrorMessage = function(type, functionName) {
1415 var message;
1416 switch (type) {
1417 case "forceMethodImplementation":
1418 message = "The method '".concat(functionName, "' must to be implemented in the inheritor child.");
1419 break;
1420 default: message = "An error occurs";
1421 }
1422 return message;
1423 };
1424 this.forceMethodImplementation = function(functionName) {
1425 throw new Error(this.getErrorMessage("forceMethodImplementation", functionName));
1426 };
1427 this.on = function(eventName, callback) {
1428 if ("object" === _typeof(eventName)) {
1429 $.each(eventName, function(singleEventName) {
1430 self.on(singleEventName, this);
1431 });
1432 return self;
1433 }
1434 eventName.split(" ").forEach(function(singleEventName) {
1435 if (!events[singleEventName]) events[singleEventName] = [];
1436 events[singleEventName].push(callback);
1437 });
1438 return self;
1439 };
1440 this.off = function(eventName, callback) {
1441 if (!events[eventName]) return self;
1442 if (!callback) {
1443 delete events[eventName];
1444 return self;
1445 }
1446 var callbackIndex = events[eventName].indexOf(callback);
1447 if (-1 !== callbackIndex) {
1448 delete events[eventName][callbackIndex];
1449 events[eventName] = events[eventName].filter(function(val) {
1450 return val;
1451 });
1452 }
1453 return self;
1454 };
1455 this.trigger = function(eventName) {
1456 var methodName = "on" + eventName[0].toUpperCase() + eventName.slice(1);
1457 var params = Array.prototype.slice.call(arguments, 1);
1458 if (self[methodName]) self[methodName].apply(self, params);
1459 var callbacks = events[eventName];
1460 if (!callbacks) return self;
1461 $.each(callbacks, function(index, callback) {
1462 callback.apply(self, params);
1463 });
1464 return self;
1465 };
1466 init();
1467 };
1468 Module.prototype.__construct = function() {};
1469 Module.prototype.getDefaultSettings = function() {
1470 return {};
1471 };
1472 Module.prototype.getConstructorID = function() {
1473 return this.constructor.name;
1474 };
1475 Module.extend = function(properties) {
1476 var $ = jQuery;
1477 var parent = this;
1478 var child = function child() {
1479 return parent.apply(this, arguments);
1480 };
1481 $.extend(child, parent);
1482 child.prototype = Object.create($.extend({}, parent.prototype, properties));
1483 child.prototype.constructor = child;
1484 child.__super__ = parent.prototype;
1485 return child;
1486 };
1487 module.exports = Module;
1488 }));
1489
1490 //#endregion
1491 //#region node_modules/@babel/runtime/helpers/esm/isNativeFunction.js
1492 var import_module = /* @__PURE__ */ __toESM(require_module());
1493 function _isNativeFunction(t) {
1494 try {
1495 return -1 !== Function.toString.call(t).indexOf("[native code]");
1496 } catch (n) {
1497 return "function" == typeof t;
1498 }
1499 }
1500
1501 //#endregion
1502 //#region node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js
1503 function _isNativeReflectConstruct$29() {
1504 try {
1505 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1506 } catch (t) {}
1507 return (_isNativeReflectConstruct$29 = function _isNativeReflectConstruct() {
1508 return !!t;
1509 })();
1510 }
1511 __name(_isNativeReflectConstruct$29, "_isNativeReflectConstruct");
1512
1513 //#endregion
1514 //#region node_modules/@babel/runtime/helpers/esm/construct.js
1515 function _construct$1(t, e, r) {
1516 if (_isNativeReflectConstruct$29()) return Reflect.construct.apply(null, arguments);
1517 var o = [null];
1518 o.push.apply(o, e);
1519 var p = new (t.bind.apply(t, o))();
1520 return r && _setPrototypeOf(p, r.prototype), p;
1521 }
1522 __name(_construct$1, "_construct");
1523
1524 //#endregion
1525 //#region node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js
1526 function _wrapNativeSuper(t) {
1527 var r = "function" == typeof Map ? /* @__PURE__ */ new Map() : void 0;
1528 return _wrapNativeSuper = function _wrapNativeSuper(t) {
1529 if (null === t || !_isNativeFunction(t)) return t;
1530 if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
1531 if (void 0 !== r) {
1532 if (r.has(t)) return r.get(t);
1533 r.set(t, Wrapper);
1534 }
1535 function Wrapper() {
1536 return _construct$1(t, arguments, _getPrototypeOf(this).constructor);
1537 }
1538 return Wrapper.prototype = Object.create(t.prototype, { constructor: {
1539 value: Wrapper,
1540 enumerable: !1,
1541 writable: !0,
1542 configurable: !0
1543 } }), _setPrototypeOf(Wrapper, t);
1544 }, _wrapNativeSuper(t);
1545 }
1546
1547 //#endregion
1548 //#region modules/web-cli/assets/js/utils/force-method-implementation.js
1549 function _callSuper$28(t, o, e) {
1550 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$28() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1551 }
1552 __name(_callSuper$28, "_callSuper");
1553 function _isNativeReflectConstruct$28() {
1554 try {
1555 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1556 } catch (t) {}
1557 return (_isNativeReflectConstruct$28 = function _isNativeReflectConstruct() {
1558 return !!t;
1559 })();
1560 }
1561 __name(_isNativeReflectConstruct$28, "_isNativeReflectConstruct");
1562 var ForceMethodImplementation = /*#__PURE__*/ function(_Error) {
1563 function ForceMethodImplementation() {
1564 var _this;
1565 var info = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1566 _classCallCheck(this, ForceMethodImplementation);
1567 _this = _callSuper$28(this, ForceMethodImplementation, ["".concat(info.isStatic ? "static " : "").concat(info.fullName, "() should be implemented, please provide '").concat(info.functionName || info.fullName, "' functionality.")]);
1568 Error.captureStackTrace(_this, ForceMethodImplementation);
1569 return _this;
1570 }
1571 _inherits$1(ForceMethodImplementation, _Error);
1572 return _createClass(ForceMethodImplementation);
1573 }(/*#__PURE__*/ _wrapNativeSuper(Error));
1574 var force_method_implementation_default = /* @__PURE__ */ __name((function() {
1575 var caller = Error().stack.split("\n")[2].trim();
1576 var callerName = caller.startsWith("at new") ? "constructor" : caller.split(" ")[1];
1577 var info = {};
1578 info.functionName = callerName;
1579 info.fullName = callerName;
1580 if (info.functionName.includes(".")) {
1581 var parts = info.functionName.split(".");
1582 info.className = parts[0];
1583 info.functionName = parts[1];
1584 } else info.isStatic = true;
1585 throw new ForceMethodImplementation(info);
1586 }), "default");
1587
1588 //#endregion
1589 //#region modules/web-cli/assets/js/modules/component-base.js
1590 init_defineProperty();
1591 function ownKeys$5(e, r) {
1592 var t = Object.keys(e);
1593 if (Object.getOwnPropertySymbols) {
1594 var o = Object.getOwnPropertySymbols(e);
1595 r && (o = o.filter(function(r) {
1596 return Object.getOwnPropertyDescriptor(e, r).enumerable;
1597 })), t.push.apply(t, o);
1598 }
1599 return t;
1600 }
1601 __name(ownKeys$5, "ownKeys");
1602 function _objectSpread$5(e) {
1603 for (var r = 1; r < arguments.length; r++) {
1604 var t = null != arguments[r] ? arguments[r] : {};
1605 r % 2 ? ownKeys$5(Object(t), !0).forEach(function(r) {
1606 _defineProperty(e, r, t[r]);
1607 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function(r) {
1608 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
1609 });
1610 }
1611 return e;
1612 }
1613 __name(_objectSpread$5, "_objectSpread");
1614 function _callSuper$27(t, o, e) {
1615 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$27() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1616 }
1617 __name(_callSuper$27, "_callSuper");
1618 function _isNativeReflectConstruct$27() {
1619 try {
1620 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1621 } catch (t) {}
1622 return (_isNativeReflectConstruct$27 = function _isNativeReflectConstruct() {
1623 return !!t;
1624 })();
1625 }
1626 __name(_isNativeReflectConstruct$27, "_isNativeReflectConstruct");
1627 /**
1628 * @typedef {import('./command-infra')} CommandInfra
1629 * @typedef {import('./hook-base')} HookBase
1630 * @typedef {import('../core/states/ui-state-base')} UiStateBase
1631 */
1632 var ComponentBase = /*#__PURE__*/ function(_Module) {
1633 function ComponentBase() {
1634 _classCallCheck(this, ComponentBase);
1635 return _callSuper$27(this, ComponentBase, arguments);
1636 }
1637 _inherits$1(ComponentBase, _Module);
1638 return _createClass(ComponentBase, [
1639 {
1640 key: "__construct",
1641 value: function __construct() {
1642 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1643 if (args.manager) this.manager = args.manager;
1644 this.commands = this.defaultCommands();
1645 this.commandsInternal = this.defaultCommandsInternal();
1646 this.hooks = this.defaultHooks();
1647 this.routes = this.defaultRoutes();
1648 this.tabs = this.defaultTabs();
1649 this.shortcuts = this.defaultShortcuts();
1650 this.utils = this.defaultUtils();
1651 this.data = this.defaultData();
1652 this.uiStates = this.defaultUiStates();
1653 this.states = this.defaultStates();
1654 this.defaultRoute = "";
1655 this.currentTab = "";
1656 }
1657 },
1658 {
1659 key: "registerAPI",
1660 value: function registerAPI() {
1661 var _this = this;
1662 Object.entries(this.getTabs()).forEach(function(tab) {
1663 return _this.registerTabRoute(tab[0]);
1664 });
1665 Object.entries(this.getRoutes()).forEach(function(_ref) {
1666 var _ref2 = _slicedToArray(_ref, 2);
1667 var route = _ref2[0];
1668 var callback = _ref2[1];
1669 return _this.registerRoute(route, callback);
1670 });
1671 Object.entries(this.getCommands()).forEach(function(_ref3) {
1672 var _ref4 = _slicedToArray(_ref3, 2);
1673 var command = _ref4[0];
1674 var callback = _ref4[1];
1675 return _this.registerCommand(command, callback);
1676 });
1677 Object.entries(this.getCommandsInternal()).forEach(function(_ref5) {
1678 var _ref6 = _slicedToArray(_ref5, 2);
1679 var command = _ref6[0];
1680 var callback = _ref6[1];
1681 return _this.registerCommandInternal(command, callback);
1682 });
1683 Object.values(this.getHooks()).forEach(function(instance) {
1684 return _this.registerHook(instance);
1685 });
1686 Object.entries(this.getData()).forEach(function(_ref7) {
1687 var _ref8 = _slicedToArray(_ref7, 2);
1688 var command = _ref8[0];
1689 var callback = _ref8[1];
1690 return _this.registerData(command, callback);
1691 });
1692 Object.values(this.getUiStates()).forEach(function(instance) {
1693 return _this.registerUiState(instance);
1694 });
1695 Object.entries(this.getStates()).forEach(function(_ref9) {
1696 var _ref0 = _slicedToArray(_ref9, 2);
1697 var id = _ref0[0];
1698 var state = _ref0[1];
1699 return _this.registerState(id, state);
1700 });
1701 }
1702 },
1703 {
1704 key: "getNamespace",
1705 value: function getNamespace() {
1706 force_method_implementation_default();
1707 }
1708 },
1709 {
1710 key: "getRootContainer",
1711 value: function getRootContainer() {
1712 Deprecation.deprecated("getRootContainer()", "3.7.0", "getServiceName()");
1713 return this.getServiceName();
1714 }
1715 },
1716 {
1717 key: "getServiceName",
1718 value: function getServiceName() {
1719 return this.getNamespace().split("/")[0];
1720 }
1721 },
1722 {
1723 key: "store",
1724 get: function get() {
1725 return $e.store.get(this.getNamespace());
1726 }
1727 },
1728 {
1729 key: "defaultTabs",
1730 value: function defaultTabs() {
1731 return {};
1732 }
1733 },
1734 {
1735 key: "defaultRoutes",
1736 value: function defaultRoutes() {
1737 return {};
1738 }
1739 },
1740 {
1741 key: "defaultCommands",
1742 value: function defaultCommands() {
1743 return {};
1744 }
1745 },
1746 {
1747 key: "defaultCommandsInternal",
1748 value: function defaultCommandsInternal() {
1749 return {};
1750 }
1751 },
1752 {
1753 key: "defaultHooks",
1754 value: function defaultHooks() {
1755 return {};
1756 }
1757 },
1758 {
1759 key: "defaultUiStates",
1760 value: function defaultUiStates() {
1761 return {};
1762 }
1763 },
1764 {
1765 key: "defaultStates",
1766 value: function defaultStates() {
1767 return {};
1768 }
1769 },
1770 {
1771 key: "defaultShortcuts",
1772 value: function defaultShortcuts() {
1773 return {};
1774 }
1775 },
1776 {
1777 key: "defaultUtils",
1778 value: function defaultUtils() {
1779 return {};
1780 }
1781 },
1782 {
1783 key: "defaultData",
1784 value: function defaultData() {
1785 return {};
1786 }
1787 },
1788 {
1789 key: "getCommands",
1790 value: function getCommands() {
1791 return this.commands;
1792 }
1793 },
1794 {
1795 key: "getCommandsInternal",
1796 value: function getCommandsInternal() {
1797 return this.commandsInternal;
1798 }
1799 },
1800 {
1801 key: "getHooks",
1802 value: function getHooks() {
1803 return this.hooks;
1804 }
1805 },
1806 {
1807 key: "getUiStates",
1808 value: function getUiStates() {
1809 return this.uiStates;
1810 }
1811 },
1812 {
1813 key: "getStates",
1814 value: function getStates() {
1815 return this.states;
1816 }
1817 },
1818 {
1819 key: "getRoutes",
1820 value: function getRoutes() {
1821 return this.routes;
1822 }
1823 },
1824 {
1825 key: "getTabs",
1826 value: function getTabs() {
1827 return this.tabs;
1828 }
1829 },
1830 {
1831 key: "getShortcuts",
1832 value: function getShortcuts() {
1833 return this.shortcuts;
1834 }
1835 },
1836 {
1837 key: "getData",
1838 value: function getData() {
1839 return this.data;
1840 }
1841 },
1842 {
1843 key: "registerCommand",
1844 value: function registerCommand(command, context) {
1845 var commandsType = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "default";
1846 var commandsManager;
1847 switch (commandsType) {
1848 case "default":
1849 commandsManager = $e.commands;
1850 break;
1851 case "internal":
1852 commandsManager = $e.commandsInternal;
1853 break;
1854 case "data":
1855 commandsManager = $e.data;
1856 break;
1857 default: throw new Error("Invalid commands type: '".concat(command, "'"));
1858 }
1859 var fullCommand = this.getNamespace() + "/" + command;
1860 var instanceType = context.getInstanceType ? context.getInstanceType() : false;
1861 var registerConfig = {
1862 command: fullCommand,
1863 component: this
1864 };
1865 if (!instanceType) {
1866 if ($e.devTools) $e.devTools.log.warn("Attach command-callback-base, on command: '".concat(fullCommand, "', context is unknown type."));
1867 registerConfig.callback = context;
1868 context = /*#__PURE__*/ function(_CommandCallbackBase) {
1869 function context() {
1870 _classCallCheck(this, context);
1871 return _callSuper$27(this, context, arguments);
1872 }
1873 _inherits$1(context, _CommandCallbackBase);
1874 return _createClass(context);
1875 }(CommandCallbackBase);
1876 }
1877 context.setRegisterConfig(registerConfig);
1878 commandsManager.register(this, command, context);
1879 }
1880 },
1881 {
1882 key: "registerHook",
1883 value: function registerHook(instance) {
1884 return instance.register();
1885 }
1886 },
1887 {
1888 key: "registerCommandInternal",
1889 value: function registerCommandInternal(command, context) {
1890 this.registerCommand(command, context, "internal");
1891 }
1892 },
1893 {
1894 key: "registerUiState",
1895 value: function registerUiState(instance) {
1896 $e.uiStates.register(instance);
1897 }
1898 },
1899 {
1900 key: "registerState",
1901 value: function registerState(id, stateConfig) {
1902 id = this.getNamespace() + (id ? "/".concat(id) : "");
1903 var slice = (0, _reduxjs_toolkit.createSlice)(_objectSpread$5(_objectSpread$5({}, stateConfig), {}, { name: id }));
1904 $e.store.register(id, slice);
1905 }
1906 },
1907 {
1908 key: "registerRoute",
1909 value: function registerRoute(route, callback) {
1910 $e.routes.register(this, route, callback);
1911 }
1912 },
1913 {
1914 key: "registerData",
1915 value: function registerData(command, context) {
1916 this.registerCommand(command, context, "data");
1917 }
1918 },
1919 {
1920 key: "unregisterRoute",
1921 value: function unregisterRoute(route) {
1922 $e.routes.unregister(this, route);
1923 }
1924 },
1925 {
1926 key: "registerTabRoute",
1927 value: function registerTabRoute(tab) {
1928 var _this2 = this;
1929 this.registerRoute(tab, function(args) {
1930 return _this2.activateTab(tab, args);
1931 });
1932 }
1933 },
1934 {
1935 key: "dependency",
1936 value: function dependency() {
1937 return true;
1938 }
1939 },
1940 {
1941 key: "open",
1942 value: function open() {
1943 return true;
1944 }
1945 },
1946 {
1947 key: "close",
1948 value: function close() {
1949 if (!this.isOpen) return false;
1950 this.isOpen = false;
1951 this.inactivate();
1952 $e.routes.clearCurrent(this.getNamespace());
1953 $e.routes.clearHistory(this.getServiceName());
1954 return true;
1955 }
1956 },
1957 {
1958 key: "activate",
1959 value: function activate() {
1960 $e.components.activate(this.getNamespace());
1961 }
1962 },
1963 {
1964 key: "inactivate",
1965 value: function inactivate() {
1966 $e.components.inactivate(this.getNamespace());
1967 }
1968 },
1969 {
1970 key: "isActive",
1971 value: function isActive() {
1972 return $e.components.isActive(this.getNamespace());
1973 }
1974 },
1975 {
1976 key: "onRoute",
1977 value: function onRoute(route) {
1978 this.toggleRouteClass(route, true);
1979 this.toggleHistoryClass();
1980 this.activate();
1981 this.trigger("route/open", route);
1982 }
1983 },
1984 {
1985 key: "onCloseRoute",
1986 value: function onCloseRoute(route) {
1987 this.toggleRouteClass(route, false);
1988 this.inactivate();
1989 this.trigger("route/close", route);
1990 }
1991 },
1992 {
1993 key: "setDefaultRoute",
1994 value: function setDefaultRoute(route) {
1995 this.defaultRoute = this.getNamespace() + "/" + route;
1996 }
1997 },
1998 {
1999 key: "getDefaultRoute",
2000 value: function getDefaultRoute() {
2001 return this.defaultRoute;
2002 }
2003 },
2004 {
2005 key: "removeTab",
2006 value: function removeTab(tab) {
2007 delete this.tabs[tab];
2008 this.unregisterRoute(tab);
2009 }
2010 },
2011 {
2012 key: "hasTab",
2013 value: function hasTab(tab) {
2014 return !!this.tabs[tab];
2015 }
2016 },
2017 {
2018 key: "addTab",
2019 value: function addTab(tab, args, position) {
2020 var _this3 = this;
2021 this.tabs[tab] = args;
2022 if ("undefined" !== typeof position) {
2023 var newTabs = {};
2024 var ids = Object.keys(this.tabs);
2025 ids.pop();
2026 ids.splice(position, 0, tab);
2027 ids.forEach(function(id) {
2028 newTabs[id] = _this3.tabs[id];
2029 });
2030 this.tabs = newTabs;
2031 }
2032 this.registerTabRoute(tab);
2033 }
2034 },
2035 {
2036 key: "getTabsWrapperSelector",
2037 value: function getTabsWrapperSelector() {
2038 return "";
2039 }
2040 },
2041 {
2042 key: "getTabRoute",
2043 value: function getTabRoute(tab) {
2044 return this.getNamespace() + "/" + tab;
2045 }
2046 },
2047 {
2048 key: "renderTab",
2049 value: function renderTab(tab) {}
2050 },
2051 {
2052 key: "activateTab",
2053 value: function activateTab(tab, args) {
2054 var _this4 = this;
2055 this.renderTab(tab, args);
2056 jQuery(this.getTabsWrapperSelector() + " .elementor-component-tab").off("click").on("click", function(event) {
2057 $e.route(_this4.getTabRoute(event.currentTarget.dataset.tab), args);
2058 }).removeClass("elementor-active").filter("[data-tab=\"" + tab + "\"]").addClass("elementor-active");
2059 }
2060 },
2061 {
2062 key: "getActiveTabConfig",
2063 value: function getActiveTabConfig() {
2064 return this.tabs[this.currentTab] || {};
2065 }
2066 },
2067 {
2068 key: "getBodyClass",
2069 value: function getBodyClass(route) {
2070 return "e-route-" + route.replace(/\//g, "-");
2071 }
2072 },
2073 {
2074 key: "normalizeCommandName",
2075 value: function normalizeCommandName(commandName) {
2076 return commandName.replace(/[A-Z]/g, function(match, offset) {
2077 return (offset > 0 ? "-" : "") + match.toLowerCase();
2078 });
2079 }
2080 },
2081 {
2082 key: "importCommands",
2083 value: function importCommands(commandsFromImport) {
2084 var _this5 = this;
2085 var commands = {};
2086 Object.entries(commandsFromImport).forEach(function(_ref1) {
2087 var _ref10 = _slicedToArray(_ref1, 2);
2088 var className = _ref10[0];
2089 var Class = _ref10[1];
2090 var command = _this5.normalizeCommandName(className);
2091 commands[command] = Class;
2092 });
2093 return commands;
2094 }
2095 },
2096 {
2097 key: "importHooks",
2098 value: function importHooks(hooksFromImport) {
2099 var hooks = {};
2100 for (var key in hooksFromImport) {
2101 var hook = new hooksFromImport[key]();
2102 hooks[hook.getId()] = hook;
2103 }
2104 return hooks;
2105 }
2106 },
2107 {
2108 key: "importUiStates",
2109 value: function importUiStates(statesFromImport) {
2110 var _this6 = this;
2111 var uiStates = {};
2112 Object.values(statesFromImport).forEach(function(className) {
2113 var uiState = new className(_this6);
2114 uiStates[uiState.getId()] = uiState;
2115 });
2116 return uiStates;
2117 }
2118 },
2119 {
2120 key: "setUiState",
2121 value: function setUiState(state, value) {
2122 $e.uiStates.set("".concat(this.getNamespace(), "/").concat(state), value);
2123 }
2124 },
2125 {
2126 key: "toggleRouteClass",
2127 value: function toggleRouteClass(route, state) {
2128 document.body.classList.toggle(this.getBodyClass(route), state);
2129 }
2130 },
2131 {
2132 key: "toggleHistoryClass",
2133 value: function toggleHistoryClass() {
2134 document.body.classList.toggle("e-routes-has-history", !!$e.routes.getHistory(this.getServiceName()).length);
2135 }
2136 }
2137 ]);
2138 }(import_module.default);
2139
2140 //#endregion
2141 //#region modules/web-cli/assets/js/modules/commands/close.js
2142 function _callSuper$26(t, o, e) {
2143 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$26() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2144 }
2145 __name(_callSuper$26, "_callSuper");
2146 function _isNativeReflectConstruct$26() {
2147 try {
2148 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2149 } catch (t) {}
2150 return (_isNativeReflectConstruct$26 = function _isNativeReflectConstruct() {
2151 return !!t;
2152 })();
2153 }
2154 __name(_isNativeReflectConstruct$26, "_isNativeReflectConstruct");
2155 var Close = /*#__PURE__*/ function(_CommandBase) {
2156 function Close() {
2157 _classCallCheck(this, Close);
2158 return _callSuper$26(this, Close, arguments);
2159 }
2160 _inherits$1(Close, _CommandBase);
2161 return _createClass(Close, [{
2162 key: "apply",
2163 value: function apply() {
2164 this.component.close();
2165 }
2166 }]);
2167 }(CommandBase);
2168
2169 //#endregion
2170 //#region modules/web-cli/assets/js/modules/commands/open.js
2171 function _callSuper$25(t, o, e) {
2172 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$25() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2173 }
2174 __name(_callSuper$25, "_callSuper");
2175 function _isNativeReflectConstruct$25() {
2176 try {
2177 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2178 } catch (t) {}
2179 return (_isNativeReflectConstruct$25 = function _isNativeReflectConstruct() {
2180 return !!t;
2181 })();
2182 }
2183 __name(_isNativeReflectConstruct$25, "_isNativeReflectConstruct");
2184 var Open = /*#__PURE__*/ function(_CommandBase) {
2185 function Open() {
2186 _classCallCheck(this, Open);
2187 return _callSuper$25(this, Open, arguments);
2188 }
2189 _inherits$1(Open, _CommandBase);
2190 return _createClass(Open, [{
2191 key: "apply",
2192 value: function apply() {
2193 $e.route(this.component.getNamespace());
2194 }
2195 }]);
2196 }(CommandBase);
2197
2198 //#endregion
2199 //#region modules/web-cli/assets/js/modules/commands/toggle.js
2200 function _callSuper$24(t, o, e) {
2201 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$24() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2202 }
2203 __name(_callSuper$24, "_callSuper");
2204 function _isNativeReflectConstruct$24() {
2205 try {
2206 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2207 } catch (t) {}
2208 return (_isNativeReflectConstruct$24 = function _isNativeReflectConstruct() {
2209 return !!t;
2210 })();
2211 }
2212 __name(_isNativeReflectConstruct$24, "_isNativeReflectConstruct");
2213 var Toggle = /*#__PURE__*/ function(_CommandBase) {
2214 function Toggle() {
2215 _classCallCheck(this, Toggle);
2216 return _callSuper$24(this, Toggle, arguments);
2217 }
2218 _inherits$1(Toggle, _CommandBase);
2219 return _createClass(Toggle, [{
2220 key: "apply",
2221 value: function apply() {
2222 if (this.component.isOpen) this.component.close();
2223 else $e.route(this.component.getNamespace());
2224 }
2225 }]);
2226 }(CommandBase);
2227
2228 //#endregion
2229 //#region modules/web-cli/assets/js/modules/commands/index.js
2230 var commands_exports$1 = /* @__PURE__ */ __exportAll({
2231 Close: () => Close,
2232 Open: () => Open,
2233 Toggle: () => Toggle
2234 });
2235
2236 //#endregion
2237 //#region modules/web-cli/assets/js/modules/component-modal-base.js
2238 function _callSuper$23(t, o, e) {
2239 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$23() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2240 }
2241 __name(_callSuper$23, "_callSuper");
2242 function _isNativeReflectConstruct$23() {
2243 try {
2244 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2245 } catch (t) {}
2246 return (_isNativeReflectConstruct$23 = function _isNativeReflectConstruct() {
2247 return !!t;
2248 })();
2249 }
2250 __name(_isNativeReflectConstruct$23, "_isNativeReflectConstruct");
2251 function _superPropGet$6(t, o, e, r) {
2252 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
2253 return 2 & r && "function" == typeof p ? function(t) {
2254 return p.apply(e, t);
2255 } : p;
2256 }
2257 __name(_superPropGet$6, "_superPropGet");
2258 var ComponentModalBase = /*#__PURE__*/ function(_ComponentBase) {
2259 function ComponentModalBase() {
2260 _classCallCheck(this, ComponentModalBase);
2261 return _callSuper$23(this, ComponentModalBase, arguments);
2262 }
2263 _inherits$1(ComponentModalBase, _ComponentBase);
2264 return _createClass(ComponentModalBase, [
2265 {
2266 key: "registerAPI",
2267 value: function registerAPI() {
2268 var _this = this;
2269 _superPropGet$6(ComponentModalBase, "registerAPI", this, 3)([]);
2270 $e.shortcuts.register("esc", {
2271 scopes: [this.getNamespace()],
2272 callback: function callback() {
2273 return _this.close();
2274 }
2275 });
2276 }
2277 },
2278 {
2279 key: "defaultCommands",
2280 value: function defaultCommands() {
2281 return this.importCommands(commands_exports$1);
2282 }
2283 },
2284 {
2285 key: "defaultRoutes",
2286 value: function defaultRoutes() {
2287 return { "": function _() {} };
2288 }
2289 },
2290 {
2291 key: "open",
2292 value: function open() {
2293 var _this2 = this;
2294 if (!this.layout) {
2295 var layout = this.getModalLayout();
2296 this.layout = new layout({ component: this });
2297 this.layout.getModal().on("hide", function() {
2298 return _this2.close();
2299 });
2300 }
2301 this.layout.showModal();
2302 return true;
2303 }
2304 },
2305 {
2306 key: "close",
2307 value: function close() {
2308 if (!_superPropGet$6(ComponentModalBase, "close", this, 3)([])) return false;
2309 elementor.hooks.applyFilters("component/modal/close", this.layout.getModal().hide.bind(this.layout.getModal()), this)();
2310 return true;
2311 }
2312 },
2313 {
2314 key: "getModalLayout",
2315 value: function getModalLayout() {
2316 force_method_implementation_default();
2317 }
2318 }
2319 ]);
2320 }(ComponentBase);
2321
2322 //#endregion
2323 //#region assets/dev/js/editor/utils/editor-one-events.js
2324 init_defineProperty();
2325 function ownKeys$4(e, r) {
2326 var t = Object.keys(e);
2327 if (Object.getOwnPropertySymbols) {
2328 var o = Object.getOwnPropertySymbols(e);
2329 r && (o = o.filter(function(r) {
2330 return Object.getOwnPropertyDescriptor(e, r).enumerable;
2331 })), t.push.apply(t, o);
2332 }
2333 return t;
2334 }
2335 __name(ownKeys$4, "ownKeys");
2336 function _objectSpread$4(e) {
2337 for (var r = 1; r < arguments.length; r++) {
2338 var t = null != arguments[r] ? arguments[r] : {};
2339 r % 2 ? ownKeys$4(Object(t), !0).forEach(function(r) {
2340 _defineProperty(e, r, t[r]);
2341 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function(r) {
2342 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
2343 });
2344 }
2345 return e;
2346 }
2347 __name(_objectSpread$4, "_objectSpread");
2348 var EditorOneEventManager = /*#__PURE__*/ function() {
2349 function EditorOneEventManager() {
2350 _classCallCheck(this, EditorOneEventManager);
2351 }
2352 return _createClass(EditorOneEventManager, null, [
2353 {
2354 key: "getEventsManager",
2355 value: function getEventsManager() {
2356 var _elementorCommon;
2357 return (_elementorCommon = elementorCommon) === null || _elementorCommon === void 0 ? void 0 : _elementorCommon.eventsManager;
2358 }
2359 },
2360 {
2361 key: "getConfig",
2362 value: function getConfig() {
2363 var _this$getEventsManage;
2364 return (_this$getEventsManage = this.getEventsManager()) === null || _this$getEventsManage === void 0 ? void 0 : _this$getEventsManage.config;
2365 }
2366 },
2367 {
2368 key: "canSendEvents",
2369 value: function canSendEvents() {
2370 var _elementorCommon2;
2371 return ((_elementorCommon2 = elementorCommon) === null || _elementorCommon2 === void 0 || (_elementorCommon2 = _elementorCommon2.config) === null || _elementorCommon2 === void 0 || (_elementorCommon2 = _elementorCommon2.editor_events) === null || _elementorCommon2 === void 0 ? void 0 : _elementorCommon2.can_send_events) || false;
2372 }
2373 },
2374 {
2375 key: "isEventsManagerAvailable",
2376 value: function isEventsManagerAvailable() {
2377 var eventsManager = this.getEventsManager();
2378 return eventsManager && "function" === typeof eventsManager.dispatchEvent;
2379 }
2380 },
2381 {
2382 key: "dispatchEvent",
2383 value: function dispatchEvent(eventName, payload) {
2384 try {
2385 if (!this.isEventsManagerAvailable() || !this.canSendEvents()) return false;
2386 this.getEventsManager().dispatchEvent(eventName, payload);
2387 return true;
2388 } catch (error) {
2389 return false;
2390 }
2391 }
2392 },
2393 {
2394 key: "toLowerSnake",
2395 value: function toLowerSnake(value) {
2396 if (!value || "string" !== typeof value) return value;
2397 return value.replace(/\s+/g, "_").toLowerCase();
2398 }
2399 },
2400 {
2401 key: "decodeHtmlEntities",
2402 value: function decodeHtmlEntities(text) {
2403 if (!text || "string" !== typeof text) return text;
2404 return new DOMParser().parseFromString(text, "text/html").body.textContent || text;
2405 }
2406 },
2407 {
2408 key: "isInEditorContext",
2409 value: function isInEditorContext() {
2410 var _window$elementor;
2411 return "undefined" !== typeof window.elementor && !!((_window$elementor = window.elementor) !== null && _window$elementor !== void 0 && _window$elementor.documents);
2412 }
2413 },
2414 {
2415 key: "getFinderContext",
2416 value: function getFinderContext() {
2417 var _config$appTypes;
2418 var _config$appTypes2;
2419 var _config$locations;
2420 var _config$locations2;
2421 var config = this.getConfig();
2422 var isEditor = this.isInEditorContext();
2423 return {
2424 windowName: isEditor ? config === null || config === void 0 || (_config$appTypes = config.appTypes) === null || _config$appTypes === void 0 ? void 0 : _config$appTypes.editor : config === null || config === void 0 || (_config$appTypes2 = config.appTypes) === null || _config$appTypes2 === void 0 ? void 0 : _config$appTypes2.wpAdmin,
2425 targetLocation: this.toLowerSnake(isEditor ? config === null || config === void 0 || (_config$locations = config.locations) === null || _config$locations === void 0 ? void 0 : _config$locations.topBar : config === null || config === void 0 || (_config$locations2 = config.locations) === null || _config$locations2 === void 0 ? void 0 : _config$locations2.sidebar)
2426 };
2427 }
2428 },
2429 {
2430 key: "createBasePayload",
2431 value: function createBasePayload() {
2432 var _config$appTypes$edit;
2433 var _config$appTypes3;
2434 var overrides = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2435 var config = this.getConfig();
2436 return _objectSpread$4({ window_name: (_config$appTypes$edit = config === null || config === void 0 || (_config$appTypes3 = config.appTypes) === null || _config$appTypes3 === void 0 ? void 0 : _config$appTypes3.editor) !== null && _config$appTypes$edit !== void 0 ? _config$appTypes$edit : "editor" }, overrides);
2437 }
2438 },
2439 {
2440 key: "sendTopBarPublishDropdown",
2441 value: function sendTopBarPublishDropdown(targetName) {
2442 var _config$names;
2443 var _config$triggers;
2444 var _config$targetTypes;
2445 var _config$interactionRe;
2446 var _config$locations3;
2447 var _config$secondaryLoca;
2448 var _config$targetTypes2;
2449 var config = this.getConfig();
2450 return this.dispatchEvent(config === null || config === void 0 || (_config$names = config.names) === null || _config$names === void 0 || (_config$names = _config$names.editorOne) === null || _config$names === void 0 ? void 0 : _config$names.topBarPublishDropdown, this.createBasePayload({
2451 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers = config.triggers) === null || _config$triggers === void 0 ? void 0 : _config$triggers.click),
2452 target_type: config === null || config === void 0 || (_config$targetTypes = config.targetTypes) === null || _config$targetTypes === void 0 ? void 0 : _config$targetTypes.dropdownItem,
2453 target_name: targetName,
2454 interaction_result: config === null || config === void 0 || (_config$interactionRe = config.interactionResults) === null || _config$interactionRe === void 0 ? void 0 : _config$interactionRe.actionSelected,
2455 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations3 = config.locations) === null || _config$locations3 === void 0 ? void 0 : _config$locations3.topBar),
2456 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca = config.secondaryLocations) === null || _config$secondaryLoca === void 0 ? void 0 : _config$secondaryLoca.publishDropdown),
2457 location_l2: config === null || config === void 0 || (_config$targetTypes2 = config.targetTypes) === null || _config$targetTypes2 === void 0 ? void 0 : _config$targetTypes2.dropdownItem,
2458 interaction_description: "User selected an action from the publish dropdown"
2459 }));
2460 }
2461 },
2462 {
2463 key: "sendTopBarPageList",
2464 value: function sendTopBarPageList(targetName) {
2465 var _config$names2;
2466 var _config$triggers2;
2467 var _config$targetTypes3;
2468 var _config$interactionRe2;
2469 var _config$interactionRe3;
2470 var _config$locations4;
2471 var _config$secondaryLoca2;
2472 var _config$targetTypes4;
2473 var isCreate = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2474 var config = this.getConfig();
2475 return this.dispatchEvent(config === null || config === void 0 || (_config$names2 = config.names) === null || _config$names2 === void 0 || (_config$names2 = _config$names2.editorOne) === null || _config$names2 === void 0 ? void 0 : _config$names2.topBarPageList, this.createBasePayload({
2476 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers2 = config.triggers) === null || _config$triggers2 === void 0 ? void 0 : _config$triggers2.click),
2477 target_type: config === null || config === void 0 || (_config$targetTypes3 = config.targetTypes) === null || _config$targetTypes3 === void 0 ? void 0 : _config$targetTypes3.dropdownItem,
2478 target_name: targetName,
2479 interaction_result: isCreate ? config === null || config === void 0 || (_config$interactionRe2 = config.interactionResults) === null || _config$interactionRe2 === void 0 ? void 0 : _config$interactionRe2.create : config === null || config === void 0 || (_config$interactionRe3 = config.interactionResults) === null || _config$interactionRe3 === void 0 ? void 0 : _config$interactionRe3.navigate,
2480 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations4 = config.locations) === null || _config$locations4 === void 0 ? void 0 : _config$locations4.topBar),
2481 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca2 = config.secondaryLocations) === null || _config$secondaryLoca2 === void 0 ? void 0 : _config$secondaryLoca2.pageListDropdown),
2482 location_l2: config === null || config === void 0 || (_config$targetTypes4 = config.targetTypes) === null || _config$targetTypes4 === void 0 ? void 0 : _config$targetTypes4.dropdownItem,
2483 interaction_description: "User selected an action from the page list dropdown"
2484 }));
2485 }
2486 },
2487 {
2488 key: "sendSiteSettingsSession",
2489 value: function sendSiteSettingsSession(_ref) {
2490 var _config$names3;
2491 var _config$triggers3;
2492 var _config$interactionRe4;
2493 var _config$locations5;
2494 var _config$secondaryLoca3;
2495 var targetType = _ref.targetType;
2496 var _ref$visitedItems = _ref.visitedItems;
2497 var visitedItems = _ref$visitedItems === void 0 ? [] : _ref$visitedItems;
2498 var _ref$savedItems = _ref.savedItems;
2499 var savedItems = _ref$savedItems === void 0 ? [] : _ref$savedItems;
2500 var state = _ref.state;
2501 var config = this.getConfig();
2502 return this.dispatchEvent(config === null || config === void 0 || (_config$names3 = config.names) === null || _config$names3 === void 0 || (_config$names3 = _config$names3.editorOne) === null || _config$names3 === void 0 ? void 0 : _config$names3.siteSettingsSession, this.createBasePayload({
2503 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers3 = config.triggers) === null || _config$triggers3 === void 0 ? void 0 : _config$triggers3.click),
2504 target_type: targetType,
2505 target_name: "site_settings",
2506 interaction_result: config === null || config === void 0 || (_config$interactionRe4 = config.interactionResults) === null || _config$interactionRe4 === void 0 ? void 0 : _config$interactionRe4.sessionEnd,
2507 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations5 = config.locations) === null || _config$locations5 === void 0 ? void 0 : _config$locations5.leftPanel),
2508 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca3 = config.secondaryLocations) === null || _config$secondaryLoca3 === void 0 ? void 0 : _config$secondaryLoca3.siteSettings),
2509 interaction_description: "Records areas visited as part of the site setting session",
2510 metadata: {
2511 visited_items: visitedItems,
2512 saved_items: savedItems
2513 },
2514 state
2515 }));
2516 }
2517 },
2518 {
2519 key: "sendELibraryNav",
2520 value: function sendELibraryNav(tabName) {
2521 var _config$names4;
2522 var _config$triggers4;
2523 var _config$targetTypes5;
2524 var _config$interactionRe5;
2525 var _config$locations6;
2526 var _config$secondaryLoca4;
2527 var config = this.getConfig();
2528 return this.dispatchEvent(config === null || config === void 0 || (_config$names4 = config.names) === null || _config$names4 === void 0 || (_config$names4 = _config$names4.editorOne) === null || _config$names4 === void 0 ? void 0 : _config$names4.eLibraryNav, this.createBasePayload({
2529 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers4 = config.triggers) === null || _config$triggers4 === void 0 ? void 0 : _config$triggers4.tabSelect),
2530 target_type: config === null || config === void 0 || (_config$targetTypes5 = config.targetTypes) === null || _config$targetTypes5 === void 0 ? void 0 : _config$targetTypes5.tab,
2531 target_name: this.toLowerSnake(tabName),
2532 interaction_result: config === null || config === void 0 || (_config$interactionRe5 = config.interactionResults) === null || _config$interactionRe5 === void 0 ? void 0 : _config$interactionRe5.tabChanged,
2533 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations6 = config.locations) === null || _config$locations6 === void 0 ? void 0 : _config$locations6.elementorLibrary),
2534 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca4 = config.secondaryLocations) === null || _config$secondaryLoca4 === void 0 ? void 0 : _config$secondaryLoca4.libraryTabs),
2535 interaction_description: "User navigates within elementor library"
2536 }));
2537 }
2538 },
2539 {
2540 key: "sendELibraryInsert",
2541 value: function sendELibraryInsert(_ref2) {
2542 var _config$triggers5;
2543 var _config$targetTypes6;
2544 var _config$interactionRe6;
2545 var _config$locations7;
2546 var _config$secondaryLoca5;
2547 var _config$names5;
2548 var assetId = _ref2.assetId;
2549 var assetName = _ref2.assetName;
2550 var libraryType = _ref2.libraryType;
2551 var _ref2$proRequired = _ref2.proRequired;
2552 var proRequired = _ref2$proRequired === void 0 ? false : _ref2$proRequired;
2553 var config = this.getConfig();
2554 var payload = this.createBasePayload({
2555 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers5 = config.triggers) === null || _config$triggers5 === void 0 ? void 0 : _config$triggers5.insert),
2556 target_type: config === null || config === void 0 || (_config$targetTypes6 = config.targetTypes) === null || _config$targetTypes6 === void 0 ? void 0 : _config$targetTypes6.button,
2557 target_name: String(assetId),
2558 interaction_result: config === null || config === void 0 || (_config$interactionRe6 = config.interactionResults) === null || _config$interactionRe6 === void 0 ? void 0 : _config$interactionRe6.assetInserted,
2559 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations7 = config.locations) === null || _config$locations7 === void 0 ? void 0 : _config$locations7.elementorLibrary),
2560 location_l1: this.toLowerSnake(libraryType),
2561 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca5 = config.secondaryLocations) === null || _config$secondaryLoca5 === void 0 ? void 0 : _config$secondaryLoca5.assetCard),
2562 interaction_description: "User inserts block/pages from elementor library",
2563 metadata: {
2564 template_id: String(assetId),
2565 template_name: this.decodeHtmlEntities(assetName) || ""
2566 }
2567 });
2568 if (proRequired) payload.state = "pro_plan_required";
2569 return this.dispatchEvent(config === null || config === void 0 || (_config$names5 = config.names) === null || _config$names5 === void 0 || (_config$names5 = _config$names5.editorOne) === null || _config$names5 === void 0 ? void 0 : _config$names5.eLibraryInsert, payload);
2570 }
2571 },
2572 {
2573 key: "sendELibraryFavorite",
2574 value: function sendELibraryFavorite(_ref3) {
2575 var _config$triggers6;
2576 var _config$targetTypes7;
2577 var _config$interactionRe7;
2578 var _config$locations8;
2579 var _config$secondaryLoca6;
2580 var _config$names6;
2581 var assetId = _ref3.assetId;
2582 var assetName = _ref3.assetName;
2583 var libraryType = _ref3.libraryType;
2584 var isFavorite = _ref3.isFavorite;
2585 var _ref3$proRequired = _ref3.proRequired;
2586 var proRequired = _ref3$proRequired === void 0 ? false : _ref3$proRequired;
2587 var config = this.getConfig();
2588 var payload = this.createBasePayload({
2589 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers6 = config.triggers) === null || _config$triggers6 === void 0 ? void 0 : _config$triggers6.click),
2590 target_type: config === null || config === void 0 || (_config$targetTypes7 = config.targetTypes) === null || _config$targetTypes7 === void 0 ? void 0 : _config$targetTypes7.toggle,
2591 target_name: String(assetId),
2592 interaction_result: config === null || config === void 0 || (_config$interactionRe7 = config.interactionResults) === null || _config$interactionRe7 === void 0 ? void 0 : _config$interactionRe7.assetFavorite,
2593 target_value: Boolean(isFavorite),
2594 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations8 = config.locations) === null || _config$locations8 === void 0 ? void 0 : _config$locations8.elementorLibrary),
2595 location_l1: this.toLowerSnake(libraryType),
2596 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca6 = config.secondaryLocations) === null || _config$secondaryLoca6 === void 0 ? void 0 : _config$secondaryLoca6.assetCard),
2597 interaction_description: "User favorite block/pages from elementor library",
2598 metadata: {
2599 template_id: String(assetId),
2600 template_name: this.decodeHtmlEntities(assetName) || ""
2601 }
2602 });
2603 if (proRequired) payload.state = "pro_plan_required";
2604 return this.dispatchEvent(config === null || config === void 0 || (_config$names6 = config.names) === null || _config$names6 === void 0 || (_config$names6 = _config$names6.editorOne) === null || _config$names6 === void 0 ? void 0 : _config$names6.eLibraryFavorite, payload);
2605 }
2606 },
2607 {
2608 key: "sendELibraryGenerateAi",
2609 value: function sendELibraryGenerateAi(_ref4) {
2610 var _config$names7;
2611 var _config$triggers7;
2612 var _config$targetTypes8;
2613 var _config$interactionRe8;
2614 var _config$locations9;
2615 var _config$secondaryLoca7;
2616 var assetId = _ref4.assetId;
2617 var assetName = _ref4.assetName;
2618 var libraryType = _ref4.libraryType;
2619 var config = this.getConfig();
2620 return this.dispatchEvent(config === null || config === void 0 || (_config$names7 = config.names) === null || _config$names7 === void 0 || (_config$names7 = _config$names7.editorOne) === null || _config$names7 === void 0 ? void 0 : _config$names7.eLibraryGenerateAi, this.createBasePayload({
2621 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers7 = config.triggers) === null || _config$triggers7 === void 0 ? void 0 : _config$triggers7.click),
2622 target_type: config === null || config === void 0 || (_config$targetTypes8 = config.targetTypes) === null || _config$targetTypes8 === void 0 ? void 0 : _config$targetTypes8.button,
2623 target_name: String(assetId),
2624 interaction_result: config === null || config === void 0 || (_config$interactionRe8 = config.interactionResults) === null || _config$interactionRe8 === void 0 ? void 0 : _config$interactionRe8.aiGenerate,
2625 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations9 = config.locations) === null || _config$locations9 === void 0 ? void 0 : _config$locations9.elementorLibrary),
2626 location_l1: this.toLowerSnake(libraryType),
2627 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca7 = config.secondaryLocations) === null || _config$secondaryLoca7 === void 0 ? void 0 : _config$secondaryLoca7.assetCard),
2628 interaction_description: "User generated block/page based on a library asset",
2629 metadata: {
2630 template_id: String(assetId),
2631 template_name: this.decodeHtmlEntities(assetName) || ""
2632 }
2633 }));
2634 }
2635 },
2636 {
2637 key: "sendFinderSearchInput",
2638 value: function sendFinderSearchInput(_ref5) {
2639 var _config$triggers8;
2640 var _config$targetTypes9;
2641 var _config$interactionRe9;
2642 var _config$interactionRe0;
2643 var _config$secondaryLoca8;
2644 var _config$names8;
2645 var resultsCount = _ref5.resultsCount;
2646 var _ref5$searchTerm = _ref5.searchTerm;
2647 var searchTerm = _ref5$searchTerm === void 0 ? null : _ref5$searchTerm;
2648 var config = this.getConfig();
2649 var hasResults = resultsCount > 0;
2650 var finderContext = this.getFinderContext();
2651 var payload = this.createBasePayload({
2652 window_name: finderContext.windowName,
2653 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers8 = config.triggers) === null || _config$triggers8 === void 0 ? void 0 : _config$triggers8.typing),
2654 target_type: config === null || config === void 0 || (_config$targetTypes9 = config.targetTypes) === null || _config$targetTypes9 === void 0 ? void 0 : _config$targetTypes9.searchInput,
2655 target_name: "finder",
2656 interaction_result: hasResults ? config === null || config === void 0 || (_config$interactionRe9 = config.interactionResults) === null || _config$interactionRe9 === void 0 ? void 0 : _config$interactionRe9.resultsUpdated : config === null || config === void 0 || (_config$interactionRe0 = config.interactionResults) === null || _config$interactionRe0 === void 0 ? void 0 : _config$interactionRe0.noResults,
2657 target_location: finderContext.targetLocation,
2658 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca8 = config.secondaryLocations) === null || _config$secondaryLoca8 === void 0 ? void 0 : _config$secondaryLoca8.finder),
2659 interaction_description: "Finder search input, follows debounce behavior",
2660 metadata: { results_count: resultsCount }
2661 });
2662 if (!hasResults && searchTerm) payload.metadata.search_term = searchTerm;
2663 return this.dispatchEvent(config === null || config === void 0 || (_config$names8 = config.names) === null || _config$names8 === void 0 || (_config$names8 = _config$names8.editorOne) === null || _config$names8 === void 0 ? void 0 : _config$names8.finderSearchInput, payload);
2664 }
2665 },
2666 {
2667 key: "sendFinderResultSelect",
2668 value: function sendFinderResultSelect(choice) {
2669 var _config$names9;
2670 var _config$triggers9;
2671 var _config$targetTypes0;
2672 var _config$interactionRe1;
2673 var _config$secondaryLoca9;
2674 var _config$secondaryLoca0;
2675 var config = this.getConfig();
2676 var finderContext = this.getFinderContext();
2677 return this.dispatchEvent(config === null || config === void 0 || (_config$names9 = config.names) === null || _config$names9 === void 0 || (_config$names9 = _config$names9.editorOne) === null || _config$names9 === void 0 ? void 0 : _config$names9.finderResultSelect, this.createBasePayload({
2678 window_name: finderContext.windowName,
2679 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers9 = config.triggers) === null || _config$triggers9 === void 0 ? void 0 : _config$triggers9.click),
2680 target_type: config === null || config === void 0 || (_config$targetTypes0 = config.targetTypes) === null || _config$targetTypes0 === void 0 ? void 0 : _config$targetTypes0.searchResult,
2681 target_name: choice,
2682 interaction_result: config === null || config === void 0 || (_config$interactionRe1 = config.interactionResults) === null || _config$interactionRe1 === void 0 ? void 0 : _config$interactionRe1.selected,
2683 target_location: finderContext.targetLocation,
2684 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca9 = config.secondaryLocations) === null || _config$secondaryLoca9 === void 0 ? void 0 : _config$secondaryLoca9.finder),
2685 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca0 = config.secondaryLocations) === null || _config$secondaryLoca0 === void 0 ? void 0 : _config$secondaryLoca0.finderResults),
2686 interaction_description: "Finder search results was selected"
2687 }));
2688 }
2689 },
2690 {
2691 key: "sendCanvasEmptyBoxAction",
2692 value: function sendCanvasEmptyBoxAction(_ref6) {
2693 var _config$triggers0;
2694 var _config$targetTypes1;
2695 var _config$interactionRe10;
2696 var _config$locations0;
2697 var _config$secondaryLoca1;
2698 var _config$names0;
2699 var targetName = _ref6.targetName;
2700 var _ref6$metadata = _ref6.metadata;
2701 var metadata = _ref6$metadata === void 0 ? {} : _ref6$metadata;
2702 var _ref6$containerCreate = _ref6.containerCreated;
2703 var containerCreated = _ref6$containerCreate === void 0 ? null : _ref6$containerCreate;
2704 var config = this.getConfig();
2705 var payload = this.createBasePayload({
2706 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers0 = config.triggers) === null || _config$triggers0 === void 0 ? void 0 : _config$triggers0.click),
2707 target_type: config === null || config === void 0 || (_config$targetTypes1 = config.targetTypes) === null || _config$targetTypes1 === void 0 ? void 0 : _config$targetTypes1.buttons,
2708 target_name: targetName,
2709 interaction_result: config === null || config === void 0 || (_config$interactionRe10 = config.interactionResults) === null || _config$interactionRe10 === void 0 ? void 0 : _config$interactionRe10.selected,
2710 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations0 = config.locations) === null || _config$locations0 === void 0 ? void 0 : _config$locations0.canvas),
2711 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca1 = config.secondaryLocations) === null || _config$secondaryLoca1 === void 0 ? void 0 : _config$secondaryLoca1.emptyBox),
2712 interaction_description: "Empty box on canvas actions"
2713 });
2714 if (Object.keys(metadata).length > 0) payload.metadata = metadata;
2715 if (containerCreated !== null) payload.state = containerCreated;
2716 return this.dispatchEvent(config === null || config === void 0 || (_config$names0 = config.names) === null || _config$names0 === void 0 || (_config$names0 = _config$names0.editorOne) === null || _config$names0 === void 0 ? void 0 : _config$names0.canvasEmptyBoxAction, payload);
2717 }
2718 },
2719 {
2720 key: "sendWidgetPanelSearch",
2721 value: function sendWidgetPanelSearch(_ref7) {
2722 var _config$triggers1;
2723 var _config$targetTypes10;
2724 var _config$interactionRe11;
2725 var _config$interactionRe12;
2726 var _config$locations1;
2727 var _config$locations10;
2728 var _config$secondaryLoca10;
2729 var _config$names1;
2730 var resultsCount = _ref7.resultsCount;
2731 var _ref7$userInput = _ref7.userInput;
2732 var userInput = _ref7$userInput === void 0 ? null : _ref7$userInput;
2733 var config = this.getConfig();
2734 var hasResults = resultsCount > 0;
2735 var payload = this.createBasePayload({
2736 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers1 = config.triggers) === null || _config$triggers1 === void 0 ? void 0 : _config$triggers1.typing),
2737 target_type: config === null || config === void 0 || (_config$targetTypes10 = config.targetTypes) === null || _config$targetTypes10 === void 0 ? void 0 : _config$targetTypes10.searchWidget,
2738 target_name: "search_widget",
2739 interaction_result: hasResults ? config === null || config === void 0 || (_config$interactionRe11 = config.interactionResults) === null || _config$interactionRe11 === void 0 ? void 0 : _config$interactionRe11.resultsUpdated : config === null || config === void 0 || (_config$interactionRe12 = config.interactionResults) === null || _config$interactionRe12 === void 0 ? void 0 : _config$interactionRe12.noResults,
2740 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations1 = config.locations) === null || _config$locations1 === void 0 ? void 0 : _config$locations1.leftPanel),
2741 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$locations10 = config.locations) === null || _config$locations10 === void 0 ? void 0 : _config$locations10.widgetPanel),
2742 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca10 = config.secondaryLocations) === null || _config$secondaryLoca10 === void 0 ? void 0 : _config$secondaryLoca10.searchBar),
2743 interaction_description: "Widget search input, follows debounce behavior"
2744 });
2745 if (!hasResults && userInput) payload.metadata = { user_input: userInput };
2746 return this.dispatchEvent(config === null || config === void 0 || (_config$names1 = config.names) === null || _config$names1 === void 0 || (_config$names1 = _config$names1.editorOne) === null || _config$names1 === void 0 ? void 0 : _config$names1.widgetPanelSearch, payload);
2747 }
2748 },
2749 {
2750 key: "createWpDashPayload",
2751 value: function createWpDashPayload() {
2752 var _config$appTypes$wpDa;
2753 var _config$appTypes4;
2754 var _config$locations11;
2755 var overrides = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2756 var config = this.getConfig();
2757 return this.createBasePayload(_objectSpread$4({
2758 window_name: (_config$appTypes$wpDa = config === null || config === void 0 || (_config$appTypes4 = config.appTypes) === null || _config$appTypes4 === void 0 ? void 0 : _config$appTypes4.wpDash) !== null && _config$appTypes$wpDa !== void 0 ? _config$appTypes$wpDa : "wpdash",
2759 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations11 = config.locations) === null || _config$locations11 === void 0 ? void 0 : _config$locations11.wpDashAdmin),
2760 location_l2: ""
2761 }, overrides));
2762 }
2763 },
2764 {
2765 key: "sendWpDashElementorMenuClick",
2766 value: function sendWpDashElementorMenuClick() {
2767 var _config$names10;
2768 var _config$triggers10;
2769 var _config$targetTypes11;
2770 var _config$interactionRe13;
2771 var _config$secondaryLoca11;
2772 var config = this.getConfig();
2773 return this.dispatchEvent(config === null || config === void 0 || (_config$names10 = config.names) === null || _config$names10 === void 0 || (_config$names10 = _config$names10.editorOne) === null || _config$names10 === void 0 ? void 0 : _config$names10.wpDashElementorMenuClick, this.createWpDashPayload({
2774 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers10 = config.triggers) === null || _config$triggers10 === void 0 ? void 0 : _config$triggers10.click),
2775 target_type: config === null || config === void 0 || (_config$targetTypes11 = config.targetTypes) === null || _config$targetTypes11 === void 0 ? void 0 : _config$targetTypes11.wpDashAdminMenuItem,
2776 target_name: "elementor_menu_item",
2777 interaction_result: config === null || config === void 0 || (_config$interactionRe13 = config.interactionResults) === null || _config$interactionRe13 === void 0 ? void 0 : _config$interactionRe13.elementorSideMenuOpened,
2778 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca11 = config.secondaryLocations) === null || _config$secondaryLoca11 === void 0 ? void 0 : _config$secondaryLoca11.wpDashElementorCoreMenu),
2779 interaction_description: "core_user_clicked_elementor_menu_item"
2780 }));
2781 }
2782 },
2783 {
2784 key: "sendWpDashEditorSubMenuHover",
2785 value: function sendWpDashEditorSubMenuHover() {
2786 var _config$names11;
2787 var _config$triggers11;
2788 var _config$targetTypes12;
2789 var _config$interactionRe14;
2790 var _config$secondaryLoca12;
2791 var config = this.getConfig();
2792 return this.dispatchEvent(config === null || config === void 0 || (_config$names11 = config.names) === null || _config$names11 === void 0 || (_config$names11 = _config$names11.editorOne) === null || _config$names11 === void 0 ? void 0 : _config$names11.wpDashEditorSubMenuHover, this.createWpDashPayload({
2793 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers11 = config.triggers) === null || _config$triggers11 === void 0 ? void 0 : _config$triggers11.hover),
2794 target_type: config === null || config === void 0 || (_config$targetTypes12 = config.targetTypes) === null || _config$targetTypes12 === void 0 ? void 0 : _config$targetTypes12.wpDashEditorMenu,
2795 target_name: "wpdash_editor_sub_menu",
2796 interaction_result: config === null || config === void 0 || (_config$interactionRe14 = config.interactionResults) === null || _config$interactionRe14 === void 0 ? void 0 : _config$interactionRe14.editorSubMenuOpened,
2797 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca12 = config.secondaryLocations) === null || _config$secondaryLoca12 === void 0 ? void 0 : _config$secondaryLoca12.wpDashElementorCoreSubMenu),
2798 interaction_description: "core_user_hovered_sub_menu"
2799 }));
2800 }
2801 },
2802 {
2803 key: "sendWpDashThemeBuilderClick",
2804 value: function sendWpDashThemeBuilderClick() {
2805 var _config$names12;
2806 var _config$triggers12;
2807 var _config$targetTypes13;
2808 var _config$interactionRe15;
2809 var _config$secondaryLoca13;
2810 var config = this.getConfig();
2811 return this.dispatchEvent(config === null || config === void 0 || (_config$names12 = config.names) === null || _config$names12 === void 0 || (_config$names12 = _config$names12.editorOne) === null || _config$names12 === void 0 ? void 0 : _config$names12.wpDashThemeBuilderClick, this.createWpDashPayload({
2812 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers12 = config.triggers) === null || _config$triggers12 === void 0 ? void 0 : _config$triggers12.click),
2813 target_type: config === null || config === void 0 || (_config$targetTypes13 = config.targetTypes) === null || _config$targetTypes13 === void 0 ? void 0 : _config$targetTypes13.wpDashSubMenuItem,
2814 target_name: "theme_builder_menu_item",
2815 interaction_result: config === null || config === void 0 || (_config$interactionRe15 = config.interactionResults) === null || _config$interactionRe15 === void 0 ? void 0 : _config$interactionRe15.themeBuilderPromotionWindow,
2816 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca13 = config.secondaryLocations) === null || _config$secondaryLoca13 === void 0 ? void 0 : _config$secondaryLoca13.wpDashThemeBuilder),
2817 interaction_description: "core_user_clicked_theme_builder_menu_item"
2818 }));
2819 }
2820 },
2821 {
2822 key: "sendSidebarMenuItemClicked",
2823 value: function sendSidebarMenuItemClicked(_ref8) {
2824 var eventId = _ref8.eventId;
2825 var groupEventId = _ref8.groupEventId;
2826 try {
2827 var _config$windowNames;
2828 var _config$triggers13;
2829 var _config$targetTypes14;
2830 var _config$interactionRe16;
2831 var _config$locations12;
2832 var _config$names13;
2833 var config = this.getConfig();
2834 var payload = this.createBasePayload({
2835 window_name: config === null || config === void 0 || (_config$windowNames = config.windowNames) === null || _config$windowNames === void 0 ? void 0 : _config$windowNames.sidebarMenu,
2836 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers13 = config.triggers) === null || _config$triggers13 === void 0 ? void 0 : _config$triggers13.click),
2837 target_type: config === null || config === void 0 || (_config$targetTypes14 = config.targetTypes) === null || _config$targetTypes14 === void 0 ? void 0 : _config$targetTypes14.link,
2838 target_name: eventId,
2839 interaction_result: config === null || config === void 0 || (_config$interactionRe16 = config.interactionResults) === null || _config$interactionRe16 === void 0 ? void 0 : _config$interactionRe16.pageOpened,
2840 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations12 = config.locations) === null || _config$locations12 === void 0 ? void 0 : _config$locations12.sidebar)
2841 });
2842 if (groupEventId) payload.location_l1 = groupEventId;
2843 return this.dispatchEvent(config === null || config === void 0 || (_config$names13 = config.names) === null || _config$names13 === void 0 || (_config$names13 = _config$names13.editorOne) === null || _config$names13 === void 0 ? void 0 : _config$names13.sidebarMenuItemClicked, payload);
2844 } catch (error) {
2845 return false;
2846 }
2847 }
2848 },
2849 {
2850 key: "sendSidebarMenuGroupToggled",
2851 value: function sendSidebarMenuGroupToggled(_ref9) {
2852 var eventId = _ref9.eventId;
2853 var isExpanded = _ref9.isExpanded;
2854 try {
2855 var _config$interactionRe17;
2856 var _config$interactionRe18;
2857 var _config$names14;
2858 var _config$windowNames2;
2859 var _config$triggers14;
2860 var _config$targetTypes15;
2861 var _config$locations13;
2862 var config = this.getConfig();
2863 var interactionResult = isExpanded ? config === null || config === void 0 || (_config$interactionRe17 = config.interactionResults) === null || _config$interactionRe17 === void 0 ? void 0 : _config$interactionRe17.expanded : config === null || config === void 0 || (_config$interactionRe18 = config.interactionResults) === null || _config$interactionRe18 === void 0 ? void 0 : _config$interactionRe18.collapsed;
2864 return this.dispatchEvent(config === null || config === void 0 || (_config$names14 = config.names) === null || _config$names14 === void 0 || (_config$names14 = _config$names14.editorOne) === null || _config$names14 === void 0 ? void 0 : _config$names14.sidebarMenuGroupToggled, this.createBasePayload({
2865 window_name: config === null || config === void 0 || (_config$windowNames2 = config.windowNames) === null || _config$windowNames2 === void 0 ? void 0 : _config$windowNames2.sidebarMenu,
2866 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers14 = config.triggers) === null || _config$triggers14 === void 0 ? void 0 : _config$triggers14.click),
2867 target_type: config === null || config === void 0 || (_config$targetTypes15 = config.targetTypes) === null || _config$targetTypes15 === void 0 ? void 0 : _config$targetTypes15.toggle,
2868 target_name: eventId,
2869 interaction_result: interactionResult,
2870 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations13 = config.locations) === null || _config$locations13 === void 0 ? void 0 : _config$locations13.sidebar)
2871 }));
2872 } catch (error) {
2873 return false;
2874 }
2875 }
2876 }
2877 ]);
2878 }();
2879 var createDebouncedFinderSearch = function createDebouncedFinderSearch() {
2880 var delay = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 300;
2881 return _.debounce(function(resultsCount, searchTerm) {
2882 EditorOneEventManager.sendFinderSearchInput({
2883 resultsCount,
2884 searchTerm
2885 });
2886 }, delay);
2887 };
2888
2889 //#endregion
2890 //#region core/common/modules/finder/assets/js/modal/views/item.js
2891 function _callSuper$22(t, o, e) {
2892 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$22() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2893 }
2894 __name(_callSuper$22, "_callSuper");
2895 function _isNativeReflectConstruct$22() {
2896 try {
2897 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2898 } catch (t) {}
2899 return (_isNativeReflectConstruct$22 = function _isNativeReflectConstruct() {
2900 return !!t;
2901 })();
2902 }
2903 __name(_isNativeReflectConstruct$22, "_isNativeReflectConstruct");
2904 var _default$9 = /*#__PURE__*/ function(_Marionette$ItemView) {
2905 function _default() {
2906 _classCallCheck(this, _default);
2907 return _callSuper$22(this, _default, arguments);
2908 }
2909 _inherits$1(_default, _Marionette$ItemView);
2910 return _createClass(_default, [
2911 {
2912 key: "className",
2913 value: function className() {
2914 return "elementor-finder__results__item";
2915 }
2916 },
2917 {
2918 key: "getTemplate",
2919 value: function getTemplate() {
2920 return "#tmpl-elementor-finder__results__item";
2921 }
2922 },
2923 {
2924 key: "events",
2925 value: function events() {
2926 this.$el[0].addEventListener("click", this.onClick.bind(this), true);
2927 }
2928 },
2929 {
2930 key: "trackResultSelect",
2931 value: function trackResultSelect() {
2932 var title = this.model.get("title");
2933 EditorOneEventManager.sendFinderResultSelect(title);
2934 }
2935 },
2936 {
2937 key: "onClick",
2938 value: function onClick(e) {
2939 var _this = this;
2940 var lockOptions = this.model.get("lock");
2941 if (!(lockOptions !== null && lockOptions !== void 0 && lockOptions.is_locked)) {
2942 this.trackResultSelect();
2943 var url = this.model.get("url") || "";
2944 if (url.includes("page=elementor-app") && window.$e) {
2945 e.preventDefault();
2946 e.stopImmediatePropagation();
2947 $e.run("finder/close");
2948 $e.run("app/open", { url });
2949 }
2950 return;
2951 }
2952 e.preventDefault();
2953 e.stopImmediatePropagation();
2954 elementorCommon.dialogsManager.createWidget("confirm", {
2955 id: "elementor-finder__lock-dialog",
2956 headerMessage: lockOptions.content.heading,
2957 message: lockOptions.content.description,
2958 position: {
2959 my: "center center",
2960 at: "center center"
2961 },
2962 strings: {
2963 confirm: lockOptions.button.text,
2964 cancel: (0, _wordpress_i18n.__)("Cancel", "elementor")
2965 },
2966 onConfirm: function onConfirm() {
2967 _this.trackResultSelect();
2968 var link = _this.replaceLockLinkPlaceholders(lockOptions.button.url);
2969 window.open(link, "_blank");
2970 }
2971 }).show();
2972 }
2973 },
2974 {
2975 key: "replaceLockLinkPlaceholders",
2976 value: function replaceLockLinkPlaceholders(link) {
2977 return link.replace(/%%utm_source%%/g, "finder").replace(/%%utm_medium%%/g, "wp-dash");
2978 }
2979 }
2980 ]);
2981 }(Marionette.ItemView);
2982
2983 //#endregion
2984 //#region core/common/modules/finder/assets/js/modal/model/item.js
2985 function _callSuper$21(t, o, e) {
2986 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$21() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2987 }
2988 __name(_callSuper$21, "_callSuper");
2989 function _isNativeReflectConstruct$21() {
2990 try {
2991 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2992 } catch (t) {}
2993 return (_isNativeReflectConstruct$21 = function _isNativeReflectConstruct() {
2994 return !!t;
2995 })();
2996 }
2997 __name(_isNativeReflectConstruct$21, "_isNativeReflectConstruct");
2998 var _default$8 = /*#__PURE__*/ function(_Backbone$Model) {
2999 function _default() {
3000 _classCallCheck(this, _default);
3001 return _callSuper$21(this, _default, arguments);
3002 }
3003 _inherits$1(_default, _Backbone$Model);
3004 return _createClass(_default, [{
3005 key: "defaults",
3006 value: function defaults() {
3007 return {
3008 description: "",
3009 icon: "settings",
3010 url: "",
3011 keywords: [],
3012 actions: [],
3013 lock: null
3014 };
3015 }
3016 }]);
3017 }(Backbone.Model);
3018
3019 //#endregion
3020 //#region core/common/modules/finder/assets/js/modal/views/category.js
3021 function _callSuper$20(t, o, e) {
3022 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$20() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3023 }
3024 __name(_callSuper$20, "_callSuper");
3025 function _isNativeReflectConstruct$20() {
3026 try {
3027 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3028 } catch (t) {}
3029 return (_isNativeReflectConstruct$20 = function _isNativeReflectConstruct() {
3030 return !!t;
3031 })();
3032 }
3033 __name(_isNativeReflectConstruct$20, "_isNativeReflectConstruct");
3034 var _default$7 = /*#__PURE__*/ function(_Marionette$Composite) {
3035 function _default() {
3036 _classCallCheck(this, _default);
3037 return _callSuper$20(this, _default, arguments);
3038 }
3039 _inherits$1(_default, _Marionette$Composite);
3040 return _createClass(_default, [
3041 {
3042 key: "className",
3043 value: function className() {
3044 return "elementor-finder__results__category";
3045 }
3046 },
3047 {
3048 key: "getTemplate",
3049 value: function getTemplate() {
3050 return "#tmpl-elementor-finder__results__category";
3051 }
3052 },
3053 {
3054 key: "getChildView",
3055 value: function getChildView() {
3056 return _default$9;
3057 }
3058 },
3059 {
3060 key: "initialize",
3061 value: function initialize() {
3062 this.childViewContainer = ".elementor-finder__results__category__items";
3063 this.isVisible = true;
3064 var items = this.model.get("items");
3065 if (items) items = Object.values(items);
3066 this.collection = new Backbone.Collection(items, { model: _default$8 });
3067 }
3068 },
3069 {
3070 key: "filter",
3071 value: function filter(childModel) {
3072 var textFilter = this.getTextFilter();
3073 if (childModel.get("title").toLowerCase().indexOf(textFilter) >= 0) return true;
3074 return childModel.get("keywords").some(function(keyword) {
3075 return keyword.indexOf(textFilter) >= 0;
3076 });
3077 }
3078 },
3079 {
3080 key: "getTextFilter",
3081 value: function getTextFilter() {
3082 return elementorCommon.finder.channel.request("filter:text").trim().toLowerCase();
3083 }
3084 },
3085 {
3086 key: "toggleElement",
3087 value: function toggleElement() {
3088 var isCurrentlyVisible = !!this.children.length;
3089 if (isCurrentlyVisible !== this.isVisible) {
3090 this.isVisible = isCurrentlyVisible;
3091 this.$el.toggle(isCurrentlyVisible);
3092 this.triggerMethod("toggle:visibility");
3093 }
3094 }
3095 },
3096 {
3097 key: "onRender",
3098 value: function onRender() {
3099 this.listenTo(elementorCommon.finder.channel, "filter:change", this.onFilterChange.bind(this));
3100 }
3101 },
3102 {
3103 key: "onFilterChange",
3104 value: function onFilterChange() {
3105 this._renderChildren();
3106 }
3107 },
3108 {
3109 key: "onRenderCollection",
3110 value: function onRenderCollection() {
3111 this.toggleElement();
3112 }
3113 }
3114 ]);
3115 }(Marionette.CompositeView);
3116
3117 //#endregion
3118 //#region core/common/modules/finder/assets/js/modal/views/dynamic-category.js
3119 function _callSuper$19(t, o, e) {
3120 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$19() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3121 }
3122 __name(_callSuper$19, "_callSuper");
3123 function _isNativeReflectConstruct$19() {
3124 try {
3125 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3126 } catch (t) {}
3127 return (_isNativeReflectConstruct$19 = function _isNativeReflectConstruct() {
3128 return !!t;
3129 })();
3130 }
3131 __name(_isNativeReflectConstruct$19, "_isNativeReflectConstruct");
3132 function _superPropGet$5(t, o, e, r) {
3133 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
3134 return 2 & r && "function" == typeof p ? function(t) {
3135 return p.apply(e, t);
3136 } : p;
3137 }
3138 __name(_superPropGet$5, "_superPropGet");
3139 var _default$6 = /*#__PURE__*/ function(_Category) {
3140 function _default() {
3141 _classCallCheck(this, _default);
3142 return _callSuper$19(this, _default, arguments);
3143 }
3144 _inherits$1(_default, _Category);
3145 return _createClass(_default, [
3146 {
3147 key: "className",
3148 value: function className() {
3149 return _superPropGet$5(_default, "className", this, 3)([]) + " elementor-finder__results__category--dynamic";
3150 }
3151 },
3152 {
3153 key: "ui",
3154 value: function ui() {
3155 return { title: ".elementor-finder__results__category__title" };
3156 }
3157 },
3158 {
3159 key: "fetchData",
3160 value: function fetchData() {
3161 var _this = this;
3162 this.ui.loadingIcon.show();
3163 elementorCommon.ajax.addRequest("finder_get_category_items", {
3164 data: {
3165 category: this.model.get("name"),
3166 filter: this.getTextFilter()
3167 },
3168 success: function success(data) {
3169 if (_this.isDestroyed) return;
3170 _this.collection.set(data);
3171 _this.toggleElement();
3172 _this.ui.loadingIcon.hide();
3173 }
3174 });
3175 }
3176 },
3177 {
3178 key: "filter",
3179 value: function filter() {
3180 return true;
3181 }
3182 },
3183 {
3184 key: "onFilterChange",
3185 value: function onFilterChange() {
3186 this.fetchData();
3187 }
3188 },
3189 {
3190 key: "onRender",
3191 value: function onRender() {
3192 _superPropGet$5(_default, "onRender", this, 3)([]);
3193 this.ui.loadingIcon = jQuery("<i>", { class: "eicon-loading eicon-animation-spin" });
3194 this.ui.title.after(this.ui.loadingIcon);
3195 this.fetchData();
3196 }
3197 }
3198 ]);
3199 }(_default$7);
3200
3201 //#endregion
3202 //#region core/common/modules/finder/assets/js/modal/views/categories.js
3203 function _callSuper$18(t, o, e) {
3204 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$18() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3205 }
3206 __name(_callSuper$18, "_callSuper");
3207 function _isNativeReflectConstruct$18() {
3208 try {
3209 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3210 } catch (t) {}
3211 return (_isNativeReflectConstruct$18 = function _isNativeReflectConstruct() {
3212 return !!t;
3213 })();
3214 }
3215 __name(_isNativeReflectConstruct$18, "_isNativeReflectConstruct");
3216 var _default$5 = /*#__PURE__*/ function(_Marionette$Composite) {
3217 function _default() {
3218 _classCallCheck(this, _default);
3219 return _callSuper$18(this, _default, arguments);
3220 }
3221 _inherits$1(_default, _Marionette$Composite);
3222 return _createClass(_default, [
3223 {
3224 key: "id",
3225 value: function id() {
3226 return "elementor-finder__results-container";
3227 }
3228 },
3229 {
3230 key: "ui",
3231 value: function ui() {
3232 this.selectors = {
3233 noResults: "#elementor-finder__no-results",
3234 categoryItem: ".elementor-finder__results__item"
3235 };
3236 return this.selectors;
3237 }
3238 },
3239 {
3240 key: "events",
3241 value: function events() {
3242 return { "mouseenter @ui.categoryItem": "onCategoryItemMouseEnter" };
3243 }
3244 },
3245 {
3246 key: "getTemplate",
3247 value: function getTemplate() {
3248 return "#tmpl-elementor-finder-results-container";
3249 }
3250 },
3251 {
3252 key: "getChildView",
3253 value: function getChildView(childModel) {
3254 return childModel.get("dynamic") ? _default$6 : _default$7;
3255 }
3256 },
3257 {
3258 key: "initialize",
3259 value: function initialize() {
3260 this.$activeItem = null;
3261 this.childViewContainer = "#elementor-finder__results";
3262 this.collection = new Backbone.Collection(Object.values(elementorCommon.finder.getSettings("data")));
3263 }
3264 },
3265 {
3266 key: "activateItem",
3267 value: function activateItem($item) {
3268 if (this.$activeItem) this.$activeItem.removeClass("elementor-active");
3269 $item.addClass("elementor-active");
3270 this.$activeItem = $item;
3271 }
3272 },
3273 {
3274 key: "activateNextItem",
3275 value: function activateNextItem(reverse) {
3276 var $allItems = jQuery(this.selectors.categoryItem);
3277 var nextItemIndex = 0;
3278 if (this.$activeItem) {
3279 nextItemIndex = $allItems.index(this.$activeItem) + (reverse ? -1 : 1);
3280 if (nextItemIndex >= $allItems.length) nextItemIndex = 0;
3281 else if (nextItemIndex < 0) nextItemIndex = $allItems.length - 1;
3282 }
3283 var $nextItem = $allItems.eq(nextItemIndex);
3284 this.activateItem($nextItem);
3285 $nextItem[0].scrollIntoView({ block: "nearest" });
3286 }
3287 },
3288 {
3289 key: "goToActiveItem",
3290 value: function goToActiveItem(event) {
3291 var $a = this.$activeItem.children("a");
3292 var isControlClicked = $e.shortcuts.isControlEvent(event);
3293 if (isControlClicked) $a.attr("target", "_blank");
3294 $a[0].click();
3295 if (isControlClicked) $a.removeAttr("target");
3296 }
3297 },
3298 {
3299 key: "onCategoryItemMouseEnter",
3300 value: function onCategoryItemMouseEnter(event) {
3301 this.activateItem(jQuery(event.currentTarget));
3302 }
3303 },
3304 {
3305 key: "onChildviewToggleVisibility",
3306 value: function onChildviewToggleVisibility() {
3307 var allCategoriesAreEmpty = this.children.every(function(child) {
3308 return !child.isVisible;
3309 });
3310 this.ui.noResults.toggle(allCategoriesAreEmpty);
3311 }
3312 }
3313 ]);
3314 }(Marionette.CompositeView);
3315
3316 //#endregion
3317 //#region core/common/modules/finder/assets/js/modal/views/content.js
3318 function _callSuper$17(t, o, e) {
3319 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$17() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3320 }
3321 __name(_callSuper$17, "_callSuper");
3322 function _isNativeReflectConstruct$17() {
3323 try {
3324 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3325 } catch (t) {}
3326 return (_isNativeReflectConstruct$17 = function _isNativeReflectConstruct() {
3327 return !!t;
3328 })();
3329 }
3330 __name(_isNativeReflectConstruct$17, "_isNativeReflectConstruct");
3331 var FINDER_SEARCH_DEBOUNCE_MS = 300;
3332 var _default$4 = /*#__PURE__*/ function(_Marionette$LayoutVie) {
3333 function _default() {
3334 _classCallCheck(this, _default);
3335 return _callSuper$17(this, _default, arguments);
3336 }
3337 _inherits$1(_default, _Marionette$LayoutVie);
3338 return _createClass(_default, [
3339 {
3340 key: "id",
3341 value: function id() {
3342 return "elementor-finder";
3343 }
3344 },
3345 {
3346 key: "getTemplate",
3347 value: function getTemplate() {
3348 return "#tmpl-elementor-finder";
3349 }
3350 },
3351 {
3352 key: "ui",
3353 value: function ui() {
3354 return { searchInput: "#elementor-finder__search__input" };
3355 }
3356 },
3357 {
3358 key: "events",
3359 value: function events() {
3360 return { "input @ui.searchInput": "onSearchInputInput" };
3361 }
3362 },
3363 {
3364 key: "regions",
3365 value: function regions() {
3366 return { content: "#elementor-finder__content" };
3367 }
3368 },
3369 {
3370 key: "initialize",
3371 value: function initialize() {
3372 this.debouncedTrackSearch = createDebouncedFinderSearch(FINDER_SEARCH_DEBOUNCE_MS);
3373 }
3374 },
3375 {
3376 key: "showCategoriesView",
3377 value: function showCategoriesView() {
3378 this.content.show(new _default$5());
3379 }
3380 },
3381 {
3382 key: "getResultsCount",
3383 value: function getResultsCount() {
3384 if (!this.content.currentView) return 0;
3385 return this.content.currentView.$el.find(".elementor-finder__results__item:visible").length;
3386 }
3387 },
3388 {
3389 key: "onSearchInputInput",
3390 value: function onSearchInputInput() {
3391 var _this = this;
3392 var value = this.ui.searchInput.val();
3393 if (value) {
3394 elementorCommon.finder.channel.reply("filter:text", value).trigger("filter:change");
3395 if (!(this.content.currentView instanceof _default$5)) this.showCategoriesView();
3396 setTimeout(function() {
3397 var resultsCount = _this.getResultsCount();
3398 _this.debouncedTrackSearch(resultsCount, value);
3399 }, 50);
3400 }
3401 this.content.currentView.$el.toggle(!!value);
3402 }
3403 },
3404 {
3405 key: "onDestroy",
3406 value: function onDestroy() {
3407 var _this$debouncedTrackS;
3408 if ((_this$debouncedTrackS = this.debouncedTrackSearch) !== null && _this$debouncedTrackS !== void 0 && _this$debouncedTrackS.cancel) this.debouncedTrackSearch.cancel();
3409 }
3410 }
3411 ]);
3412 }(Marionette.LayoutView);
3413
3414 //#endregion
3415 //#region core/common/modules/finder/assets/js/modal/views/layout.js
3416 function _callSuper$16(t, o, e) {
3417 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$16() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3418 }
3419 __name(_callSuper$16, "_callSuper");
3420 function _isNativeReflectConstruct$16() {
3421 try {
3422 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3423 } catch (t) {}
3424 return (_isNativeReflectConstruct$16 = function _isNativeReflectConstruct() {
3425 return !!t;
3426 })();
3427 }
3428 __name(_isNativeReflectConstruct$16, "_isNativeReflectConstruct");
3429 function _superPropGet$4(t, o, e, r) {
3430 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
3431 return 2 & r && "function" == typeof p ? function(t) {
3432 return p.apply(e, t);
3433 } : p;
3434 }
3435 __name(_superPropGet$4, "_superPropGet");
3436 var _default$3 = /*#__PURE__*/ function(_elementorModules$com) {
3437 function _default() {
3438 _classCallCheck(this, _default);
3439 return _callSuper$16(this, _default, arguments);
3440 }
3441 _inherits$1(_default, _elementorModules$com);
3442 return _createClass(_default, [
3443 {
3444 key: "getModalOptions",
3445 value: function getModalOptions() {
3446 return {
3447 id: "elementor-finder__modal",
3448 draggable: true,
3449 effects: {
3450 show: "show",
3451 hide: "hide"
3452 },
3453 position: { enable: false }
3454 };
3455 }
3456 },
3457 {
3458 key: "getLogoOptions",
3459 value: function getLogoOptions() {
3460 return { title: (0, _wordpress_i18n.__)("Finder", "elementor") };
3461 }
3462 },
3463 {
3464 key: "initialize",
3465 value: function initialize() {
3466 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
3467 _superPropGet$4(_default, "initialize", this, 3)(args);
3468 this.showLogo();
3469 this.showContentView();
3470 }
3471 },
3472 {
3473 key: "showContentView",
3474 value: function showContentView() {
3475 this.modalContent.show(new _default$4());
3476 }
3477 },
3478 {
3479 key: "showModal",
3480 value: function showModal() {
3481 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2];
3482 _superPropGet$4(_default, "showModal", this, 3)(args);
3483 this.modalContent.currentView.ui.searchInput.focus();
3484 }
3485 }
3486 ]);
3487 }(elementorModules.common.views.modal.Layout);
3488
3489 //#endregion
3490 //#region core/common/modules/finder/assets/js/commands/navigate-down.js
3491 function _callSuper$15(t, o, e) {
3492 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$15() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3493 }
3494 __name(_callSuper$15, "_callSuper");
3495 function _isNativeReflectConstruct$15() {
3496 try {
3497 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3498 } catch (t) {}
3499 return (_isNativeReflectConstruct$15 = function _isNativeReflectConstruct() {
3500 return !!t;
3501 })();
3502 }
3503 __name(_isNativeReflectConstruct$15, "_isNativeReflectConstruct");
3504 var NavigateDown = /*#__PURE__*/ function(_CommandBase) {
3505 function NavigateDown() {
3506 _classCallCheck(this, NavigateDown);
3507 return _callSuper$15(this, NavigateDown, arguments);
3508 }
3509 _inherits$1(NavigateDown, _CommandBase);
3510 return _createClass(NavigateDown, [{
3511 key: "apply",
3512 value: function apply() {
3513 this.component.getItemsView().activateNextItem();
3514 }
3515 }]);
3516 }(CommandBase);
3517
3518 //#endregion
3519 //#region core/common/modules/finder/assets/js/commands/navigate-select.js
3520 function _callSuper$14(t, o, e) {
3521 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$14() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3522 }
3523 __name(_callSuper$14, "_callSuper");
3524 function _isNativeReflectConstruct$14() {
3525 try {
3526 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3527 } catch (t) {}
3528 return (_isNativeReflectConstruct$14 = function _isNativeReflectConstruct() {
3529 return !!t;
3530 })();
3531 }
3532 __name(_isNativeReflectConstruct$14, "_isNativeReflectConstruct");
3533 var NavigateSelect = /*#__PURE__*/ function(_CommandBase) {
3534 function NavigateSelect() {
3535 _classCallCheck(this, NavigateSelect);
3536 return _callSuper$14(this, NavigateSelect, arguments);
3537 }
3538 _inherits$1(NavigateSelect, _CommandBase);
3539 return _createClass(NavigateSelect, [{
3540 key: "apply",
3541 value: function apply(args) {
3542 this.component.getItemsView().goToActiveItem(args);
3543 }
3544 }]);
3545 }(CommandBase);
3546
3547 //#endregion
3548 //#region core/common/modules/finder/assets/js/commands/navigate-up.js
3549 function _callSuper$13(t, o, e) {
3550 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$13() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3551 }
3552 __name(_callSuper$13, "_callSuper");
3553 function _isNativeReflectConstruct$13() {
3554 try {
3555 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3556 } catch (t) {}
3557 return (_isNativeReflectConstruct$13 = function _isNativeReflectConstruct() {
3558 return !!t;
3559 })();
3560 }
3561 __name(_isNativeReflectConstruct$13, "_isNativeReflectConstruct");
3562 var NavigateUp = /*#__PURE__*/ function(_CommandBase) {
3563 function NavigateUp() {
3564 _classCallCheck(this, NavigateUp);
3565 return _callSuper$13(this, NavigateUp, arguments);
3566 }
3567 _inherits$1(NavigateUp, _CommandBase);
3568 return _createClass(NavigateUp, [{
3569 key: "apply",
3570 value: function apply() {
3571 this.component.getItemsView().activateNextItem(true);
3572 }
3573 }]);
3574 }(CommandBase);
3575
3576 //#endregion
3577 //#region core/common/modules/finder/assets/js/commands/index.js
3578 var commands_exports = /* @__PURE__ */ __exportAll({
3579 NavigateDown: () => NavigateDown,
3580 NavigateSelect: () => NavigateSelect,
3581 NavigateUp: () => NavigateUp
3582 });
3583
3584 //#endregion
3585 //#region core/common/modules/finder/assets/js/component.js
3586 init_defineProperty();
3587 function ownKeys$3(e, r) {
3588 var t = Object.keys(e);
3589 if (Object.getOwnPropertySymbols) {
3590 var o = Object.getOwnPropertySymbols(e);
3591 r && (o = o.filter(function(r) {
3592 return Object.getOwnPropertyDescriptor(e, r).enumerable;
3593 })), t.push.apply(t, o);
3594 }
3595 return t;
3596 }
3597 __name(ownKeys$3, "ownKeys");
3598 function _objectSpread$3(e) {
3599 for (var r = 1; r < arguments.length; r++) {
3600 var t = null != arguments[r] ? arguments[r] : {};
3601 r % 2 ? ownKeys$3(Object(t), !0).forEach(function(r) {
3602 _defineProperty(e, r, t[r]);
3603 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function(r) {
3604 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
3605 });
3606 }
3607 return e;
3608 }
3609 __name(_objectSpread$3, "_objectSpread");
3610 function _callSuper$12(t, o, e) {
3611 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$12() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3612 }
3613 __name(_callSuper$12, "_callSuper");
3614 function _isNativeReflectConstruct$12() {
3615 try {
3616 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3617 } catch (t) {}
3618 return (_isNativeReflectConstruct$12 = function _isNativeReflectConstruct() {
3619 return !!t;
3620 })();
3621 }
3622 __name(_isNativeReflectConstruct$12, "_isNativeReflectConstruct");
3623 function _superPropGet$3(t, o, e, r) {
3624 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
3625 return 2 & r && "function" == typeof p ? function(t) {
3626 return p.apply(e, t);
3627 } : p;
3628 }
3629 __name(_superPropGet$3, "_superPropGet");
3630 var Component$2 = /*#__PURE__*/ function(_ComponentModalBase) {
3631 function Component() {
3632 _classCallCheck(this, Component);
3633 return _callSuper$12(this, Component, arguments);
3634 }
3635 _inherits$1(Component, _ComponentModalBase);
3636 return _createClass(Component, [
3637 {
3638 key: "getNamespace",
3639 value: function getNamespace() {
3640 return "finder";
3641 }
3642 },
3643 {
3644 key: "defaultShortcuts",
3645 value: function defaultShortcuts() {
3646 var _this = this;
3647 return {
3648 "": { keys: "ctrl+e" },
3649 "navigate-down": {
3650 keys: "down",
3651 scopes: [this.getNamespace()],
3652 dependency: function dependency() {
3653 return _this.getItemsView();
3654 }
3655 },
3656 "navigate-up": {
3657 keys: "up",
3658 scopes: [this.getNamespace()],
3659 dependency: function dependency() {
3660 return _this.getItemsView();
3661 }
3662 },
3663 "navigate-select": {
3664 keys: "enter",
3665 scopes: [this.getNamespace()],
3666 dependency: function dependency() {
3667 return _this.getItemsView().$activeItem;
3668 }
3669 }
3670 };
3671 }
3672 },
3673 {
3674 key: "defaultCommands",
3675 value: function defaultCommands() {
3676 return _objectSpread$3(_objectSpread$3({
3677 "navigate/down": function navigate_down() {
3678 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/down' )", "3.0.0", "$e.run( 'finder/navigate-down' )");
3679 $e.run("finder/navigate-down");
3680 },
3681 "navigate/up": function navigate_up() {
3682 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/up' )", "3.0.0", "$e.run( 'finder/navigate-up' )");
3683 $e.run("finder/navigate-up");
3684 },
3685 "navigate/select": function navigate_select(event) {
3686 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/select', event )", "3.0.0", "$e.run( 'finder/navigate-select', event )");
3687 $e.run("finder/navigate-select", event);
3688 }
3689 }, _superPropGet$3(Component, "defaultCommands", this, 3)([])), this.importCommands(commands_exports));
3690 }
3691 },
3692 {
3693 key: "getModalLayout",
3694 value: function getModalLayout() {
3695 return _default$3;
3696 }
3697 },
3698 {
3699 key: "getItemsView",
3700 value: function getItemsView() {
3701 return this.layout.modalContent.currentView.content.currentView;
3702 }
3703 }
3704 ]);
3705 }(ComponentModalBase);
3706
3707 //#endregion
3708 //#region core/common/modules/finder/assets/js/finder.js
3709 function _callSuper$11(t, o, e) {
3710 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$11() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3711 }
3712 __name(_callSuper$11, "_callSuper");
3713 function _isNativeReflectConstruct$11() {
3714 try {
3715 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3716 } catch (t) {}
3717 return (_isNativeReflectConstruct$11 = function _isNativeReflectConstruct() {
3718 return !!t;
3719 })();
3720 }
3721 __name(_isNativeReflectConstruct$11, "_isNativeReflectConstruct");
3722 var _default$2 = /*#__PURE__*/ function(_elementorModules$Mod) {
3723 function _default() {
3724 _classCallCheck(this, _default);
3725 return _callSuper$11(this, _default, arguments);
3726 }
3727 _inherits$1(_default, _elementorModules$Mod);
3728 return _createClass(_default, [{
3729 key: "onInit",
3730 value: function onInit() {
3731 if (window.top !== window) return;
3732 this.channel = Backbone.Radio.channel("ELEMENTOR:finder");
3733 $e.components.register(new Component$2({ manager: this }));
3734 }
3735 }]);
3736 }(elementorModules.Module);
3737
3738 //#endregion
3739 //#region core/common/modules/connect/assets/js/connect.js
3740 function _callSuper$10(t, o, e) {
3741 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$10() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3742 }
3743 __name(_callSuper$10, "_callSuper");
3744 function _isNativeReflectConstruct$10() {
3745 try {
3746 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3747 } catch (t) {}
3748 return (_isNativeReflectConstruct$10 = function _isNativeReflectConstruct() {
3749 return !!t;
3750 })();
3751 }
3752 __name(_isNativeReflectConstruct$10, "_isNativeReflectConstruct");
3753 function _superPropGet$2(t, o, e, r) {
3754 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
3755 return 2 & r && "function" == typeof p ? function(t) {
3756 return p.apply(e, t);
3757 } : p;
3758 }
3759 __name(_superPropGet$2, "_superPropGet");
3760 var _default$1 = /*#__PURE__*/ function(_elementorModules$Vie) {
3761 function _default() {
3762 _classCallCheck(this, _default);
3763 return _callSuper$10(this, _default, arguments);
3764 }
3765 _inherits$1(_default, _elementorModules$Vie);
3766 return _createClass(_default, [
3767 {
3768 key: "addPopupPlugin",
3769 value: function addPopupPlugin() {
3770 var counter = 0;
3771 jQuery.fn.elementorConnect = function(options) {
3772 var _this = this;
3773 if (options !== null && options !== void 0 && options.popup) {
3774 jQuery(this).on("click", function(event) {
3775 var _options$popup;
3776 var _options$popup2;
3777 event.preventDefault();
3778 var width = ((_options$popup = options.popup) === null || _options$popup === void 0 ? void 0 : _options$popup.width) || 600;
3779 var height = ((_options$popup2 = options.popup) === null || _options$popup2 === void 0 ? void 0 : _options$popup2.height) || 700;
3780 window.open(jQuery(_this).attr("href") + "&mode=popup", "elementorConnect", "toolbar=no, menubar=no, width=".concat(width, ", height=").concat(height, ", top=200, left=0"));
3781 });
3782 delete options.popup;
3783 }
3784 var settings = jQuery.extend({
3785 success: function success() {
3786 return location.reload();
3787 },
3788 error: function error() {
3789 elementor.notifications.showToast({ message: (0, _wordpress_i18n.__)("Unable to connect", "elementor") });
3790 },
3791 parseUrl: function parseUrl(url) {
3792 return url;
3793 }
3794 }, options);
3795 this.each(function() {
3796 counter++;
3797 var $this = jQuery(this);
3798 var callbackId = "cb" + counter;
3799 $this.attr({
3800 target: "_blank",
3801 rel: "opener",
3802 href: settings.parseUrl($this.attr("href") + "&mode=popup&callback_id=" + callbackId)
3803 });
3804 elementorCommon.elements.$window.on("elementor/connect/success/" + callbackId, settings.success).on("elementor/connect/error/" + callbackId, settings.error);
3805 });
3806 return this;
3807 };
3808 }
3809 },
3810 {
3811 key: "getDefaultSettings",
3812 value: function getDefaultSettings() {
3813 return { selectors: { connectButton: "#elementor-template-library-connect__button" } };
3814 }
3815 },
3816 {
3817 key: "getDefaultElements",
3818 value: function getDefaultElements() {
3819 return { $connectButton: jQuery(this.getSettings("selectors.connectButton")) };
3820 }
3821 },
3822 {
3823 key: "applyPopup",
3824 value: function applyPopup() {
3825 this.elements.$connectButton.elementorConnect();
3826 }
3827 },
3828 {
3829 key: "onInit",
3830 value: function onInit() {
3831 _superPropGet$2(_default, "onInit", this, 3)([]);
3832 this.addPopupPlugin();
3833 this.applyPopup();
3834 }
3835 }
3836 ]);
3837 }(elementorModules.ViewModule);
3838
3839 //#endregion
3840 //#region node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
3841 function asyncGeneratorStep$1(n, t, e, r, o, a, c) {
3842 try {
3843 var i = n[a](c);
3844 var u = i.value;
3845 } catch (n) {
3846 e(n);
3847 return;
3848 }
3849 i.done ? t(u) : Promise.resolve(u).then(r, o);
3850 }
3851 __name(asyncGeneratorStep$1, "asyncGeneratorStep");
3852 function _asyncToGenerator(n) {
3853 return function() {
3854 var t = this;
3855 var e = arguments;
3856 return new Promise(function(r, o) {
3857 var a = n.apply(t, e);
3858 function _next(n) {
3859 asyncGeneratorStep$1(a, r, o, _next, _throw, "next", n);
3860 }
3861 function _throw(n) {
3862 asyncGeneratorStep$1(a, r, o, _next, _throw, "throw", n);
3863 }
3864 _next(void 0);
3865 });
3866 };
3867 }
3868
3869 //#endregion
3870 //#region node_modules/@babel/runtime/helpers/OverloadYield.js
3871 var require_OverloadYield = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3872 function _OverloadYield(e, d) {
3873 this.v = e, this.k = d;
3874 }
3875 module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
3876 }));
3877
3878 //#endregion
3879 //#region node_modules/@babel/runtime/helpers/regeneratorDefine.js
3880 var require_regeneratorDefine = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3881 function _regeneratorDefine(e, r, n, t) {
3882 var i = Object.defineProperty;
3883 try {
3884 i({}, "", {});
3885 } catch (e) {
3886 i = 0;
3887 }
3888 module.exports = _regeneratorDefine = function regeneratorDefine(e, r, n, t) {
3889 function o(r, n) {
3890 _regeneratorDefine(e, r, function(e) {
3891 return this._invoke(r, n, e);
3892 });
3893 }
3894 r ? i ? i(e, r, {
3895 value: n,
3896 enumerable: !t,
3897 configurable: !t,
3898 writable: !t
3899 }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
3900 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _regeneratorDefine(e, r, n, t);
3901 }
3902 module.exports = _regeneratorDefine, module.exports.__esModule = true, module.exports["default"] = module.exports;
3903 }));
3904
3905 //#endregion
3906 //#region node_modules/@babel/runtime/helpers/regenerator.js
3907 var require_regenerator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3908 var regeneratorDefine = require_regeneratorDefine();
3909 function _regenerator() {
3910 /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
3911 var e;
3912 var t;
3913 var r = "function" == typeof Symbol ? Symbol : {};
3914 var n = r.iterator || "@@iterator";
3915 var o = r.toStringTag || "@@toStringTag";
3916 function i(r, n, o, i) {
3917 var c = n && n.prototype instanceof Generator ? n : Generator;
3918 var u = Object.create(c.prototype);
3919 return regeneratorDefine(u, "_invoke", function(r, n, o) {
3920 var i;
3921 var c;
3922 var u;
3923 var f = 0;
3924 var p = o || [];
3925 var y = !1;
3926 var G = {
3927 p: 0,
3928 n: 0,
3929 v: e,
3930 a: d,
3931 f: d.bind(e, 4),
3932 d: function d(t, r) {
3933 return i = t, c = 0, u = e, G.n = r, a;
3934 }
3935 };
3936 function d(r, n) {
3937 for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
3938 var o;
3939 var i = p[t];
3940 var d = G.p;
3941 var l = i[2];
3942 r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
3943 }
3944 if (o || r > 1) return a;
3945 throw y = !0, n;
3946 }
3947 return function(o, p, l) {
3948 if (f > 1) throw TypeError("Generator is already running");
3949 for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
3950 i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
3951 try {
3952 if (f = 2, i) {
3953 if (c || (o = "next"), t = i[o]) {
3954 if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
3955 if (!t.done) return t;
3956 u = t.value, c < 2 && (c = 0);
3957 } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
3958 i = e;
3959 } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
3960 } catch (t) {
3961 i = e, c = 1, u = t;
3962 } finally {
3963 f = 1;
3964 }
3965 }
3966 return {
3967 value: t,
3968 done: y
3969 };
3970 };
3971 }(r, o, i), !0), u;
3972 }
3973 var a = {};
3974 function Generator() {}
3975 function GeneratorFunction() {}
3976 function GeneratorFunctionPrototype() {}
3977 t = Object.getPrototypeOf;
3978 var c = [][n] ? t(t([][n]())) : (regeneratorDefine(t = {}, n, function() {
3979 return this;
3980 }), t);
3981 var u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
3982 function f(e) {
3983 return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
3984 }
3985 return GeneratorFunction.prototype = GeneratorFunctionPrototype, regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), regeneratorDefine(u), regeneratorDefine(u, o, "Generator"), regeneratorDefine(u, n, function() {
3986 return this;
3987 }), regeneratorDefine(u, "toString", function() {
3988 return "[object Generator]";
3989 }), (module.exports = _regenerator = function _regenerator() {
3990 return {
3991 w: i,
3992 m: f
3993 };
3994 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
3995 }
3996 module.exports = _regenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
3997 }));
3998
3999 //#endregion
4000 //#region node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js
4001 var require_regeneratorAsyncIterator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4002 var OverloadYield = require_OverloadYield();
4003 var regeneratorDefine = require_regeneratorDefine();
4004 function AsyncIterator(t, e) {
4005 function n(r, o, i, f) {
4006 try {
4007 var c = t[r](o);
4008 var u = c.value;
4009 return u instanceof OverloadYield ? e.resolve(u.v).then(function(t) {
4010 n("next", t, i, f);
4011 }, function(t) {
4012 n("throw", t, i, f);
4013 }) : e.resolve(u).then(function(t) {
4014 c.value = t, i(c);
4015 }, function(t) {
4016 return n("throw", t, i, f);
4017 });
4018 } catch (t) {
4019 f(t);
4020 }
4021 }
4022 var r;
4023 this.next || (regeneratorDefine(AsyncIterator.prototype), regeneratorDefine(AsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function() {
4024 return this;
4025 })), regeneratorDefine(this, "_invoke", function(t, o, i) {
4026 function f() {
4027 return new e(function(e, r) {
4028 n(t, i, e, r);
4029 });
4030 }
4031 return r = r ? r.then(f, f) : f();
4032 }, !0);
4033 }
4034 module.exports = AsyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports;
4035 }));
4036
4037 //#endregion
4038 //#region node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js
4039 var require_regeneratorAsyncGen = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4040 var regenerator = require_regenerator$1();
4041 var regeneratorAsyncIterator = require_regeneratorAsyncIterator();
4042 function _regeneratorAsyncGen(r, e, t, o, n) {
4043 return new regeneratorAsyncIterator(regenerator().w(r, e, t, o), n || Promise);
4044 }
4045 module.exports = _regeneratorAsyncGen, module.exports.__esModule = true, module.exports["default"] = module.exports;
4046 }));
4047
4048 //#endregion
4049 //#region node_modules/@babel/runtime/helpers/regeneratorAsync.js
4050 var require_regeneratorAsync = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4051 var regeneratorAsyncGen = require_regeneratorAsyncGen();
4052 function _regeneratorAsync(n, e, r, t, o) {
4053 var a = regeneratorAsyncGen(n, e, r, t, o);
4054 return a.next().then(function(n) {
4055 return n.done ? n.value : a.next();
4056 });
4057 }
4058 module.exports = _regeneratorAsync, module.exports.__esModule = true, module.exports["default"] = module.exports;
4059 }));
4060
4061 //#endregion
4062 //#region node_modules/@babel/runtime/helpers/regeneratorKeys.js
4063 var require_regeneratorKeys = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4064 function _regeneratorKeys(e) {
4065 var n = Object(e);
4066 var r = [];
4067 for (var t in n) r.unshift(t);
4068 return function e() {
4069 for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e;
4070 return e.done = !0, e;
4071 };
4072 }
4073 module.exports = _regeneratorKeys, module.exports.__esModule = true, module.exports["default"] = module.exports;
4074 }));
4075
4076 //#endregion
4077 //#region node_modules/@babel/runtime/helpers/typeof.js
4078 var require_typeof = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4079 function _typeof(o) {
4080 "@babel/helpers - typeof";
4081 return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
4082 return typeof o;
4083 } : function(o) {
4084 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
4085 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
4086 }
4087 module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
4088 }));
4089
4090 //#endregion
4091 //#region node_modules/@babel/runtime/helpers/regeneratorValues.js
4092 var require_regeneratorValues = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4093 var _typeof = require_typeof()["default"];
4094 function _regeneratorValues(e) {
4095 if (null != e) {
4096 var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"];
4097 var r = 0;
4098 if (t) return t.call(e);
4099 if ("function" == typeof e.next) return e;
4100 if (!isNaN(e.length)) return { next: function next() {
4101 return e && r >= e.length && (e = void 0), {
4102 value: e && e[r++],
4103 done: !e
4104 };
4105 } };
4106 }
4107 throw new TypeError(_typeof(e) + " is not iterable");
4108 }
4109 module.exports = _regeneratorValues, module.exports.__esModule = true, module.exports["default"] = module.exports;
4110 }));
4111
4112 //#endregion
4113 //#region node_modules/@babel/runtime/helpers/regeneratorRuntime.js
4114 var require_regeneratorRuntime = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4115 var OverloadYield = require_OverloadYield();
4116 var regenerator = require_regenerator$1();
4117 var regeneratorAsync = require_regeneratorAsync();
4118 var regeneratorAsyncGen = require_regeneratorAsyncGen();
4119 var regeneratorAsyncIterator = require_regeneratorAsyncIterator();
4120 var regeneratorKeys = require_regeneratorKeys();
4121 var regeneratorValues = require_regeneratorValues();
4122 function _regeneratorRuntime() {
4123 "use strict";
4124 var r = regenerator();
4125 var e = r.m(_regeneratorRuntime);
4126 var t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor;
4127 function n(r) {
4128 var e = "function" == typeof r && r.constructor;
4129 return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name));
4130 }
4131 var o = {
4132 "throw": 1,
4133 "return": 2,
4134 "break": 3,
4135 "continue": 3
4136 };
4137 function a(r) {
4138 var e;
4139 var t;
4140 return function(n) {
4141 e || (e = {
4142 stop: function stop() {
4143 return t(n.a, 2);
4144 },
4145 "catch": function _catch() {
4146 return n.v;
4147 },
4148 abrupt: function abrupt(r, e) {
4149 return t(n.a, o[r], e);
4150 },
4151 delegateYield: function delegateYield(r, o, a) {
4152 return e.resultName = o, t(n.d, regeneratorValues(r), a);
4153 },
4154 finish: function finish(r) {
4155 return t(n.f, r);
4156 }
4157 }, t = function t(r, _t, o) {
4158 n.p = e.prev, n.n = e.next;
4159 try {
4160 return r(_t, o);
4161 } finally {
4162 e.next = n.n;
4163 }
4164 }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n;
4165 try {
4166 return r.call(this, e);
4167 } finally {
4168 n.p = e.prev, n.n = e.next;
4169 }
4170 };
4171 }
4172 return (module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
4173 return {
4174 wrap: function wrap(e, t, n, o) {
4175 return r.w(a(e), t, n, o && o.reverse());
4176 },
4177 isGeneratorFunction: n,
4178 mark: r.m,
4179 awrap: function awrap(r, e) {
4180 return new OverloadYield(r, e);
4181 },
4182 AsyncIterator: regeneratorAsyncIterator,
4183 async: function async(r, e, t, o, u) {
4184 return (n(e) ? regeneratorAsyncGen : regeneratorAsync)(a(r), e, t, o, u);
4185 },
4186 keys: regeneratorKeys,
4187 values: regeneratorValues
4188 };
4189 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
4190 }
4191 module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
4192 }));
4193
4194 //#endregion
4195 //#region node_modules/@babel/runtime/regenerator/index.js
4196 var require_regenerator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4197 var runtime = require_regeneratorRuntime()();
4198 module.exports = runtime;
4199 try {
4200 regeneratorRuntime = runtime;
4201 } catch (accidentalStrictMode) {
4202 if (typeof globalThis === "object") globalThis.regeneratorRuntime = runtime;
4203 else Function("r", "regeneratorRuntime = r")(runtime);
4204 }
4205 }));
4206
4207 //#endregion
4208 //#region modules/web-cli/assets/js/core/data/errors/base-error.js
4209 var import_regenerator = /* @__PURE__ */ __toESM(require_regenerator());
4210 init_defineProperty();
4211 function ownKeys$2(e, r) {
4212 var t = Object.keys(e);
4213 if (Object.getOwnPropertySymbols) {
4214 var o = Object.getOwnPropertySymbols(e);
4215 r && (o = o.filter(function(r) {
4216 return Object.getOwnPropertyDescriptor(e, r).enumerable;
4217 })), t.push.apply(t, o);
4218 }
4219 return t;
4220 }
4221 __name(ownKeys$2, "ownKeys");
4222 function _objectSpread$2(e) {
4223 for (var r = 1; r < arguments.length; r++) {
4224 var t = null != arguments[r] ? arguments[r] : {};
4225 r % 2 ? ownKeys$2(Object(t), !0).forEach(function(r) {
4226 _defineProperty(e, r, t[r]);
4227 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function(r) {
4228 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
4229 });
4230 }
4231 return e;
4232 }
4233 __name(_objectSpread$2, "_objectSpread");
4234 function _callSuper$9(t, o, e) {
4235 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$9() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4236 }
4237 __name(_callSuper$9, "_callSuper");
4238 function _isNativeReflectConstruct$9() {
4239 try {
4240 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4241 } catch (t) {}
4242 return (_isNativeReflectConstruct$9 = function _isNativeReflectConstruct() {
4243 return !!t;
4244 })();
4245 }
4246 __name(_isNativeReflectConstruct$9, "_isNativeReflectConstruct");
4247 var BaseError = /*#__PURE__*/ function(_Error) {
4248 /**
4249 * Error constructor.
4250 *
4251 * @param {string} message
4252 * @param {string} code
4253 * @param {*} data
4254 */
4255 function BaseError() {
4256 var _this;
4257 var message = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
4258 var code = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
4259 var data = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
4260 _classCallCheck(this, BaseError);
4261 _this = _callSuper$9(this, BaseError, [message]);
4262 /**
4263 * The server error code.
4264 *
4265 * @type {string}
4266 */
4267 _defineProperty(_this, "code", "");
4268 /**
4269 * Additional data about the current error.
4270 *
4271 * @type {*[]}
4272 */
4273 _defineProperty(_this, "data", []);
4274 _this.code = code;
4275 _this.data = data;
4276 return _this;
4277 }
4278 /**
4279 * Notify a message when the error occurs.
4280 */
4281 _inherits$1(BaseError, _Error);
4282 return _createClass(BaseError, [{
4283 key: "notify",
4284 value: function notify() {
4285 Console.error(_objectSpread$2({ message: this.message }, this));
4286 }
4287 }], [{
4288 key: "create",
4289 value: function create(message) {
4290 var code = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
4291 var data = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
4292 return new this(message, code, data);
4293 }
4294 }, {
4295 key: "getHTTPErrorCode",
4296 value: function getHTTPErrorCode() {
4297 force_method_implementation_default();
4298 }
4299 }]);
4300 }(/*#__PURE__*/ _wrapNativeSuper(Error));
4301
4302 //#endregion
4303 //#region modules/web-cli/assets/js/core/data/errors/default-error.js
4304 function _callSuper$8(t, o, e) {
4305 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$8() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4306 }
4307 __name(_callSuper$8, "_callSuper");
4308 function _isNativeReflectConstruct$8() {
4309 try {
4310 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4311 } catch (t) {}
4312 return (_isNativeReflectConstruct$8 = function _isNativeReflectConstruct() {
4313 return !!t;
4314 })();
4315 }
4316 __name(_isNativeReflectConstruct$8, "_isNativeReflectConstruct");
4317 var DefaultError = /*#__PURE__*/ function(_BaseError) {
4318 function DefaultError() {
4319 _classCallCheck(this, DefaultError);
4320 return _callSuper$8(this, DefaultError, arguments);
4321 }
4322 _inherits$1(DefaultError, _BaseError);
4323 return _createClass(DefaultError, null, [{
4324 key: "getHTTPErrorCode",
4325 value: function getHTTPErrorCode() {
4326 return 501;
4327 }
4328 }]);
4329 }(BaseError);
4330
4331 //#endregion
4332 //#region modules/web-cli/assets/js/core/data/errors/error-404.js
4333 function _callSuper$7(t, o, e) {
4334 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$7() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4335 }
4336 __name(_callSuper$7, "_callSuper");
4337 function _isNativeReflectConstruct$7() {
4338 try {
4339 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4340 } catch (t) {}
4341 return (_isNativeReflectConstruct$7 = function _isNativeReflectConstruct() {
4342 return !!t;
4343 })();
4344 }
4345 __name(_isNativeReflectConstruct$7, "_isNativeReflectConstruct");
4346 var Error404 = /*#__PURE__*/ function(_BaseError) {
4347 function Error404() {
4348 _classCallCheck(this, Error404);
4349 return _callSuper$7(this, Error404, arguments);
4350 }
4351 _inherits$1(Error404, _BaseError);
4352 return _createClass(Error404, [{
4353 key: "notify",
4354 value: function notify() {
4355 Console.warn(this.message);
4356 }
4357 }], [{
4358 key: "getHTTPErrorCode",
4359 value: function getHTTPErrorCode() {
4360 return 404;
4361 }
4362 }]);
4363 }(BaseError);
4364
4365 //#endregion
4366 //#region modules/web-cli/assets/js/core/data/errors/index.js
4367 var errors_exports = /* @__PURE__ */ __exportAll({
4368 DefaultError: () => DefaultError,
4369 Error404: () => Error404
4370 });
4371
4372 //#endregion
4373 //#region modules/web-cli/assets/js/modules/command-data.js
4374 init_defineProperty();
4375 function _callSuper$6(t, o, e) {
4376 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$6() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4377 }
4378 __name(_callSuper$6, "_callSuper");
4379 function _isNativeReflectConstruct$6() {
4380 try {
4381 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4382 } catch (t) {}
4383 return (_isNativeReflectConstruct$6 = function _isNativeReflectConstruct() {
4384 return !!t;
4385 })();
4386 }
4387 __name(_isNativeReflectConstruct$6, "_isNativeReflectConstruct");
4388 /**
4389 * @name $e.modules.CommandData
4390 */
4391 /**
4392 * @typedef {('create'|'delete'|'get'|'update'|'options')} DataTypes
4393 */
4394 /**
4395 * @typedef {{}} RequestData
4396 */
4397 /**
4398 * @typedef {import('../core/data/errors/base-error')} BaseError
4399 */
4400 var CommandData = /*#__PURE__*/ function(_CommandBase) {
4401 function CommandData(args) {
4402 var _this$args$options;
4403 var _this;
4404 var commandsAPI = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : $e.data;
4405 _classCallCheck(this, CommandData);
4406 _this = _callSuper$6(this, CommandData, [args, commandsAPI]);
4407 /**
4408 * Data returned from remote.
4409 *
4410 * @type {*}
4411 */
4412 _defineProperty(_this, "data", void 0);
4413 /**
4414 * Fetch type.
4415 *
4416 * @type {DataTypes}
4417 */
4418 _defineProperty(_this, "type", void 0);
4419 if ((_this$args$options = _this.args.options) !== null && _this$args$options !== void 0 && _this$args$options.type) _this.type = _this.args.options.type;
4420 return _this;
4421 }
4422 /**
4423 * Function getEndpointFormat().
4424 *
4425 * @return {null|string} endpoint format
4426 */
4427 _inherits$1(CommandData, _CommandBase);
4428 return _createClass(CommandData, [
4429 {
4430 key: "getApplyMethods",
4431 value: function getApplyMethods() {
4432 var type = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.type;
4433 var before;
4434 var after;
4435 switch (type) {
4436 case "create":
4437 before = this.applyBeforeCreate;
4438 after = this.applyAfterCreate;
4439 break;
4440 case "delete":
4441 before = this.applyBeforeDelete;
4442 after = this.applyAfterDelete;
4443 break;
4444 case "get":
4445 before = this.applyBeforeGet;
4446 after = this.applyAfterGet;
4447 break;
4448 case "update":
4449 before = this.applyBeforeUpdate;
4450 after = this.applyAfterUpdate;
4451 break;
4452 case "options":
4453 before = this.applyBeforeOptions;
4454 after = this.applyAfterOptions;
4455 break;
4456 default: return false;
4457 }
4458 return {
4459 before: before.bind(this),
4460 after: after.bind(this)
4461 };
4462 }
4463 },
4464 {
4465 key: "getRequestData",
4466 value: function getRequestData() {
4467 return {
4468 type: this.type,
4469 args: this.args,
4470 timestamp: (/* @__PURE__ */ new Date()).getTime(),
4471 component: this.component,
4472 command: this.command,
4473 endpoint: $e.data.commandToEndpoint(this.command, JSON.parse(JSON.stringify(this.args)), this.constructor.getEndpointFormat())
4474 };
4475 }
4476 },
4477 {
4478 key: "apply",
4479 value: function apply() {
4480 var _this2 = this;
4481 var applyMethods = this.getApplyMethods();
4482 this.args = applyMethods.before(this.args);
4483 var requestData = this.getRequestData();
4484 return $e.data.fetch(requestData).then(function(data) {
4485 _this2.data = data;
4486 _this2.data = applyMethods.after(data, _this2.args);
4487 _this2.data = { data: _this2.data };
4488 _this2.data = Object.assign({ __requestData__: requestData }, _this2.data);
4489 return _this2.data;
4490 });
4491 }
4492 },
4493 {
4494 key: "applyBeforeCreate",
4495 value: function applyBeforeCreate() {
4496 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4497 }
4498 },
4499 {
4500 key: "applyAfterCreate",
4501 value: function applyAfterCreate(data) {
4502 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4503 return data;
4504 }
4505 },
4506 {
4507 key: "applyBeforeDelete",
4508 value: function applyBeforeDelete() {
4509 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4510 }
4511 },
4512 {
4513 key: "applyAfterDelete",
4514 value: function applyAfterDelete(data) {
4515 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4516 return data;
4517 }
4518 },
4519 {
4520 key: "applyBeforeGet",
4521 value: function applyBeforeGet() {
4522 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4523 }
4524 },
4525 {
4526 key: "applyAfterGet",
4527 value: function applyAfterGet(data) {
4528 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4529 return data;
4530 }
4531 },
4532 {
4533 key: "applyBeforeUpdate",
4534 value: function applyBeforeUpdate() {
4535 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4536 }
4537 },
4538 {
4539 key: "applyAfterUpdate",
4540 value: function applyAfterUpdate(data) {
4541 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4542 return data;
4543 }
4544 },
4545 {
4546 key: "applyBeforeOptions",
4547 value: function applyBeforeOptions() {
4548 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4549 }
4550 },
4551 {
4552 key: "applyAfterOptions",
4553 value: function applyAfterOptions(data) {
4554 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4555 return data;
4556 }
4557 },
4558 {
4559 key: "applyAfterCatch",
4560 value: function applyAfterCatch(e) {
4561 e.notify();
4562 }
4563 },
4564 {
4565 key: "onCatchApply",
4566 value: function onCatchApply(e) {
4567 var _e;
4568 var httpErrorCode = ((_e = e) === null || _e === void 0 || (_e = _e.data) === null || _e === void 0 ? void 0 : _e.status) || 501;
4569 var dataError = Object.values(errors_exports).find(function(error) {
4570 return error.getHTTPErrorCode() === httpErrorCode;
4571 });
4572 if (!dataError) dataError = DefaultError;
4573 e = dataError.create(e.message, e.code, e.data || []);
4574 this.runCatchHooks(e);
4575 this.applyAfterCatch(e);
4576 }
4577 }
4578 ], [{
4579 key: "getInstanceType",
4580 value: function getInstanceType() {
4581 return "CommandData";
4582 }
4583 }, {
4584 key: "getEndpointFormat",
4585 value: function getEndpointFormat() {
4586 return null;
4587 }
4588 }]);
4589 }(CommandBase);
4590
4591 //#endregion
4592 //#region assets/dev/js/editor/utils/files-upload-handler.js
4593 var FilesUploadHandler = /*#__PURE__*/ function() {
4594 function FilesUploadHandler() {
4595 _classCallCheck(this, FilesUploadHandler);
4596 }
4597 return _createClass(FilesUploadHandler, null, [
4598 {
4599 key: "isUploadEnabled",
4600 value: function isUploadEnabled(mediaType) {
4601 if (!["svg", "application/json"].includes(mediaType)) return true;
4602 return elementorCommon.config.filesUpload.unfilteredFiles;
4603 }
4604 },
4605 {
4606 key: "setUploadTypeCaller",
4607 value: function setUploadTypeCaller(frame) {
4608 frame.uploader.uploader.param("uploadTypeCaller", "elementor-wp-media-upload");
4609 }
4610 },
4611 {
4612 key: "getUnfilteredFilesNonAdminDialog",
4613 value: function getUnfilteredFilesNonAdminDialog() {
4614 return elementorCommon.dialogsManager.createWidget("alert", {
4615 id: "e-unfiltered-files-disabled-dialog",
4616 headerMessage: (0, _wordpress_i18n.__)("Sorry, you can't upload that file yet", "elementor"),
4617 message: (0, _wordpress_i18n.__)("This is because JSON files may pose a security risk.", "elementor") + "<br><br>" + (0, _wordpress_i18n.__)("To upload them anyway, ask the site administrator to enable unfiltered file uploads.", "elementor"),
4618 strings: { confirm: (0, _wordpress_i18n.__)("Got it", "elementor") }
4619 });
4620 }
4621 },
4622 {
4623 key: "getUnfilteredFilesNotEnabledDialog",
4624 value: function getUnfilteredFilesNotEnabledDialog(callback) {
4625 var elementorInstance = window.elementorAdmin || window.elementor;
4626 if (!elementorInstance.config.user.is_administrator) return this.getUnfilteredFilesNonAdminDialog();
4627 return elementorInstance.helpers.getSimpleDialog("e-enable-unfiltered-files-dialog", (0, _wordpress_i18n.__)("Enable Unfiltered File Uploads", "elementor"), (0, _wordpress_i18n.__)("Before you enable unfiltered files upload, note that such files include a security risk. Elementor does run a process to remove possible malicious code, but there is still risk involved when using such files.", "elementor"), (0, _wordpress_i18n.__)("Enable", "elementor"), function onConfirm() {
4628 elementorCommon.ajax.addRequest("enable_unfiltered_files_upload", {}, true);
4629 elementorCommon.config.filesUpload.unfilteredFiles = true;
4630 callback();
4631 });
4632 }
4633 },
4634 {
4635 key: "getUnfilteredFilesNotEnabledImportTemplateDialog",
4636 value: function getUnfilteredFilesNotEnabledImportTemplateDialog(callback) {
4637 if (!(window.elementorAdmin || window.elementor).config.user.is_administrator) return this.getUnfilteredFilesNonAdminDialog();
4638 return elementorCommon.dialogsManager.createWidget("confirm", {
4639 id: "e-enable-unfiltered-files-dialog-import-template",
4640 headerMessage: (0, _wordpress_i18n.__)("Enable Unfiltered File Uploads", "elementor"),
4641 message: (0, _wordpress_i18n.__)("Before you enable unfiltered files upload, note that such files include a security risk. Elementor does run a process to remove possible malicious code, but there is still risk involved when using such files.", "elementor") + "<br /><br />" + (0, _wordpress_i18n.__)("If you do not enable uploading unfiltered files, any SVG or JSON (including lottie) files used in the uploaded template will not be imported.", "elementor"),
4642 position: {
4643 my: "center center",
4644 at: "center center"
4645 },
4646 strings: {
4647 confirm: (0, _wordpress_i18n.__)("Enable and Import", "elementor"),
4648 cancel: (0, _wordpress_i18n.__)("Import Without Enabling", "elementor")
4649 },
4650 onConfirm: function onConfirm() {
4651 elementorCommon.ajax.addRequest("enable_unfiltered_files_upload", { success: function success() {
4652 elementorCommon.config.filesUpload.unfilteredFiles = true;
4653 callback();
4654 } }, true);
4655 },
4656 onCancel: function onCancel() {
4657 return callback();
4658 }
4659 });
4660 }
4661 }
4662 ]);
4663 }();
4664
4665 //#endregion
4666 //#region core/common/assets/js/components/wordpress/commands-data/media.js
4667 function _callSuper$5(t, o, e) {
4668 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$5() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4669 }
4670 __name(_callSuper$5, "_callSuper");
4671 function _isNativeReflectConstruct$5() {
4672 try {
4673 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4674 } catch (t) {}
4675 return (_isNativeReflectConstruct$5 = function _isNativeReflectConstruct() {
4676 return !!t;
4677 })();
4678 }
4679 __name(_isNativeReflectConstruct$5, "_isNativeReflectConstruct");
4680 function _superPropGet$1(t, o, e, r) {
4681 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
4682 return 2 & r && "function" == typeof p ? function(t) {
4683 return p.apply(e, t);
4684 } : p;
4685 }
4686 __name(_superPropGet$1, "_superPropGet");
4687 var Media = /*#__PURE__*/ function(_CommandData) {
4688 function Media() {
4689 _classCallCheck(this, Media);
4690 return _callSuper$5(this, Media, arguments);
4691 }
4692 _inherits$1(Media, _CommandData);
4693 return _createClass(Media, [
4694 {
4695 key: "validateArgs",
4696 value: function validateArgs() {
4697 this.requireArgumentInstance("file", File);
4698 }
4699 },
4700 {
4701 key: "getRequestData",
4702 value: function getRequestData() {
4703 var requestData = _superPropGet$1(Media, "getRequestData", this, 3)([]);
4704 requestData.namespace = "wp";
4705 requestData.version = "2";
4706 return requestData;
4707 }
4708 },
4709 {
4710 key: "applyBeforeCreate",
4711 value: function applyBeforeCreate(args) {
4712 var _args$options;
4713 args.headers = {
4714 "Content-Disposition": "attachment; filename=".concat(this.file.name),
4715 "Content-Type": this.file.type
4716 };
4717 args.query = { uploadTypeCaller: "elementor-wp-media-upload" };
4718 args.data = this.file;
4719 if ((_args$options = args.options) !== null && _args$options !== void 0 && _args$options.progress) this.toast = elementor.notifications.showToast({
4720 message: (0, _wordpress_i18n.__)("Uploading..."),
4721 sticky: true
4722 });
4723 return args;
4724 }
4725 },
4726 {
4727 key: "applyAfterCreate",
4728 value: function applyAfterCreate(data, args) {
4729 var _args$options2;
4730 if ((_args$options2 = args.options) !== null && _args$options2 !== void 0 && _args$options2.progress) this.toast.hide();
4731 return data;
4732 }
4733 },
4734 {
4735 key: "run",
4736 value: function() {
4737 var _run = _asyncToGenerator(/*#__PURE__*/ import_regenerator.default.mark(function _callee() {
4738 return import_regenerator.default.wrap(function(_context) {
4739 while (1) switch (_context.prev = _context.next) {
4740 case 0:
4741 this.file = this.args.file;
4742 if (!(this.file.size > parseInt(window._wpPluploadSettings.defaults.filters.max_file_size, 10))) {
4743 _context.next = 1;
4744 break;
4745 }
4746 throw new Error((0, _wordpress_i18n.__)("The file exceeds the maximum upload size for this site.", "elementor"));
4747 case 1:
4748 if (!(!window._wpPluploadSettings.defaults.filters.mime_types[0].extensions.split(",").includes(this.file.name.split(".").pop()) && !elementor.config.filesUpload.unfilteredFiles)) {
4749 _context.next = 2;
4750 break;
4751 }
4752 FilesUploadHandler.getUnfilteredFilesNotEnabledDialog(function() {}).show();
4753 return _context.abrupt("return");
4754 case 2:
4755 _context.next = 3;
4756 return _superPropGet$1(Media, "run", this, 3)([]);
4757 case 3: return _context.abrupt("return", _context.sent);
4758 case 4:
4759 case "end": return _context.stop();
4760 }
4761 }, _callee, this);
4762 }));
4763 function run() {
4764 return _run.apply(this, arguments);
4765 }
4766 return run;
4767 }()
4768 }
4769 ], [{
4770 key: "getEndpointFormat",
4771 value: function getEndpointFormat() {
4772 return "media";
4773 }
4774 }]);
4775 }(CommandData);
4776
4777 //#endregion
4778 //#region core/common/assets/js/components/wordpress/commands-data/index.js
4779 var commands_data_exports$1 = /* @__PURE__ */ __exportAll({ Media: () => Media });
4780
4781 //#endregion
4782 //#region core/common/assets/js/components/wordpress/component.js
4783 function _callSuper$4(t, o, e) {
4784 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$4() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4785 }
4786 __name(_callSuper$4, "_callSuper");
4787 function _isNativeReflectConstruct$4() {
4788 try {
4789 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4790 } catch (t) {}
4791 return (_isNativeReflectConstruct$4 = function _isNativeReflectConstruct() {
4792 return !!t;
4793 })();
4794 }
4795 __name(_isNativeReflectConstruct$4, "_isNativeReflectConstruct");
4796 var Component$1 = /*#__PURE__*/ function(_ComponentBase) {
4797 function Component() {
4798 _classCallCheck(this, Component);
4799 return _callSuper$4(this, Component, arguments);
4800 }
4801 _inherits$1(Component, _ComponentBase);
4802 return _createClass(Component, [{
4803 key: "getNamespace",
4804 value: function getNamespace() {
4805 return "wp";
4806 }
4807 }, {
4808 key: "defaultData",
4809 value: function defaultData() {
4810 return this.importCommands(commands_data_exports$1);
4811 }
4812 }]);
4813 }(ComponentBase);
4814
4815 //#endregion
4816 //#region core/common/modules/event-tracker/assets/js/data/commands-data/index.js
4817 var commands_data_exports = /* @__PURE__ */ __exportAll({ Index: () => Index });
4818 function _callSuper$3(t, o, e) {
4819 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$3() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4820 }
4821 __name(_callSuper$3, "_callSuper");
4822 function _isNativeReflectConstruct$3() {
4823 try {
4824 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4825 } catch (t) {}
4826 return (_isNativeReflectConstruct$3 = function _isNativeReflectConstruct() {
4827 return !!t;
4828 })();
4829 }
4830 __name(_isNativeReflectConstruct$3, "_isNativeReflectConstruct");
4831 var Index = /*#__PURE__*/ function(_CommandData) {
4832 function Index() {
4833 _classCallCheck(this, Index);
4834 return _callSuper$3(this, Index, arguments);
4835 }
4836 _inherits$1(Index, _CommandData);
4837 return _createClass(Index, null, [{
4838 key: "getEndpointFormat",
4839 value: function getEndpointFormat() {
4840 return "send-event";
4841 }
4842 }]);
4843 }(CommandData);
4844
4845 //#endregion
4846 //#region core/common/modules/event-tracker/assets/js/data/component.js
4847 function _callSuper$2(t, o, e) {
4848 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$2() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4849 }
4850 __name(_callSuper$2, "_callSuper");
4851 function _isNativeReflectConstruct$2() {
4852 try {
4853 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4854 } catch (t) {}
4855 return (_isNativeReflectConstruct$2 = function _isNativeReflectConstruct() {
4856 return !!t;
4857 })();
4858 }
4859 __name(_isNativeReflectConstruct$2, "_isNativeReflectConstruct");
4860 var Component = /*#__PURE__*/ function(_ComponentBase) {
4861 function Component() {
4862 _classCallCheck(this, Component);
4863 return _callSuper$2(this, Component, arguments);
4864 }
4865 _inherits$1(Component, _ComponentBase);
4866 return _createClass(Component, [{
4867 key: "getNamespace",
4868 value: function getNamespace() {
4869 return "event-tracker";
4870 }
4871 }, {
4872 key: "defaultData",
4873 value: function defaultData() {
4874 return this.importCommands(commands_data_exports);
4875 }
4876 }]);
4877 }(ComponentBase);
4878
4879 //#endregion
4880 //#region assets/dev/js/utils/time.js
4881 /**
4882 * Returns the timestamp in ISO8601 format with the UTC timezone offset.
4883 *
4884 * @since 3.6.0
4885 *
4886 * @param {Date} date
4887 * @return {Date} timestamp
4888 */
4889 function getUserTimestamp() {
4890 var date = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : /* @__PURE__ */ new Date();
4891 var timezoneOffset = date.getTimezoneOffset();
4892 var UTCTimestamp = (/* @__PURE__ */ new Date(date.getTime() - timezoneOffset * 6e4)).toISOString();
4893 UTCTimestamp = UTCTimestamp.slice(0, -1);
4894 var decimalTimezoneOffset = timezoneOffset / 60;
4895 var sign = 0 <= decimalTimezoneOffset ? "+" : "-";
4896 var hours = Math.abs(Math.floor(decimalTimezoneOffset));
4897 var minutes = Math.abs(decimalTimezoneOffset % 1) * 60;
4898 var addZeroToHour = 10 > hours ? "0" : "";
4899 var addZeroToMinutes = 10 > minutes ? "0" : "";
4900 var formattedTimezoneOffset = sign + addZeroToHour + hours + ":" + addZeroToMinutes + minutes;
4901 return UTCTimestamp + formattedTimezoneOffset;
4902 }
4903
4904 //#endregion
4905 //#region core/common/modules/event-tracker/assets/js/events.js
4906 var Events = /*#__PURE__*/ function() {
4907 function Events() {
4908 _classCallCheck(this, Events);
4909 }
4910 return _createClass(Events, [{
4911 key: "dispatchEvent",
4912 value: function dispatchEvent(eventData) {
4913 if (!eventData) return;
4914 eventData.ts = getUserTimestamp();
4915 $e.data.create("event-tracker/index", { event_data: eventData });
4916 }
4917 }]);
4918 }();
4919
4920 //#endregion
4921 //#region core/common/modules/events-manager/assets/js/events-config.js
4922 var eventsConfig = {
4923 appTypes: {
4924 editor: "editor",
4925 wpAdmin: "wpadmin",
4926 wpDash: "wpdash"
4927 },
4928 windowNames: { sidebarMenu: "sidebar_menu" },
4929 targetTypes: {
4930 dropdownItem: "dropdown_item",
4931 button: "button",
4932 tab: "tab",
4933 toggle: "toggle",
4934 searchInput: "search_input",
4935 searchResult: "search_result",
4936 buttons: "buttons",
4937 searchWidget: "search_widget",
4938 wpDashAdminMenuItem: "wpdash_admin_menu_item",
4939 wpDashEditorMenu: "wpdash_editor_menu",
4940 wpDashSubMenuItem: "wpdash_sub_menu_item",
4941 link: "link"
4942 },
4943 interactionResults: {
4944 actionSelected: "action_selected",
4945 navigate: "navigate",
4946 create: "create",
4947 sessionEnd: "session_end",
4948 tabChanged: "tab_changed",
4949 assetInserted: "asset_inserted",
4950 assetFavorite: "asset_favorite",
4951 aiGenerate: "ai_generate",
4952 resultsUpdated: "results_updated",
4953 noResults: "no_results",
4954 selected: "selected",
4955 promotionViewed: "promotion_viewed",
4956 upgradeNow: "upgrade_now",
4957 elementorSideMenuOpened: "elementor_side_menu_opened",
4958 editorSubMenuOpened: "wpdash_editor_sub_menu_opened",
4959 themeBuilderPromotionWindow: "theme_builder_promotion_window",
4960 pageOpened: "page_opened",
4961 expanded: "expanded",
4962 collapsed: "collapsed"
4963 },
4964 targetNames: {
4965 publishDropdown: {
4966 saveDraft: "save_draft",
4967 saveAsTemplate: "save_as_template",
4968 viewPage: "view_page",
4969 copyAndShare: "copy_and_share"
4970 },
4971 pageList: { addNewPage: "add_new_page" }
4972 },
4973 triggers: {
4974 click: "Click",
4975 rightClick: "Right Click",
4976 doubleClick: "Double Click",
4977 accordionClick: "Accordion Click",
4978 toggleClick: "Toggle Click",
4979 dropdownClick: "Click Dropdown",
4980 editorLoaded: "Editor Loaded",
4981 visible: "Visible",
4982 pageLoaded: "Page Loaded",
4983 typing: "Typing",
4984 tabSelect: "Tab Select",
4985 insert: "Insert",
4986 hover: "Hover"
4987 },
4988 locations: {
4989 widgetPanel: "Widget Panel",
4990 topBar: "Top Bar",
4991 sidebar: "Sidebar",
4992 elementorEditor: "Elementor Editor",
4993 templatesLibrary: { library: "Templates Library" },
4994 app: {
4995 import: "Import Kit",
4996 export: "Export Kit",
4997 kitLibrary: "Kit Library",
4998 cloudKitLibrary: "Cloud Kit Library"
4999 },
5000 variables: "Variables Panel",
5001 variablesManager: "Variables Manager",
5002 admin: "WP admin",
5003 wpDashAdmin: "wpdash_admin",
5004 structurePanel: "Structure Panel",
5005 canvas: "Canvas",
5006 leftPanel: "Left Panel",
5007 elementorLibrary: "Elementor Library",
5008 components: { instanceEditingPanel: "Instance Editing Panel" }
5009 },
5010 secondaryLocations: {
5011 layout: "Layout Section",
5012 basic: "Basic Section",
5013 "pro-elements": "Pro Section",
5014 general: "General Section",
5015 "theme-elements": "Site Section",
5016 "theme-elements-single": "Single Section",
5017 "woocommerce-elements": "WooCommerce Section",
5018 wordpress: "WordPress Section",
5019 categories: "Widgets Tab",
5020 global: "Globals Tab",
5021 "whats-new": "What's New",
5022 "document-settings": "Document Settings icon",
5023 "preview-page": "Preview Page",
5024 "publish-button": "Publish Button",
5025 "widget-panel": "Widget Panel Icon",
5026 finder: "Finder",
5027 help: "Help",
5028 elementorLogoDropdown: "top_bar_elementor_logo_dropdown",
5029 elementorLogo: "Elementor Logo",
5030 eLogoMenu: "E-logo Menu",
5031 notes: "Notes",
5032 siteSettings: "Site Settings",
5033 structure: "Structure",
5034 documentNameDropdown: "Document Name dropdown",
5035 responsiveControls: "Responsive controls",
5036 launchpad: "launchpad",
5037 checklistHeader: "Checklist Header",
5038 checklistSteps: "Checklist Steps",
5039 userPreferences: "User Preferences",
5040 contextMenu: "Context Menu",
5041 templateLibrary: {
5042 saveModal: "Save to Modal",
5043 moveModal: "Move to Modal",
5044 bulkMoveModal: "Bulk Move to Modal",
5045 copyModal: "Copy to Modal",
5046 bulkCopyModal: "Bulk Copy to Modal",
5047 saveModalSelectFolder: "Save to Modal - select folder",
5048 saveModalSelectConnect: "Save to Modal - connect",
5049 saveModalSelectUpgrade: "Save to Modal - upgrade",
5050 importModal: "Import Modal",
5051 newFolderModal: "New Folder Modal",
5052 deleteDialog: "Delete Dialog",
5053 deleteFolderDialog: "Delete Folder Dialog",
5054 renameDialog: "Rename Dialog",
5055 createFolderDialog: "Create Folder Dialog",
5056 applySettingsDialog: "Apply Settings Dialog",
5057 cloudTab: "Cloud Tab",
5058 siteTab: "Site Tab",
5059 cloudTabFolder: "Cloud Tab - Folder",
5060 cloudTabConnect: "Cloud Tab - Connect",
5061 cloudTabUpgrade: "Cloud Tab - Upgrade",
5062 morePopup: "Context Menu",
5063 quotaBar: "Quota Bar"
5064 },
5065 kitLibrary: {
5066 cloudKitLibrary: "kits_cloud_library",
5067 cloudKitLibraryConnect: "kits_cloud_library_connect",
5068 cloudKitLibraryUpgrade: "kits_cloud_library_upgrade",
5069 kitExportCustomization: "kit_export_customization",
5070 kitExport: "kit_export",
5071 kitExportCustomizationEdit: "kit_export_customization_edit",
5072 kitExportSummary: "kit_export_summary",
5073 kitImportUploadBox: "kit_import_upload_box",
5074 kitImportCustomization: "kit_import_customization",
5075 kitImportSummary: "kit_import_summary"
5076 },
5077 variablesPopover: "Variables Popover",
5078 admin: {
5079 pluginToolsTab: "plugin_tools_tab",
5080 pluginWebsiteTemplatesTab: "plugin_website_templates_tab"
5081 },
5082 componentsTab: "Components Tab",
5083 canvasElement: "Canvas Element",
5084 publishDropdown: "Publish Dropdown",
5085 pageListDropdown: "Page List Dropdown",
5086 emptyBox: "Empty Box",
5087 searchBar: "Search Bar",
5088 finderResults: "Finder Results",
5089 libraryTabs: "Library Tabs",
5090 assetCard: "Asset Card",
5091 wpDashElementorCoreMenu: "elementor_editor_core_menu",
5092 wpDashElementorCoreSubMenu: "elementor_editor_core_sub_menu",
5093 wpDashThemeBuilder: "wpdash_core_sub_menu_theme_builder"
5094 },
5095 elements: {
5096 accordionSection: "Accordion section",
5097 buttonIcon: "Button Icon",
5098 mainCta: "Main CTA",
5099 button: "Button",
5100 link: "Link",
5101 dropdown: "Dropdown",
5102 toggle: "Toggle",
5103 launchpadChecklist: "Checklist popup"
5104 },
5105 names: {
5106 v1: {
5107 layout: "v1_widgets_tab_layout_section",
5108 basic: "v1_widgets_tab_basic_section",
5109 "pro-elements": "v1_widgets_tab_pro_section",
5110 general: "v1_widgets_tab_general_section",
5111 "theme-elements": "v1_widgets_tab_site_section",
5112 "theme-elements-single": "v1_widgets_tab_single_section",
5113 "woocommerce-elements": "v1_widgets_tab_woocommerce_section",
5114 wordpress: "v1_widgets_tab_wordpress_section",
5115 categories: "v1_widgets_tab",
5116 global: "v1_globals_tab"
5117 },
5118 topBar: {
5119 whatsNew: "top_bar_whats_new",
5120 documentSettings: "top_bar_document_settings_icon",
5121 previewPage: "top_bar_preview_page",
5122 publishButton: "top_bar_publish_button",
5123 widgetPanel: "top_bar_widget_panel_icon",
5124 finder: "top_bar_finder",
5125 help: "top_bar_help",
5126 history: "top_bar_elementor_logo_dropdown_history",
5127 userPreferences: "top_bar_elementor_logo_dropdown_user_preferences",
5128 keyboardShortcuts: "top_bar_elementor_logo_dropdown_keyboard_shortcuts",
5129 exitToWordpress: "top_bar_elementor_logo_dropdown_exit_to_wordpress",
5130 themeBuilder: "top_bar_elementor_logo_dropdown_theme_builder",
5131 notes: "top_bar_notes",
5132 siteSettings: "top_bar_site_setting",
5133 structure: "top_bar_structure",
5134 documentNameDropdown: "top_bar_document_name_dropdown",
5135 responsiveControls: "top_bar_responsive_controls",
5136 launchpadOn: "top_bar_checklist_icon_show",
5137 launchpadOff: "top_bar_checklist_icon_hide",
5138 elementorLogoDropdown: "open_e_menu",
5139 connectAccount: "connect_account",
5140 accountConnected: "account_connected"
5141 },
5142 elementorEditor: {
5143 editorLoaded: "editor_loaded",
5144 checklist: {
5145 checklistHeaderClose: "checklist_header_close_icon",
5146 checklistFirstPopup: "checklist popup triggered"
5147 },
5148 userPreferences: {
5149 checklistShow: "checklist_userpreferences_toggle_show",
5150 checklistHide: "checklist_userpreferences_toggle_hide"
5151 }
5152 },
5153 variables: {
5154 open: "open_variables_popover",
5155 add: "add_new_variable",
5156 connect: "connect_variable",
5157 save: "save_new_variable",
5158 update: "update_variable",
5159 openManager: "open_variables_manager",
5160 saveChanges: "save_variables_changes",
5161 delete: "delete_variable",
5162 variableSyncToV3: "variable_sync_to_v3"
5163 },
5164 design_system: {
5165 importOpened: "design_system_import_opened",
5166 fileSelected: "design_system_file_selected",
5167 validationFailed: "design_system_validation_failed",
5168 conflictChoice: "design_system_conflict_choice",
5169 confirmed: "design_system_import_confirmed",
5170 imported: "design_system_imported",
5171 importFailed: "design_system_import_failed",
5172 export: "design_system_export",
5173 opened: "design_system_opened"
5174 },
5175 components: {
5176 createClicked: "component_create_clicked",
5177 createCancelled: "component_creation_cancelled",
5178 created: "component_created",
5179 instanceAdded: "component_instance_added",
5180 edited: "component_edited",
5181 propertiesPanelOpened: "component_properties_panel_opened",
5182 propertiesGroupCreated: "component_properties_group_created",
5183 propertyExposed: "component_property_exposed",
5184 propertyRemoved: "component_property_removed",
5185 detached: "component_detached"
5186 },
5187 global_classes: {
5188 classApplied: "class_applied",
5189 classRemoved: "class_removed",
5190 classManagerFilterCleared: "class_manager_filter_cleared",
5191 classDeleted: "class_deleted",
5192 classPublishConflict: "class_publish_conflict",
5193 classRenamed: "class_renamed",
5194 classCreated: "class_created",
5195 classManagerSearched: "class_manager_searched",
5196 classManagerFiltersOpened: "class_manager_filters_opened",
5197 classManagerOpened: "class_manager_opened",
5198 classManagerReorder: "class_manager_reorder",
5199 classManagerFilterUsed: "class_manager_filter_used",
5200 classUsageLocate: "class_usage_locate",
5201 classUsageHovered: "class_usage_hovered",
5202 classStyled: "class_styled",
5203 classStateClicked: "class_state_clicked",
5204 classUsageClicked: "class_usage_clicked",
5205 classDuplicate: "class_duplicate",
5206 classSyncToV3PopupShown: "class_sync_to_v3_popup_shown",
5207 classSyncToV3: "class_sync_to_v3",
5208 classSyncToV3PopupClick: "class_sync_to_v3_popup_click"
5209 },
5210 editorOne: {
5211 topBarPublishDropdown: "top_bar_publish_dropdown",
5212 topBarPageList: "top_bar_page_list",
5213 siteSettingsSession: "site_settings_session",
5214 eLibraryNav: "e_library_nav",
5215 eLibraryInsert: "e_library_insert",
5216 eLibraryFavorite: "e_library_favorite",
5217 eLibraryGenerateAi: "e_library_generate_ai",
5218 finderSearchInput: "finder_search_input",
5219 finderResultSelect: "finder_result_select",
5220 canvasEmptyBoxAction: "canvas_empty_box_action",
5221 widgetPanelSearch: "widget_panel_search",
5222 wpDashElementorMenuClick: "wpdash_elementor_menu_click",
5223 wpDashEditorSubMenuHover: "wpdash_editor_sub_menu_hover",
5224 wpDashThemeBuilderClick: "wpdash_theme_builder_click",
5225 sidebarMenuItemClicked: "sidebar_menu_item_clicked",
5226 sidebarMenuGroupToggled: "sidebar_menu_group_toggled"
5227 },
5228 interactions: { created: "interactions_created" },
5229 promotions: {
5230 viewPromotion: "view_promotion",
5231 upgradePromotionClick: "upgrade_promotion_click"
5232 }
5233 }
5234 };
5235
5236 //#endregion
5237 //#region core/common/modules/events-manager/assets/js/install-events-proxy-fetch.js
5238 init_defineProperty();
5239 function ownKeys$1(e, r) {
5240 var t = Object.keys(e);
5241 if (Object.getOwnPropertySymbols) {
5242 var o = Object.getOwnPropertySymbols(e);
5243 r && (o = o.filter(function(r) {
5244 return Object.getOwnPropertyDescriptor(e, r).enumerable;
5245 })), t.push.apply(t, o);
5246 }
5247 return t;
5248 }
5249 __name(ownKeys$1, "ownKeys");
5250 function _objectSpread$1(e) {
5251 for (var r = 1; r < arguments.length; r++) {
5252 var t = null != arguments[r] ? arguments[r] : {};
5253 r % 2 ? ownKeys$1(Object(t), !0).forEach(function(r) {
5254 _defineProperty(e, r, t[r]);
5255 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function(r) {
5256 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
5257 });
5258 }
5259 return e;
5260 }
5261 __name(_objectSpread$1, "_objectSpread");
5262 var INSTALLED_FLAG = "__elementorEventsProxyFetchInstalled";
5263 function buildMixpanelAuthorization(token) {
5264 return "Basic ".concat(btoa("".concat(token, ":")));
5265 }
5266 function isProxyRequestUrl(url, proxyPrefixes) {
5267 return proxyPrefixes.some(function(prefix) {
5268 return url.startsWith(prefix);
5269 });
5270 }
5271 function isFetchRequest(input) {
5272 return "function" === typeof Request && input instanceof Request;
5273 }
5274 function mergeFetchHeaders(input, init) {
5275 var headers = new Headers();
5276 if (isFetchRequest(input)) input.headers.forEach(function(value, key) {
5277 headers.set(key, value);
5278 });
5279 if (init !== null && init !== void 0 && init.headers) new Headers(init.headers).forEach(function(value, key) {
5280 headers.set(key, value);
5281 });
5282 return headers;
5283 }
5284 function stripMixpanelAuthorization(input, init, token) {
5285 var _init$credentials;
5286 if (!token) return {
5287 input,
5288 init,
5289 stripped: false
5290 };
5291 var headers = mergeFetchHeaders(input, init);
5292 var mixpanelAuthorization = buildMixpanelAuthorization(token);
5293 if (headers.get("Authorization") !== mixpanelAuthorization) return {
5294 input,
5295 init,
5296 stripped: false
5297 };
5298 headers.delete("Authorization");
5299 var credentials = (_init$credentials = init.credentials) !== null && _init$credentials !== void 0 ? _init$credentials : "include";
5300 if (isFetchRequest(input)) return {
5301 input: new Request(input, {
5302 headers,
5303 credentials
5304 }),
5305 init: void 0,
5306 stripped: true
5307 };
5308 return {
5309 input,
5310 init: _objectSpread$1(_objectSpread$1({}, init), {}, {
5311 credentials,
5312 headers
5313 }),
5314 stripped: true
5315 };
5316 }
5317 function installEventsProxyFetch(proxyApiHost, proxyLibBasePath, token) {
5318 if (!proxyApiHost || !token || window[INSTALLED_FLAG] || "function" !== typeof window.fetch) return;
5319 var proxyPrefixes = [proxyApiHost, proxyLibBasePath].filter(Boolean);
5320 var nativeFetch = window.fetch.bind(window);
5321 window.fetch = function(input) {
5322 var init = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
5323 var url = "string" === typeof input ? input : input === null || input === void 0 ? void 0 : input.url;
5324 if (!url || !isProxyRequestUrl(url, proxyPrefixes)) return nativeFetch(input, init);
5325 var _stripMixpanelAuthori = stripMixpanelAuthorization(input, init, token);
5326 var nextInput = _stripMixpanelAuthori.input;
5327 var nextInit = _stripMixpanelAuthori.init;
5328 if (void 0 === nextInit) return nativeFetch(nextInput);
5329 return nativeFetch(nextInput, nextInit);
5330 };
5331 window[INSTALLED_FLAG] = true;
5332 }
5333
5334 //#endregion
5335 //#region node_modules/mixpanel-browser/dist/mixpanel.module.js
5336 var win;
5337 if (typeof window === "undefined") {
5338 var loc = { hostname: "" };
5339 win = {
5340 crypto: { randomUUID: function() {
5341 throw Error("unsupported");
5342 } },
5343 navigator: {
5344 userAgent: "",
5345 onLine: true
5346 },
5347 document: {
5348 createElement: function() {
5349 return {};
5350 },
5351 location: loc,
5352 referrer: ""
5353 },
5354 screen: {
5355 width: 0,
5356 height: 0
5357 },
5358 location: loc,
5359 addEventListener: function() {},
5360 removeEventListener: function() {}
5361 };
5362 } else win = window;
5363 function _array_like_to_array(arr, len) {
5364 if (len == null || len > arr.length) len = arr.length;
5365 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
5366 return arr2;
5367 }
5368 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
5369 try {
5370 var info = gen[key](arg);
5371 var value = info.value;
5372 } catch (error) {
5373 reject(error);
5374 return;
5375 }
5376 if (info.done) resolve(value);
5377 else Promise.resolve(value).then(_next, _throw);
5378 }
5379 function _async_to_generator(fn) {
5380 return function() {
5381 var self = this;
5382 var args = arguments;
5383 return new Promise(function(resolve, reject) {
5384 var gen = fn.apply(self, args);
5385 function _next(value) {
5386 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
5387 }
5388 function _throw(err) {
5389 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
5390 }
5391 _next(void 0);
5392 });
5393 };
5394 }
5395 function _construct(Parent, args, Class) {
5396 if (_is_native_reflect_construct()) _construct = Reflect.construct;
5397 else _construct = function construct(Parent, args, Class) {
5398 var a = [null];
5399 a.push.apply(a, args);
5400 var instance = new (Function.bind.apply(Parent, a))();
5401 if (Class) _set_prototype_of(instance, Class.prototype);
5402 return instance;
5403 };
5404 return _construct.apply(null, arguments);
5405 }
5406 function _defineProperties(target, props) {
5407 for (var i = 0; i < props.length; i++) {
5408 var descriptor = props[i];
5409 descriptor.enumerable = descriptor.enumerable || false;
5410 descriptor.configurable = true;
5411 if ("value" in descriptor) descriptor.writable = true;
5412 Object.defineProperty(target, descriptor.key, descriptor);
5413 }
5414 }
5415 function _create_class(Constructor, protoProps, staticProps) {
5416 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
5417 return Constructor;
5418 }
5419 function _extends() {
5420 _extends = Object.assign || function(target) {
5421 for (var i = 1; i < arguments.length; i++) {
5422 var source = arguments[i];
5423 for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
5424 }
5425 return target;
5426 };
5427 return _extends.apply(this, arguments);
5428 }
5429 function _get_prototype_of(o) {
5430 _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
5431 return o.__proto__ || Object.getPrototypeOf(o);
5432 };
5433 return _get_prototype_of(o);
5434 }
5435 function _inherits(subClass, superClass) {
5436 if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
5437 subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
5438 value: subClass,
5439 writable: true,
5440 configurable: true
5441 } });
5442 if (superClass) _set_prototype_of(subClass, superClass);
5443 }
5444 function _instanceof(left, right) {
5445 if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) return !!right[Symbol.hasInstance](left);
5446 else return left instanceof right;
5447 }
5448 function _is_native_function(fn) {
5449 return Function.toString.call(fn).indexOf("[native code]") !== -1;
5450 }
5451 function _object_without_properties_loose(source, excluded) {
5452 if (source == null) return {};
5453 var target = {};
5454 var sourceKeys = Object.keys(source);
5455 var key;
5456 var i;
5457 for (i = 0; i < sourceKeys.length; i++) {
5458 key = sourceKeys[i];
5459 if (excluded.indexOf(key) >= 0) continue;
5460 target[key] = source[key];
5461 }
5462 return target;
5463 }
5464 function _set_prototype_of(o, p) {
5465 _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
5466 o.__proto__ = p;
5467 return o;
5468 };
5469 return _set_prototype_of(o, p);
5470 }
5471 function _type_of(obj) {
5472 "@swc/helpers - typeof";
5473 return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
5474 }
5475 function _unsupported_iterable_to_array(o, minLen) {
5476 if (!o) return;
5477 if (typeof o === "string") return _array_like_to_array(o, minLen);
5478 var n = Object.prototype.toString.call(o).slice(8, -1);
5479 if (n === "Object" && o.constructor) n = o.constructor.name;
5480 if (n === "Map" || n === "Set") return Array.from(n);
5481 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
5482 }
5483 function _wrap_native_super(Class) {
5484 var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0;
5485 _wrap_native_super = function wrapNativeSuper(Class) {
5486 if (Class === null || !_is_native_function(Class)) return Class;
5487 if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
5488 if (typeof _cache !== "undefined") {
5489 if (_cache.has(Class)) return _cache.get(Class);
5490 _cache.set(Class, Wrapper);
5491 }
5492 function Wrapper() {
5493 return _construct(Class, arguments, _get_prototype_of(this).constructor);
5494 }
5495 Wrapper.prototype = Object.create(Class.prototype, { constructor: {
5496 value: Wrapper,
5497 enumerable: false,
5498 writable: true,
5499 configurable: true
5500 } });
5501 return _set_prototype_of(Wrapper, Class);
5502 };
5503 return _wrap_native_super(Class);
5504 }
5505 function _is_native_reflect_construct() {
5506 try {
5507 var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
5508 } catch (_) {}
5509 return (_is_native_reflect_construct = function() {
5510 return !!result;
5511 })();
5512 }
5513 function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
5514 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
5515 if (it) return (it = it.call(o)).next.bind(it);
5516 if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike) {
5517 if (it) o = it;
5518 var i = 0;
5519 return function() {
5520 if (i >= o.length) return { done: true };
5521 return {
5522 done: false,
5523 value: o[i++]
5524 };
5525 };
5526 }
5527 throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
5528 }
5529 function _ts_generator(thisArg, body) {
5530 var f;
5531 var y;
5532 var t;
5533 var g;
5534 var _ = {
5535 label: 0,
5536 sent: function() {
5537 if (t[0] & 1) throw t[1];
5538 return t[1];
5539 },
5540 trys: [],
5541 ops: []
5542 };
5543 return g = {
5544 next: verb(0),
5545 "throw": verb(1),
5546 "return": verb(2)
5547 }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
5548 return this;
5549 }), g;
5550 function verb(n) {
5551 return function(v) {
5552 return step([n, v]);
5553 };
5554 }
5555 function step(op) {
5556 if (f) throw new TypeError("Generator is already executing.");
5557 while (_) try {
5558 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
5559 if (y = 0, t) op = [op[0] & 2, t.value];
5560 switch (op[0]) {
5561 case 0:
5562 case 1:
5563 t = op;
5564 break;
5565 case 4:
5566 _.label++;
5567 return {
5568 value: op[1],
5569 done: false
5570 };
5571 case 5:
5572 _.label++;
5573 y = op[1];
5574 op = [0];
5575 continue;
5576 case 7:
5577 op = _.ops.pop();
5578 _.trys.pop();
5579 continue;
5580 default:
5581 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
5582 _ = 0;
5583 continue;
5584 }
5585 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
5586 _.label = op[1];
5587 break;
5588 }
5589 if (op[0] === 6 && _.label < t[1]) {
5590 _.label = t[1];
5591 t = op;
5592 break;
5593 }
5594 if (t && _.label < t[2]) {
5595 _.label = t[2];
5596 _.ops.push(op);
5597 break;
5598 }
5599 if (t[2]) _.ops.pop();
5600 _.trys.pop();
5601 continue;
5602 }
5603 op = body.call(thisArg, _);
5604 } catch (e) {
5605 op = [6, e];
5606 y = 0;
5607 } finally {
5608 f = t = 0;
5609 }
5610 if (op[0] & 5) throw op[1];
5611 return {
5612 value: op[0] ? op[1] : void 0,
5613 done: true
5614 };
5615 }
5616 }
5617 function _ts_values(o) {
5618 var s = typeof Symbol === "function" && Symbol.iterator;
5619 var m = s && o[s];
5620 var i = 0;
5621 if (m) return m.call(o);
5622 if (o && typeof o.length === "number") return { next: function() {
5623 if (o && i >= o.length) o = void 0;
5624 return {
5625 value: o && o[i++],
5626 done: !o
5627 };
5628 } };
5629 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
5630 }
5631 var __defProp = Object.defineProperty;
5632 var __defNormalProp = function(obj, key, value) {
5633 return key in obj ? __defProp(obj, key, {
5634 enumerable: true,
5635 configurable: true,
5636 writable: true,
5637 value
5638 }) : obj[key] = value;
5639 };
5640 var __publicField = function(obj, key, value) {
5641 return __defNormalProp(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
5642 };
5643 var _a;
5644 var __defProp$1 = Object.defineProperty;
5645 var __defNormalProp$1 = function(obj, key, value) {
5646 return key in obj ? __defProp$1(obj, key, {
5647 enumerable: true,
5648 configurable: true,
5649 writable: true,
5650 value
5651 }) : obj[key] = value;
5652 };
5653 var __publicField$1 = function(obj, key, value) {
5654 return __defNormalProp$1(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
5655 };
5656 var NodeType$3 = /* @__PURE__ */ function(NodeType2) {
5657 NodeType2[NodeType2["Document"] = 0] = "Document";
5658 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
5659 NodeType2[NodeType2["Element"] = 2] = "Element";
5660 NodeType2[NodeType2["Text"] = 3] = "Text";
5661 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
5662 NodeType2[NodeType2["Comment"] = 5] = "Comment";
5663 return NodeType2;
5664 }(NodeType$3 || {});
5665 var testableAccessors$1 = {
5666 Node: [
5667 "childNodes",
5668 "parentNode",
5669 "parentElement",
5670 "textContent"
5671 ],
5672 ShadowRoot: ["host", "styleSheets"],
5673 Element: [
5674 "shadowRoot",
5675 "querySelector",
5676 "querySelectorAll"
5677 ],
5678 MutationObserver: []
5679 };
5680 var testableMethods$1 = {
5681 Node: ["contains", "getRootNode"],
5682 ShadowRoot: ["getSelection"],
5683 Element: [],
5684 MutationObserver: ["constructor"]
5685 };
5686 var untaintedBasePrototype$1 = {};
5687 var isAngularZonePresent$1 = function() {
5688 return !!globalThis.Zone;
5689 };
5690 function getUntaintedPrototype$1(key) {
5691 if (untaintedBasePrototype$1[key]) return untaintedBasePrototype$1[key];
5692 var defaultObj = globalThis[key];
5693 var defaultPrototype = defaultObj.prototype;
5694 var accessorNames = key in testableAccessors$1 ? testableAccessors$1[key] : void 0;
5695 var isUntaintedAccessors = Boolean(accessorNames && accessorNames.every(function(accessor) {
5696 var _a2;
5697 var _b;
5698 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
5699 }));
5700 var methodNames = key in testableMethods$1 ? testableMethods$1[key] : void 0;
5701 var isUntaintedMethods = Boolean(methodNames && methodNames.every(function(method) {
5702 var _a2;
5703 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
5704 }));
5705 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent$1()) {
5706 untaintedBasePrototype$1[key] = defaultObj.prototype;
5707 return defaultObj.prototype;
5708 }
5709 try {
5710 var iframeEl = document.createElement("iframe");
5711 document.body.appendChild(iframeEl);
5712 var win = iframeEl.contentWindow;
5713 if (!win) return defaultObj.prototype;
5714 var untaintedObject = win[key].prototype;
5715 document.body.removeChild(iframeEl);
5716 if (!untaintedObject) return defaultPrototype;
5717 return untaintedBasePrototype$1[key] = untaintedObject;
5718 } catch (e) {
5719 return defaultPrototype;
5720 }
5721 }
5722 var untaintedAccessorCache$1 = {};
5723 function getUntaintedAccessor$1(key, instance, accessor) {
5724 var _a2;
5725 var cacheKey = key + "." + String(accessor);
5726 if (untaintedAccessorCache$1[cacheKey]) return untaintedAccessorCache$1[cacheKey].call(instance);
5727 var untaintedPrototype = getUntaintedPrototype$1(key);
5728 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
5729 if (!untaintedAccessor) return instance[accessor];
5730 untaintedAccessorCache$1[cacheKey] = untaintedAccessor;
5731 return untaintedAccessor.call(instance);
5732 }
5733 var untaintedMethodCache$1 = {};
5734 function getUntaintedMethod$1(key, instance, method) {
5735 var cacheKey = key + "." + String(method);
5736 if (untaintedMethodCache$1[cacheKey]) return untaintedMethodCache$1[cacheKey].bind(instance);
5737 var untaintedMethod = getUntaintedPrototype$1(key)[method];
5738 if (typeof untaintedMethod !== "function") return instance[method];
5739 untaintedMethodCache$1[cacheKey] = untaintedMethod;
5740 return untaintedMethod.bind(instance);
5741 }
5742 function childNodes$1(n2) {
5743 return getUntaintedAccessor$1("Node", n2, "childNodes");
5744 }
5745 function parentNode$1(n2) {
5746 return getUntaintedAccessor$1("Node", n2, "parentNode");
5747 }
5748 function parentElement$1(n2) {
5749 return getUntaintedAccessor$1("Node", n2, "parentElement");
5750 }
5751 function textContent$1(n2) {
5752 return getUntaintedAccessor$1("Node", n2, "textContent");
5753 }
5754 function contains$1(n2, other) {
5755 return getUntaintedMethod$1("Node", n2, "contains")(other);
5756 }
5757 function getRootNode$1(n2) {
5758 return getUntaintedMethod$1("Node", n2, "getRootNode")();
5759 }
5760 function host$1(n2) {
5761 if (!n2 || !("host" in n2)) return null;
5762 return getUntaintedAccessor$1("ShadowRoot", n2, "host");
5763 }
5764 function styleSheets$1(n2) {
5765 return n2.styleSheets;
5766 }
5767 function shadowRoot$1(n2) {
5768 if (!n2 || !("shadowRoot" in n2)) return null;
5769 return getUntaintedAccessor$1("Element", n2, "shadowRoot");
5770 }
5771 function querySelector$1(n2, selectors) {
5772 return getUntaintedAccessor$1("Element", n2, "querySelector")(selectors);
5773 }
5774 function querySelectorAll$1(n2, selectors) {
5775 return getUntaintedAccessor$1("Element", n2, "querySelectorAll")(selectors);
5776 }
5777 function mutationObserverCtor$1() {
5778 return getUntaintedPrototype$1("MutationObserver").constructor;
5779 }
5780 function patch$1(source, name, replacement) {
5781 try {
5782 if (!(name in source)) return function() {};
5783 var original = source[name];
5784 var wrapped = replacement(original);
5785 if (typeof wrapped === "function") {
5786 wrapped.prototype = wrapped.prototype || {};
5787 Object.defineProperties(wrapped, { __rrweb_original__: {
5788 enumerable: false,
5789 value: original
5790 } });
5791 }
5792 source[name] = wrapped;
5793 return function() {
5794 source[name] = original;
5795 };
5796 } catch (e) {
5797 return function() {};
5798 }
5799 }
5800 var index$1 = {
5801 childNodes: childNodes$1,
5802 parentNode: parentNode$1,
5803 parentElement: parentElement$1,
5804 textContent: textContent$1,
5805 contains: contains$1,
5806 getRootNode: getRootNode$1,
5807 host: host$1,
5808 styleSheets: styleSheets$1,
5809 shadowRoot: shadowRoot$1,
5810 querySelector: querySelector$1,
5811 querySelectorAll: querySelectorAll$1,
5812 mutationObserver: mutationObserverCtor$1,
5813 patch: patch$1
5814 };
5815 function isElement(n2) {
5816 return n2.nodeType === n2.ELEMENT_NODE;
5817 }
5818 function isShadowRoot(n2) {
5819 var hostEl = n2 && "host" in n2 && "mode" in n2 && index$1.host(n2) || null;
5820 return Boolean(hostEl && "shadowRoot" in hostEl && index$1.shadowRoot(hostEl) === n2);
5821 }
5822 function isNativeShadowDom(shadowRoot2) {
5823 return Object.prototype.toString.call(shadowRoot2) === "[object ShadowRoot]";
5824 }
5825 function fixBrowserCompatibilityIssuesInCSS(cssText) {
5826 if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) cssText = cssText.replace(/\sbackground-clip:\s*text;/g, " -webkit-background-clip: text; background-clip: text;");
5827 return cssText;
5828 }
5829 function escapeImportStatement(rule2) {
5830 var cssText = rule2.cssText;
5831 if (cssText.split("\"").length < 3) return cssText;
5832 var statement = ["@import", "url(" + JSON.stringify(rule2.href) + ")"];
5833 if (rule2.layerName === "") statement.push("layer");
5834 else if (rule2.layerName) statement.push("layer(" + rule2.layerName + ")");
5835 if (rule2.supportsText) statement.push("supports(" + rule2.supportsText + ")");
5836 if (rule2.media.length) statement.push(rule2.media.mediaText);
5837 return statement.join(" ") + ";";
5838 }
5839 function stringifyStylesheet(s2) {
5840 try {
5841 var rules2 = s2.rules || s2.cssRules;
5842 if (!rules2) return null;
5843 var sheetHref = s2.href;
5844 if (!sheetHref && s2.ownerNode && s2.ownerNode.ownerDocument) sheetHref = s2.ownerNode.ownerDocument.location.href;
5845 return fixBrowserCompatibilityIssuesInCSS(Array.from(rules2, function(rule2) {
5846 return stringifyRule(rule2, sheetHref);
5847 }).join(""));
5848 } catch (error) {
5849 return null;
5850 }
5851 }
5852 function stringifyRule(rule2, sheetHref) {
5853 if (isCSSImportRule(rule2)) {
5854 var importStringified;
5855 try {
5856 importStringified = stringifyStylesheet(rule2.styleSheet) || escapeImportStatement(rule2);
5857 } catch (error) {
5858 importStringified = rule2.cssText;
5859 }
5860 if (rule2.styleSheet.href) return absolutifyURLs(importStringified, rule2.styleSheet.href);
5861 return importStringified;
5862 } else {
5863 var ruleStringified = rule2.cssText;
5864 if (isCSSStyleRule(rule2) && rule2.selectorText.includes(":")) ruleStringified = fixSafariColons(ruleStringified);
5865 if (sheetHref) return absolutifyURLs(ruleStringified, sheetHref);
5866 return ruleStringified;
5867 }
5868 }
5869 function fixSafariColons(cssStringified) {
5870 return cssStringified.replace(/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm, "$1\\$2");
5871 }
5872 function isCSSImportRule(rule2) {
5873 return "styleSheet" in rule2;
5874 }
5875 function isCSSStyleRule(rule2) {
5876 return "selectorText" in rule2;
5877 }
5878 var Mirror = /*#__PURE__*/ function() {
5879 function Mirror() {
5880 __publicField$1(this, "idNodeMap", /* @__PURE__ */ new Map());
5881 __publicField$1(this, "nodeMetaMap", /* @__PURE__ */ new WeakMap());
5882 }
5883 var _proto = Mirror.prototype;
5884 _proto.getId = function getId(n2) {
5885 var _a2;
5886 if (!n2) return -1;
5887 var id = (_a2 = this.getMeta(n2)) == null ? void 0 : _a2.id;
5888 return id != null ? id : -1;
5889 };
5890 _proto.getNode = function getNode(id) {
5891 return this.idNodeMap.get(id) || null;
5892 };
5893 _proto.getIds = function getIds() {
5894 return Array.from(this.idNodeMap.keys());
5895 };
5896 _proto.getMeta = function getMeta(n2) {
5897 return this.nodeMetaMap.get(n2) || null;
5898 };
5899 _proto.removeNodeFromMap = function removeNodeFromMap(n2) {
5900 var _this = this;
5901 var id = this.getId(n2);
5902 this.idNodeMap.delete(id);
5903 if (n2.childNodes) n2.childNodes.forEach(function(childNode) {
5904 return _this.removeNodeFromMap(childNode);
5905 });
5906 };
5907 _proto.has = function has(id) {
5908 return this.idNodeMap.has(id);
5909 };
5910 _proto.hasNode = function hasNode(node2) {
5911 return this.nodeMetaMap.has(node2);
5912 };
5913 _proto.add = function add(n2, meta) {
5914 var id = meta.id;
5915 this.idNodeMap.set(id, n2);
5916 this.nodeMetaMap.set(n2, meta);
5917 };
5918 _proto.replace = function replace(id, n2) {
5919 var oldNode = this.getNode(id);
5920 if (oldNode) {
5921 var meta = this.nodeMetaMap.get(oldNode);
5922 if (meta) this.nodeMetaMap.set(n2, meta);
5923 }
5924 this.idNodeMap.set(id, n2);
5925 };
5926 _proto.reset = function reset() {
5927 this.idNodeMap = /* @__PURE__ */ new Map();
5928 this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
5929 };
5930 return Mirror;
5931 }();
5932 function createMirror$2() {
5933 return new Mirror();
5934 }
5935 function maskInputValue(param) {
5936 var element = param.element;
5937 var maskInputOptions = param.maskInputOptions;
5938 var tagName = param.tagName;
5939 var type = param.type;
5940 var value = param.value;
5941 var maskInputFn = param.maskInputFn;
5942 var text = value || "";
5943 var actualType = type && toLowerCase(type);
5944 if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) if (maskInputFn) text = maskInputFn(text, element);
5945 else text = "*".repeat(text.length);
5946 return text;
5947 }
5948 function toLowerCase(str) {
5949 return str.toLowerCase();
5950 }
5951 var ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__";
5952 function is2DCanvasBlank(canvas) {
5953 var ctx = canvas.getContext("2d");
5954 if (!ctx) return true;
5955 var chunkSize = 50;
5956 for (var x2 = 0; x2 < canvas.width; x2 += chunkSize) for (var y = 0; y < canvas.height; y += chunkSize) {
5957 var getImageData = ctx.getImageData;
5958 var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
5959 if (new Uint32Array(originalGetImageData.call(ctx, x2, y, Math.min(chunkSize, canvas.width - x2), Math.min(chunkSize, canvas.height - y)).data.buffer).some(function(pixel) {
5960 return pixel !== 0;
5961 })) return false;
5962 }
5963 return true;
5964 }
5965 function getInputType(element) {
5966 var type = element.type;
5967 return element.hasAttribute("data-rr-is-password") ? "password" : type ? toLowerCase(type) : null;
5968 }
5969 function extractFileExtension(path, baseURL) {
5970 var url;
5971 try {
5972 url = new URL(path, baseURL != null ? baseURL : window.location.href);
5973 } catch (err) {
5974 return null;
5975 }
5976 var match = url.pathname.match(/\.([0-9a-z]+)(?:$)/i);
5977 var _ref;
5978 return (_ref = match == null ? void 0 : match[1]) != null ? _ref : null;
5979 }
5980 function extractOrigin(url) {
5981 var origin = "";
5982 if (url.indexOf("//") > -1) origin = url.split("/").slice(0, 3).join("/");
5983 else origin = url.split("/")[0];
5984 origin = origin.split("?")[0];
5985 return origin;
5986 }
5987 var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
5988 var URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i;
5989 var URL_WWW_MATCH = /^www\..*/i;
5990 var DATA_URI = /^(data:)([^,]*),(.*)/i;
5991 function absolutifyURLs(cssText, href) {
5992 return (cssText || "").replace(URL_IN_CSS_REF, function(origin, quote1, path1, quote2, path2, path3) {
5993 var filePath = path1 || path2 || path3;
5994 var maybeQuote = quote1 || quote2 || "";
5995 if (!filePath) return origin;
5996 if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) return "url(" + maybeQuote + filePath + maybeQuote + ")";
5997 if (DATA_URI.test(filePath)) return "url(" + maybeQuote + filePath + maybeQuote + ")";
5998 if (filePath[0] === "/") return "url(" + maybeQuote + (extractOrigin(href) + filePath) + maybeQuote + ")";
5999 var stack = href.split("/");
6000 var parts = filePath.split("/");
6001 stack.pop();
6002 for (var _iterator = _create_for_of_iterator_helper_loose(parts), _step; !(_step = _iterator()).done;) {
6003 var part = _step.value;
6004 if (part === ".") continue;
6005 else if (part === "..") stack.pop();
6006 else stack.push(part);
6007 }
6008 return "url(" + maybeQuote + stack.join("/") + maybeQuote + ")";
6009 });
6010 }
6011 function normalizeCssString(cssText, _testNoPxNorm) {
6012 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
6013 if (_testNoPxNorm) return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "");
6014 else return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "").replace(/0px/g, "0");
6015 }
6016 function splitCssText(cssText, style, _testNoPxNorm) {
6017 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
6018 var childNodes2 = Array.from(style.childNodes);
6019 var splits = [];
6020 var iterCount = 0;
6021 if (childNodes2.length > 1 && cssText && typeof cssText === "string") {
6022 var cssTextNorm = normalizeCssString(cssText, _testNoPxNorm);
6023 var normFactor = cssTextNorm.length / cssText.length;
6024 for (var i2 = 1; i2 < childNodes2.length; i2++) if (childNodes2[i2].textContent && typeof childNodes2[i2].textContent === "string") {
6025 var textContentNorm = normalizeCssString(childNodes2[i2].textContent, _testNoPxNorm);
6026 var jLimit = 100;
6027 var j = 3;
6028 for (; j < textContentNorm.length; j++) {
6029 if (textContentNorm[j].match(/[a-zA-Z0-9]/) || textContentNorm.indexOf(textContentNorm.substring(0, j), 1) !== -1) continue;
6030 break;
6031 }
6032 for (; j < textContentNorm.length; j++) {
6033 var startSubstring = textContentNorm.substring(0, j);
6034 var cssNormSplits = cssTextNorm.split(startSubstring);
6035 var splitNorm = -1;
6036 if (cssNormSplits.length === 2) splitNorm = cssNormSplits[0].length;
6037 else if (cssNormSplits.length > 2 && cssNormSplits[0] === "" && childNodes2[i2 - 1].textContent !== "") splitNorm = cssTextNorm.indexOf(startSubstring, 1);
6038 else if (cssNormSplits.length === 1) {
6039 startSubstring = startSubstring.substring(0, startSubstring.length - 1);
6040 cssNormSplits = cssTextNorm.split(startSubstring);
6041 if (cssNormSplits.length <= 1) {
6042 splits.push(cssText);
6043 return splits;
6044 }
6045 j = jLimit + 1;
6046 } else if (j === textContentNorm.length - 1) splitNorm = cssTextNorm.indexOf(startSubstring);
6047 if (cssNormSplits.length >= 2 && j > jLimit) {
6048 var prevTextContent = childNodes2[i2 - 1].textContent;
6049 if (prevTextContent && typeof prevTextContent === "string") {
6050 var prevMinLength = normalizeCssString(prevTextContent).length;
6051 splitNorm = cssTextNorm.indexOf(startSubstring, prevMinLength);
6052 }
6053 if (splitNorm === -1) splitNorm = cssNormSplits[0].length;
6054 }
6055 if (splitNorm !== -1) {
6056 var k = Math.floor(splitNorm / normFactor);
6057 for (; k > 0 && k < cssText.length;) {
6058 iterCount += 1;
6059 if (iterCount > 50 * childNodes2.length) {
6060 splits.push(cssText);
6061 return splits;
6062 }
6063 var normPart = normalizeCssString(cssText.substring(0, k), _testNoPxNorm);
6064 if (normPart.length === splitNorm) {
6065 splits.push(cssText.substring(0, k));
6066 cssText = cssText.substring(k);
6067 cssTextNorm = cssTextNorm.substring(splitNorm);
6068 break;
6069 } else if (normPart.length < splitNorm) k += Math.max(1, Math.floor((splitNorm - normPart.length) / normFactor));
6070 else k -= Math.max(1, Math.floor((normPart.length - splitNorm) * normFactor));
6071 }
6072 break;
6073 }
6074 }
6075 }
6076 }
6077 splits.push(cssText);
6078 return splits;
6079 }
6080 function markCssSplits(cssText, style) {
6081 return splitCssText(cssText, style).join("/* rr_split */");
6082 }
6083 var _id = 1;
6084 var tagNameRegex = /* @__PURE__ */ new RegExp("[^a-z0-9-_:]");
6085 var IGNORED_NODE = -2;
6086 function genId() {
6087 return _id++;
6088 }
6089 function getValidTagName$1(element) {
6090 if (_instanceof(element, HTMLFormElement)) return "form";
6091 var processedTagName = toLowerCase(element.tagName);
6092 if (tagNameRegex.test(processedTagName)) return "div";
6093 return processedTagName;
6094 }
6095 var canvasService;
6096 var canvasCtx;
6097 var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
6098 var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
6099 function getAbsoluteSrcsetString(doc, attributeValue) {
6100 if (attributeValue.trim() === "") return attributeValue;
6101 var pos = 0;
6102 function collectCharacters(regEx) {
6103 var chars2;
6104 var match = regEx.exec(attributeValue.substring(pos));
6105 if (match) {
6106 chars2 = match[0];
6107 pos += chars2.length;
6108 return chars2;
6109 }
6110 return "";
6111 }
6112 var output = [];
6113 while (true) {
6114 collectCharacters(SRCSET_COMMAS_OR_SPACES);
6115 if (pos >= attributeValue.length) break;
6116 var url = collectCharacters(SRCSET_NOT_SPACES);
6117 if (url.slice(-1) === ",") {
6118 url = absoluteToDoc(doc, url.substring(0, url.length - 1));
6119 output.push(url);
6120 } else {
6121 var descriptorsStr = "";
6122 url = absoluteToDoc(doc, url);
6123 var inParens = false;
6124 while (true) {
6125 var c2 = attributeValue.charAt(pos);
6126 if (c2 === "") {
6127 output.push((url + descriptorsStr).trim());
6128 break;
6129 } else if (!inParens) {
6130 if (c2 === ",") {
6131 pos += 1;
6132 output.push((url + descriptorsStr).trim());
6133 break;
6134 } else if (c2 === "(") inParens = true;
6135 } else if (c2 === ")") inParens = false;
6136 descriptorsStr += c2;
6137 pos += 1;
6138 }
6139 }
6140 }
6141 return output.join(", ");
6142 }
6143 var cachedDocument = /* @__PURE__ */ new WeakMap();
6144 function absoluteToDoc(doc, attributeValue) {
6145 if (!attributeValue || attributeValue.trim() === "") return attributeValue;
6146 return getHref(doc, attributeValue);
6147 }
6148 function isSVGElement(el) {
6149 return Boolean(el.tagName === "svg" || el.ownerSVGElement);
6150 }
6151 function getHref(doc, customHref) {
6152 var a2 = cachedDocument.get(doc);
6153 if (!a2) {
6154 a2 = doc.createElement("a");
6155 cachedDocument.set(doc, a2);
6156 }
6157 if (!customHref) customHref = "";
6158 else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) return customHref;
6159 a2.setAttribute("href", customHref);
6160 return a2.href;
6161 }
6162 function transformAttribute(doc, tagName, name, value) {
6163 if (!value) return value;
6164 if (name === "src" || name === "href" && !(tagName === "use" && value[0] === "#")) return absoluteToDoc(doc, value);
6165 else if (name === "xlink:href" && value[0] !== "#") return absoluteToDoc(doc, value);
6166 else if (name === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) return absoluteToDoc(doc, value);
6167 else if (name === "srcset") return getAbsoluteSrcsetString(doc, value);
6168 else if (name === "style") return absolutifyURLs(value, getHref(doc));
6169 else if (tagName === "object" && name === "data") return absoluteToDoc(doc, value);
6170 return value;
6171 }
6172 function ignoreAttribute(tagName, name, _value) {
6173 return (tagName === "video" || tagName === "audio") && name === "autoplay";
6174 }
6175 function _isBlockedElement(element, blockClass, blockSelector) {
6176 try {
6177 if (typeof blockClass === "string") {
6178 if (element.classList.contains(blockClass)) return true;
6179 } else for (var eIndex = element.classList.length; eIndex--;) {
6180 var className = element.classList[eIndex];
6181 if (blockClass.test(className)) return true;
6182 }
6183 if (blockSelector) return element.matches(blockSelector);
6184 } catch (e2) {}
6185 return false;
6186 }
6187 function classMatchesRegex(node2, regex, checkAncestors) {
6188 if (!node2) return false;
6189 if (node2.nodeType !== node2.ELEMENT_NODE) {
6190 if (!checkAncestors) return false;
6191 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
6192 }
6193 for (var eIndex = node2.classList.length; eIndex--;) {
6194 var className = node2.classList[eIndex];
6195 if (regex.test(className)) return true;
6196 }
6197 if (!checkAncestors) return false;
6198 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
6199 }
6200 function needMaskingText(node2, maskTextClass, maskTextSelector, checkAncestors) {
6201 var el;
6202 if (isElement(node2)) {
6203 el = node2;
6204 if (!index$1.childNodes(el).length) return false;
6205 } else if (index$1.parentElement(node2) === null) return false;
6206 else el = index$1.parentElement(node2);
6207 try {
6208 if (typeof maskTextClass === "string") {
6209 if (checkAncestors) {
6210 if (el.closest("." + maskTextClass)) return true;
6211 } else if (el.classList.contains(maskTextClass)) return true;
6212 } else if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;
6213 if (maskTextSelector) {
6214 if (checkAncestors) {
6215 if (el.closest(maskTextSelector)) return true;
6216 } else if (el.matches(maskTextSelector)) return true;
6217 }
6218 } catch (e2) {}
6219 return false;
6220 }
6221 function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
6222 var win = iframeEl.contentWindow;
6223 if (!win) return;
6224 var fired = false;
6225 var readyState;
6226 try {
6227 readyState = win.document.readyState;
6228 } catch (error) {
6229 return;
6230 }
6231 if (readyState !== "complete") {
6232 var timer = setTimeout(function() {
6233 if (!fired) {
6234 listener();
6235 fired = true;
6236 }
6237 }, iframeLoadTimeout);
6238 iframeEl.addEventListener("load", function() {
6239 clearTimeout(timer);
6240 fired = true;
6241 listener();
6242 });
6243 return;
6244 }
6245 var blankUrl = "about:blank";
6246 if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") {
6247 setTimeout(listener, 0);
6248 return iframeEl.addEventListener("load", listener);
6249 }
6250 iframeEl.addEventListener("load", listener);
6251 }
6252 function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
6253 var fired = false;
6254 var styleSheetLoaded;
6255 try {
6256 styleSheetLoaded = link.sheet;
6257 } catch (error) {
6258 return;
6259 }
6260 if (styleSheetLoaded) return;
6261 var timer = setTimeout(function() {
6262 if (!fired) {
6263 listener();
6264 fired = true;
6265 }
6266 }, styleSheetLoadTimeout);
6267 link.addEventListener("load", function() {
6268 clearTimeout(timer);
6269 fired = true;
6270 listener();
6271 });
6272 }
6273 function serializeNode(n2, options) {
6274 var doc = options.doc;
6275 var mirror2 = options.mirror;
6276 var blockClass = options.blockClass;
6277 var blockSelector = options.blockSelector;
6278 var needsMask = options.needsMask;
6279 var inlineStylesheet = options.inlineStylesheet;
6280 var _options_maskInputOptions = options.maskInputOptions;
6281 var maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions;
6282 var maskTextFn = options.maskTextFn;
6283 var maskInputFn = options.maskInputFn;
6284 var _options_dataURLOptions = options.dataURLOptions;
6285 var dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions;
6286 var inlineImages = options.inlineImages;
6287 var recordCanvas = options.recordCanvas;
6288 var keepIframeSrcFn = options.keepIframeSrcFn;
6289 var _options_newlyAddedElement = options.newlyAddedElement;
6290 var newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement;
6291 var _options_cssCaptured = options.cssCaptured;
6292 var cssCaptured = _options_cssCaptured === void 0 ? false : _options_cssCaptured;
6293 var rootId = getRootId(doc, mirror2);
6294 switch (n2.nodeType) {
6295 case n2.DOCUMENT_NODE: if (n2.compatMode !== "CSS1Compat") return {
6296 type: NodeType$3.Document,
6297 childNodes: [],
6298 compatMode: n2.compatMode
6299 };
6300 else return {
6301 type: NodeType$3.Document,
6302 childNodes: []
6303 };
6304 case n2.DOCUMENT_TYPE_NODE: return {
6305 type: NodeType$3.DocumentType,
6306 name: n2.name,
6307 publicId: n2.publicId,
6308 systemId: n2.systemId,
6309 rootId
6310 };
6311 case n2.ELEMENT_NODE: return serializeElementNode(n2, {
6312 doc,
6313 blockClass,
6314 blockSelector,
6315 inlineStylesheet,
6316 maskInputOptions,
6317 maskInputFn,
6318 dataURLOptions,
6319 inlineImages,
6320 recordCanvas,
6321 keepIframeSrcFn,
6322 newlyAddedElement,
6323 rootId
6324 });
6325 case n2.TEXT_NODE: return serializeTextNode(n2, {
6326 doc,
6327 needsMask,
6328 maskTextFn,
6329 rootId,
6330 cssCaptured
6331 });
6332 case n2.CDATA_SECTION_NODE: return {
6333 type: NodeType$3.CDATA,
6334 textContent: "",
6335 rootId
6336 };
6337 case n2.COMMENT_NODE: return {
6338 type: NodeType$3.Comment,
6339 textContent: index$1.textContent(n2) || "",
6340 rootId
6341 };
6342 default: return false;
6343 }
6344 }
6345 function getRootId(doc, mirror2) {
6346 if (!mirror2.hasNode(doc)) return void 0;
6347 var docId = mirror2.getId(doc);
6348 return docId === 1 ? void 0 : docId;
6349 }
6350 function serializeTextNode(n2, options) {
6351 var needsMask = options.needsMask;
6352 var maskTextFn = options.maskTextFn;
6353 var rootId = options.rootId;
6354 var cssCaptured = options.cssCaptured;
6355 var parent = index$1.parentNode(n2);
6356 var parentTagName = parent && parent.tagName;
6357 var textContent2 = "";
6358 var isStyle = parentTagName === "STYLE" ? true : void 0;
6359 var isScript = parentTagName === "SCRIPT" ? true : void 0;
6360 if (isScript) textContent2 = "SCRIPT_PLACEHOLDER";
6361 else if (!cssCaptured) {
6362 textContent2 = index$1.textContent(n2);
6363 if (isStyle && textContent2) textContent2 = absolutifyURLs(textContent2, getHref(options.doc));
6364 }
6365 if (!isStyle && !isScript && textContent2 && needsMask) textContent2 = maskTextFn ? maskTextFn(textContent2, index$1.parentElement(n2)) : textContent2.replace(/[\S]/g, "*");
6366 return {
6367 type: NodeType$3.Text,
6368 textContent: textContent2 || "",
6369 rootId
6370 };
6371 }
6372 function serializeElementNode(n2, options) {
6373 var doc = options.doc;
6374 var blockClass = options.blockClass;
6375 var blockSelector = options.blockSelector;
6376 var inlineStylesheet = options.inlineStylesheet;
6377 var _options_maskInputOptions = options.maskInputOptions;
6378 var maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions;
6379 var maskInputFn = options.maskInputFn;
6380 var _options_dataURLOptions = options.dataURLOptions;
6381 var dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions;
6382 var inlineImages = options.inlineImages;
6383 var recordCanvas = options.recordCanvas;
6384 var keepIframeSrcFn = options.keepIframeSrcFn;
6385 var _options_newlyAddedElement = options.newlyAddedElement;
6386 var newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement;
6387 var rootId = options.rootId;
6388 var needBlock = _isBlockedElement(n2, blockClass, blockSelector);
6389 var tagName = getValidTagName$1(n2);
6390 var attributes = {};
6391 var len = n2.attributes.length;
6392 for (var i2 = 0; i2 < len; i2++) {
6393 var attr = n2.attributes[i2];
6394 if (!ignoreAttribute(tagName, attr.name, attr.value)) attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value);
6395 }
6396 if (tagName === "link" && inlineStylesheet) {
6397 var stylesheet = Array.from(doc.styleSheets).find(function(s2) {
6398 return s2.href === n2.href;
6399 });
6400 var cssText = null;
6401 if (stylesheet) cssText = stringifyStylesheet(stylesheet);
6402 if (cssText) {
6403 delete attributes.rel;
6404 delete attributes.href;
6405 attributes._cssText = cssText;
6406 }
6407 }
6408 if (tagName === "style" && n2.sheet) {
6409 var cssText1 = stringifyStylesheet(n2.sheet);
6410 if (cssText1) {
6411 if (n2.childNodes.length > 1) cssText1 = markCssSplits(cssText1, n2);
6412 attributes._cssText = cssText1;
6413 }
6414 }
6415 if (tagName === "input" || tagName === "textarea" || tagName === "select") {
6416 var value = n2.value;
6417 var checked = n2.checked;
6418 if (attributes.type !== "radio" && attributes.type !== "checkbox" && attributes.type !== "submit" && attributes.type !== "button" && value) attributes.value = maskInputValue({
6419 element: n2,
6420 type: getInputType(n2),
6421 tagName,
6422 value,
6423 maskInputOptions,
6424 maskInputFn
6425 });
6426 else if (checked) attributes.checked = checked;
6427 }
6428 if (tagName === "option") if (n2.selected && !maskInputOptions["select"]) attributes.selected = true;
6429 else delete attributes.selected;
6430 if (tagName === "dialog" && n2.open) attributes.rr_open_mode = n2.matches("dialog:modal") ? "modal" : "non-modal";
6431 if (tagName === "canvas" && recordCanvas) {
6432 if (n2.__context === "2d") {
6433 if (!is2DCanvasBlank(n2)) attributes.rr_dataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
6434 } else if (!("__context" in n2)) {
6435 var canvasDataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
6436 var blankCanvas = doc.createElement("canvas");
6437 blankCanvas.width = n2.width;
6438 blankCanvas.height = n2.height;
6439 if (canvasDataURL !== blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality)) attributes.rr_dataURL = canvasDataURL;
6440 }
6441 }
6442 if (tagName === "img" && inlineImages) {
6443 if (!canvasService) {
6444 canvasService = doc.createElement("canvas");
6445 canvasCtx = canvasService.getContext("2d");
6446 }
6447 var image = n2;
6448 var imageSrc = image.currentSrc || image.getAttribute("src") || "<unknown-src>";
6449 var priorCrossOrigin = image.crossOrigin;
6450 var recordInlineImage = function() {
6451 image.removeEventListener("load", recordInlineImage);
6452 try {
6453 canvasService.width = image.naturalWidth;
6454 canvasService.height = image.naturalHeight;
6455 canvasCtx.drawImage(image, 0, 0);
6456 attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
6457 } catch (err) {
6458 if (image.crossOrigin !== "anonymous") {
6459 image.crossOrigin = "anonymous";
6460 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
6461 else image.addEventListener("load", recordInlineImage);
6462 return;
6463 } else console.warn("Cannot inline img src=" + imageSrc + "! Error: " + err);
6464 }
6465 if (image.crossOrigin === "anonymous") priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute("crossorigin");
6466 };
6467 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
6468 else image.addEventListener("load", recordInlineImage);
6469 }
6470 if (tagName === "audio" || tagName === "video") {
6471 var mediaAttributes = attributes;
6472 mediaAttributes.rr_mediaState = n2.paused ? "paused" : "played";
6473 mediaAttributes.rr_mediaCurrentTime = n2.currentTime;
6474 mediaAttributes.rr_mediaPlaybackRate = n2.playbackRate;
6475 mediaAttributes.rr_mediaMuted = n2.muted;
6476 mediaAttributes.rr_mediaLoop = n2.loop;
6477 mediaAttributes.rr_mediaVolume = n2.volume;
6478 }
6479 if (!newlyAddedElement) {
6480 if (n2.scrollLeft) attributes.rr_scrollLeft = n2.scrollLeft;
6481 if (n2.scrollTop) attributes.rr_scrollTop = n2.scrollTop;
6482 }
6483 if (needBlock) {
6484 var _n2_getBoundingClientRect = n2.getBoundingClientRect();
6485 var width = _n2_getBoundingClientRect.width;
6486 var height = _n2_getBoundingClientRect.height;
6487 attributes = {
6488 class: attributes.class,
6489 rr_width: "" + width + "px",
6490 rr_height: "" + height + "px"
6491 };
6492 }
6493 if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) {
6494 if (!n2.contentDocument) attributes.rr_src = attributes.src;
6495 delete attributes.src;
6496 }
6497 var isCustomElement;
6498 try {
6499 if (customElements.get(tagName)) isCustomElement = true;
6500 } catch (e2) {}
6501 return {
6502 type: NodeType$3.Element,
6503 tagName,
6504 attributes,
6505 childNodes: [],
6506 isSVG: isSVGElement(n2) || void 0,
6507 needBlock,
6508 rootId,
6509 isCustom: isCustomElement
6510 };
6511 }
6512 function lowerIfExists(maybeAttr) {
6513 if (maybeAttr === void 0 || maybeAttr === null) return "";
6514 else return maybeAttr.toLowerCase();
6515 }
6516 function slimDOMExcluded(sn, slimDOMOptions) {
6517 if (slimDOMOptions.comment && sn.type === NodeType$3.Comment) return true;
6518 else if (sn.type === NodeType$3.Element) {
6519 if (slimDOMOptions.script && (sn.tagName === "script" || sn.tagName === "link" && (sn.attributes.rel === "preload" && sn.attributes.as === "script" || sn.attributes.rel === "modulepreload") || sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && extractFileExtension(sn.attributes.href) === "js")) return true;
6520 else if (slimDOMOptions.headFavicon && (sn.tagName === "link" && sn.attributes.rel === "shortcut icon" || sn.tagName === "meta" && (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) || lowerIfExists(sn.attributes.name) === "application-name" || lowerIfExists(sn.attributes.rel) === "icon" || lowerIfExists(sn.attributes.rel) === "apple-touch-icon" || lowerIfExists(sn.attributes.rel) === "shortcut icon"))) return true;
6521 else if (sn.tagName === "meta") {
6522 if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) return true;
6523 else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) return true;
6524 else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) return true;
6525 else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) return true;
6526 else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === "author" || lowerIfExists(sn.attributes.name) === "generator" || lowerIfExists(sn.attributes.name) === "framework" || lowerIfExists(sn.attributes.name) === "publisher" || lowerIfExists(sn.attributes.name) === "progid" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) return true;
6527 else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === "google-site-verification" || lowerIfExists(sn.attributes.name) === "yandex-verification" || lowerIfExists(sn.attributes.name) === "csrf-token" || lowerIfExists(sn.attributes.name) === "p:domain_verify" || lowerIfExists(sn.attributes.name) === "verify-v1" || lowerIfExists(sn.attributes.name) === "verification" || lowerIfExists(sn.attributes.name) === "shopify-checkout-api-token")) return true;
6528 }
6529 }
6530 return false;
6531 }
6532 function serializeNodeWithId(n2, options) {
6533 var doc = options.doc;
6534 var mirror2 = options.mirror;
6535 var blockClass = options.blockClass;
6536 var blockSelector = options.blockSelector;
6537 var maskTextClass = options.maskTextClass;
6538 var maskTextSelector = options.maskTextSelector;
6539 var _options_skipChild = options.skipChild;
6540 var skipChild = _options_skipChild === void 0 ? false : _options_skipChild;
6541 var _options_inlineStylesheet = options.inlineStylesheet;
6542 var inlineStylesheet = _options_inlineStylesheet === void 0 ? true : _options_inlineStylesheet;
6543 var _options_maskInputOptions = options.maskInputOptions;
6544 var maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions;
6545 var maskTextFn = options.maskTextFn;
6546 var maskInputFn = options.maskInputFn;
6547 var slimDOMOptions = options.slimDOMOptions;
6548 var _options_dataURLOptions = options.dataURLOptions;
6549 var dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions;
6550 var _options_inlineImages = options.inlineImages;
6551 var inlineImages = _options_inlineImages === void 0 ? false : _options_inlineImages;
6552 var _options_recordCanvas = options.recordCanvas;
6553 var recordCanvas = _options_recordCanvas === void 0 ? false : _options_recordCanvas;
6554 var onSerialize = options.onSerialize;
6555 var onIframeLoad = options.onIframeLoad;
6556 var _options_iframeLoadTimeout = options.iframeLoadTimeout;
6557 var iframeLoadTimeout = _options_iframeLoadTimeout === void 0 ? 5e3 : _options_iframeLoadTimeout;
6558 var onStylesheetLoad = options.onStylesheetLoad;
6559 var _options_stylesheetLoadTimeout = options.stylesheetLoadTimeout;
6560 var stylesheetLoadTimeout = _options_stylesheetLoadTimeout === void 0 ? 5e3 : _options_stylesheetLoadTimeout;
6561 var _options_keepIframeSrcFn = options.keepIframeSrcFn;
6562 var keepIframeSrcFn = _options_keepIframeSrcFn === void 0 ? function() {
6563 return false;
6564 } : _options_keepIframeSrcFn;
6565 var _options_newlyAddedElement = options.newlyAddedElement;
6566 var newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement;
6567 var _options_cssCaptured = options.cssCaptured;
6568 var cssCaptured = _options_cssCaptured === void 0 ? false : _options_cssCaptured;
6569 var needsMask = options.needsMask;
6570 var _options_preserveWhiteSpace = options.preserveWhiteSpace;
6571 var preserveWhiteSpace = _options_preserveWhiteSpace === void 0 ? true : _options_preserveWhiteSpace;
6572 if (!needsMask) needsMask = needMaskingText(n2, maskTextClass, maskTextSelector, needsMask === void 0);
6573 var _serializedNode = serializeNode(n2, {
6574 doc,
6575 mirror: mirror2,
6576 blockClass,
6577 blockSelector,
6578 needsMask,
6579 inlineStylesheet,
6580 maskInputOptions,
6581 maskTextFn,
6582 maskInputFn,
6583 dataURLOptions,
6584 inlineImages,
6585 recordCanvas,
6586 keepIframeSrcFn,
6587 newlyAddedElement,
6588 cssCaptured
6589 });
6590 if (!_serializedNode) {
6591 console.warn(n2, "not serialized");
6592 return null;
6593 }
6594 var id;
6595 if (mirror2.hasNode(n2)) id = mirror2.getId(n2);
6596 else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$3.Text && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) id = IGNORED_NODE;
6597 else id = genId();
6598 var serializedNode = Object.assign(_serializedNode, { id });
6599 mirror2.add(n2, serializedNode);
6600 if (id === IGNORED_NODE) return null;
6601 if (onSerialize) onSerialize(n2);
6602 var recordChild = !skipChild;
6603 if (serializedNode.type === NodeType$3.Element) {
6604 recordChild = recordChild && !serializedNode.needBlock;
6605 delete serializedNode.needBlock;
6606 var shadowRootEl = index$1.shadowRoot(n2);
6607 if (shadowRootEl && isNativeShadowDom(shadowRootEl)) serializedNode.isShadowHost = true;
6608 }
6609 if ((serializedNode.type === NodeType$3.Document || serializedNode.type === NodeType$3.Element) && recordChild) {
6610 if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType$3.Element && serializedNode.tagName === "head") preserveWhiteSpace = false;
6611 var bypassOptions = {
6612 doc,
6613 mirror: mirror2,
6614 blockClass,
6615 blockSelector,
6616 needsMask,
6617 maskTextClass,
6618 maskTextSelector,
6619 skipChild,
6620 inlineStylesheet,
6621 maskInputOptions,
6622 maskTextFn,
6623 maskInputFn,
6624 slimDOMOptions,
6625 dataURLOptions,
6626 inlineImages,
6627 recordCanvas,
6628 preserveWhiteSpace,
6629 onSerialize,
6630 onIframeLoad,
6631 iframeLoadTimeout,
6632 onStylesheetLoad,
6633 stylesheetLoadTimeout,
6634 keepIframeSrcFn,
6635 cssCaptured: false
6636 };
6637 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "textarea" && serializedNode.attributes.value !== void 0);
6638 else {
6639 if (serializedNode.type === NodeType$3.Element && serializedNode.attributes._cssText !== void 0 && typeof serializedNode.attributes._cssText === "string") bypassOptions.cssCaptured = true;
6640 for (var _iterator = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(n2))), _step; !(_step = _iterator()).done;) {
6641 var childN = _step.value;
6642 var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
6643 if (serializedChildNode) serializedNode.childNodes.push(serializedChildNode);
6644 }
6645 }
6646 var shadowRootEl1 = null;
6647 if (isElement(n2) && (shadowRootEl1 = index$1.shadowRoot(n2))) for (var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(shadowRootEl1))), _step1; !(_step1 = _iterator1()).done;) {
6648 var childN1 = _step1.value;
6649 var serializedChildNode1 = serializeNodeWithId(childN1, bypassOptions);
6650 if (serializedChildNode1) {
6651 isNativeShadowDom(shadowRootEl1) && (serializedChildNode1.isShadow = true);
6652 serializedNode.childNodes.push(serializedChildNode1);
6653 }
6654 }
6655 }
6656 var parent = index$1.parentNode(n2);
6657 if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) serializedNode.isShadow = true;
6658 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "iframe") onceIframeLoaded(n2, function() {
6659 var iframeDoc = n2.contentDocument;
6660 if (iframeDoc && onIframeLoad) {
6661 var serializedIframeNode = serializeNodeWithId(iframeDoc, {
6662 doc: iframeDoc,
6663 mirror: mirror2,
6664 blockClass,
6665 blockSelector,
6666 needsMask,
6667 maskTextClass,
6668 maskTextSelector,
6669 skipChild: false,
6670 inlineStylesheet,
6671 maskInputOptions,
6672 maskTextFn,
6673 maskInputFn,
6674 slimDOMOptions,
6675 dataURLOptions,
6676 inlineImages,
6677 recordCanvas,
6678 preserveWhiteSpace,
6679 onSerialize,
6680 onIframeLoad,
6681 iframeLoadTimeout,
6682 onStylesheetLoad,
6683 stylesheetLoadTimeout,
6684 keepIframeSrcFn
6685 });
6686 if (serializedIframeNode) onIframeLoad(n2, serializedIframeNode);
6687 }
6688 }, iframeLoadTimeout);
6689 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "link" && typeof serializedNode.attributes.rel === "string" && (serializedNode.attributes.rel === "stylesheet" || serializedNode.attributes.rel === "preload" && typeof serializedNode.attributes.href === "string" && extractFileExtension(serializedNode.attributes.href) === "css")) onceStylesheetLoaded(n2, function() {
6690 if (onStylesheetLoad) {
6691 var serializedLinkNode = serializeNodeWithId(n2, {
6692 doc,
6693 mirror: mirror2,
6694 blockClass,
6695 blockSelector,
6696 needsMask,
6697 maskTextClass,
6698 maskTextSelector,
6699 skipChild: false,
6700 inlineStylesheet,
6701 maskInputOptions,
6702 maskTextFn,
6703 maskInputFn,
6704 slimDOMOptions,
6705 dataURLOptions,
6706 inlineImages,
6707 recordCanvas,
6708 preserveWhiteSpace,
6709 onSerialize,
6710 onIframeLoad,
6711 iframeLoadTimeout,
6712 onStylesheetLoad,
6713 stylesheetLoadTimeout,
6714 keepIframeSrcFn
6715 });
6716 if (serializedLinkNode) onStylesheetLoad(n2, serializedLinkNode);
6717 }
6718 }, stylesheetLoadTimeout);
6719 return serializedNode;
6720 }
6721 function snapshot(n2, options) {
6722 var _ref = options || {};
6723 var tmp = _ref.mirror;
6724 var mirror2 = tmp === void 0 ? new Mirror() : tmp;
6725 var _ref_blockClass = _ref.blockClass;
6726 var blockClass = _ref_blockClass === void 0 ? "rr-block" : _ref_blockClass;
6727 var _ref_blockSelector = _ref.blockSelector;
6728 var blockSelector = _ref_blockSelector === void 0 ? null : _ref_blockSelector;
6729 var _ref_maskTextClass = _ref.maskTextClass;
6730 var maskTextClass = _ref_maskTextClass === void 0 ? "rr-mask" : _ref_maskTextClass;
6731 var _ref_maskTextSelector = _ref.maskTextSelector;
6732 var maskTextSelector = _ref_maskTextSelector === void 0 ? null : _ref_maskTextSelector;
6733 var _ref_inlineStylesheet = _ref.inlineStylesheet;
6734 var inlineStylesheet = _ref_inlineStylesheet === void 0 ? true : _ref_inlineStylesheet;
6735 var _ref_inlineImages = _ref.inlineImages;
6736 var inlineImages = _ref_inlineImages === void 0 ? false : _ref_inlineImages;
6737 var _ref_recordCanvas = _ref.recordCanvas;
6738 var recordCanvas = _ref_recordCanvas === void 0 ? false : _ref_recordCanvas;
6739 var _ref_maskAllInputs = _ref.maskAllInputs;
6740 var maskAllInputs = _ref_maskAllInputs === void 0 ? false : _ref_maskAllInputs;
6741 var maskTextFn = _ref.maskTextFn;
6742 var maskInputFn = _ref.maskInputFn;
6743 var _ref_slimDOM = _ref.slimDOM;
6744 var slimDOM = _ref_slimDOM === void 0 ? false : _ref_slimDOM;
6745 var dataURLOptions = _ref.dataURLOptions;
6746 var preserveWhiteSpace = _ref.preserveWhiteSpace;
6747 var onSerialize = _ref.onSerialize;
6748 var onIframeLoad = _ref.onIframeLoad;
6749 var iframeLoadTimeout = _ref.iframeLoadTimeout;
6750 var onStylesheetLoad = _ref.onStylesheetLoad;
6751 var stylesheetLoadTimeout = _ref.stylesheetLoadTimeout;
6752 var _ref_keepIframeSrcFn = _ref.keepIframeSrcFn;
6753 return serializeNodeWithId(n2, {
6754 doc: n2,
6755 mirror: mirror2,
6756 blockClass,
6757 blockSelector,
6758 maskTextClass,
6759 maskTextSelector,
6760 skipChild: false,
6761 inlineStylesheet,
6762 maskInputOptions: maskAllInputs === true ? {
6763 color: true,
6764 date: true,
6765 "datetime-local": true,
6766 email: true,
6767 month: true,
6768 number: true,
6769 range: true,
6770 search: true,
6771 tel: true,
6772 text: true,
6773 time: true,
6774 url: true,
6775 week: true,
6776 textarea: true,
6777 select: true,
6778 password: true,
6779 hidden: true
6780 } : maskAllInputs === false ? { password: true } : maskAllInputs,
6781 maskTextFn,
6782 maskInputFn,
6783 slimDOMOptions: slimDOM === true || slimDOM === "all" ? {
6784 script: true,
6785 comment: true,
6786 headFavicon: true,
6787 headWhitespace: true,
6788 headMetaDescKeywords: slimDOM === "all",
6789 headMetaSocial: true,
6790 headMetaRobots: true,
6791 headMetaHttpEquiv: true,
6792 headMetaAuthorship: true,
6793 headMetaVerification: true
6794 } : slimDOM === false ? {} : slimDOM,
6795 dataURLOptions,
6796 inlineImages,
6797 recordCanvas,
6798 preserveWhiteSpace,
6799 onSerialize,
6800 onIframeLoad,
6801 iframeLoadTimeout,
6802 onStylesheetLoad,
6803 stylesheetLoadTimeout,
6804 keepIframeSrcFn: _ref_keepIframeSrcFn === void 0 ? function() {
6805 return false;
6806 } : _ref_keepIframeSrcFn,
6807 newlyAddedElement: false
6808 });
6809 }
6810 function getDefaultExportFromCjs$1(x2) {
6811 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
6812 }
6813 function getAugmentedNamespace$1(n2) {
6814 if (n2.__esModule) return n2;
6815 var f2 = n2.default;
6816 if (typeof f2 == "function") {
6817 var a2 = function a22() {
6818 if (_instanceof(this, a22)) return Reflect.construct(f2, arguments, this.constructor);
6819 return f2.apply(this, arguments);
6820 };
6821 a2.prototype = f2.prototype;
6822 } else a2 = {};
6823 Object.defineProperty(a2, "__esModule", { value: true });
6824 Object.keys(n2).forEach(function(k) {
6825 var d = Object.getOwnPropertyDescriptor(n2, k);
6826 Object.defineProperty(a2, k, d.get ? d : {
6827 enumerable: true,
6828 get: function get() {
6829 return n2[k];
6830 }
6831 });
6832 });
6833 return a2;
6834 }
6835 var picocolors_browser$1 = { exports: {} };
6836 var x$1 = String;
6837 var create$1 = function create$1() {
6838 return {
6839 isColorSupported: false,
6840 reset: x$1,
6841 bold: x$1,
6842 dim: x$1,
6843 italic: x$1,
6844 underline: x$1,
6845 inverse: x$1,
6846 hidden: x$1,
6847 strikethrough: x$1,
6848 black: x$1,
6849 red: x$1,
6850 green: x$1,
6851 yellow: x$1,
6852 blue: x$1,
6853 magenta: x$1,
6854 cyan: x$1,
6855 white: x$1,
6856 gray: x$1,
6857 bgBlack: x$1,
6858 bgRed: x$1,
6859 bgGreen: x$1,
6860 bgYellow: x$1,
6861 bgBlue: x$1,
6862 bgMagenta: x$1,
6863 bgCyan: x$1,
6864 bgWhite: x$1
6865 };
6866 };
6867 picocolors_browser$1.exports = create$1();
6868 picocolors_browser$1.exports.createColors = create$1;
6869 var picocolors_browserExports$1 = picocolors_browser$1.exports;
6870 var require$$2$1 = /* @__PURE__ */ getAugmentedNamespace$1(/* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
6871 __proto__: null,
6872 default: {}
6873 }, Symbol.toStringTag, { value: "Module" })));
6874 var pico$1 = picocolors_browserExports$1;
6875 var terminalHighlight$1$1 = require$$2$1;
6876 var CssSyntaxError$3$1 = /*#__PURE__*/ function(Error1) {
6877 _inherits(CssSyntaxError, Error1);
6878 function CssSyntaxError(message, line, column, source, file, plugin22) {
6879 var _this = Error1.call(this, message) || this;
6880 _this.name = "CssSyntaxError";
6881 _this.reason = message;
6882 if (file) _this.file = file;
6883 if (source) _this.source = source;
6884 if (plugin22) _this.plugin = plugin22;
6885 if (typeof line !== "undefined" && typeof column !== "undefined") if (typeof line === "number") {
6886 _this.line = line;
6887 _this.column = column;
6888 } else {
6889 _this.line = line.line;
6890 _this.column = line.column;
6891 _this.endLine = column.line;
6892 _this.endColumn = column.column;
6893 }
6894 _this.setMessage();
6895 if (Error.captureStackTrace) Error.captureStackTrace(_this, CssSyntaxError);
6896 return _this;
6897 }
6898 var _proto = CssSyntaxError.prototype;
6899 _proto.setMessage = function setMessage() {
6900 this.message = this.plugin ? this.plugin + ": " : "";
6901 this.message += this.file ? this.file : "<css input>";
6902 if (typeof this.line !== "undefined") this.message += ":" + this.line + ":" + this.column;
6903 this.message += ": " + this.reason;
6904 };
6905 _proto.showSourceCode = function showSourceCode(color) {
6906 var _this = this;
6907 if (!this.source) return "";
6908 var css = this.source;
6909 if (color == null) color = pico$1.isColorSupported;
6910 if (terminalHighlight$1$1) {
6911 if (color) css = terminalHighlight$1$1(css);
6912 }
6913 var lines = css.split(/\r?\n/);
6914 var start = Math.max(this.line - 3, 0);
6915 var end = Math.min(this.line + 2, lines.length);
6916 var maxWidth = String(end).length;
6917 var mark;
6918 var aside;
6919 if (color) {
6920 var _pico$1_createColors = pico$1.createColors(true);
6921 var bold = _pico$1_createColors.bold;
6922 var gray = _pico$1_createColors.gray;
6923 var red = _pico$1_createColors.red;
6924 mark = function(text) {
6925 return bold(red(text));
6926 };
6927 aside = function(text) {
6928 return gray(text);
6929 };
6930 } else mark = aside = function(str) {
6931 return str;
6932 };
6933 return lines.slice(start, end).map(function(line, index2) {
6934 var number = start + 1 + index2;
6935 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
6936 if (number === _this.line) {
6937 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
6938 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
6939 }
6940 return " " + aside(gutter) + line;
6941 }).join("\n");
6942 };
6943 _proto.toString = function toString() {
6944 var code = this.showSourceCode();
6945 if (code) code = "\n\n" + code + "\n";
6946 return this.name + ": " + this.message + code;
6947 };
6948 return CssSyntaxError;
6949 }(_wrap_native_super(Error));
6950 var cssSyntaxError$1 = CssSyntaxError$3$1;
6951 CssSyntaxError$3$1.default = CssSyntaxError$3$1;
6952 var symbols$1 = {};
6953 symbols$1.isClean = Symbol("isClean");
6954 symbols$1.my = Symbol("my");
6955 var DEFAULT_RAW$1 = {
6956 after: "\n",
6957 beforeClose: "\n",
6958 beforeComment: "\n",
6959 beforeDecl: "\n",
6960 beforeOpen: " ",
6961 beforeRule: "\n",
6962 colon: ": ",
6963 commentLeft: " ",
6964 commentRight: " ",
6965 emptyBody: "",
6966 indent: " ",
6967 semicolon: false
6968 };
6969 function capitalize$1(str) {
6970 return str[0].toUpperCase() + str.slice(1);
6971 }
6972 var Stringifier$2$1 = /*#__PURE__*/ function() {
6973 function Stringifier(builder) {
6974 this.builder = builder;
6975 }
6976 var _proto = Stringifier.prototype;
6977 _proto.atrule = function atrule(node2, semicolon) {
6978 var name = "@" + node2.name;
6979 var params = node2.params ? this.rawValue(node2, "params") : "";
6980 if (typeof node2.raws.afterName !== "undefined") name += node2.raws.afterName;
6981 else if (params) name += " ";
6982 if (node2.nodes) this.block(node2, name + params);
6983 else {
6984 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
6985 this.builder(name + params + end, node2);
6986 }
6987 };
6988 _proto.beforeAfter = function beforeAfter(node2, detect) {
6989 var value;
6990 if (node2.type === "decl") value = this.raw(node2, null, "beforeDecl");
6991 else if (node2.type === "comment") value = this.raw(node2, null, "beforeComment");
6992 else if (detect === "before") value = this.raw(node2, null, "beforeRule");
6993 else value = this.raw(node2, null, "beforeClose");
6994 var buf = node2.parent;
6995 var depth = 0;
6996 while (buf && buf.type !== "root") {
6997 depth += 1;
6998 buf = buf.parent;
6999 }
7000 if (value.includes("\n")) {
7001 var indent = this.raw(node2, null, "indent");
7002 if (indent.length) for (var step = 0; step < depth; step++) value += indent;
7003 }
7004 return value;
7005 };
7006 _proto.block = function block(node2, start) {
7007 var between = this.raw(node2, "between", "beforeOpen");
7008 this.builder(start + between + "{", node2, "start");
7009 var after;
7010 if (node2.nodes && node2.nodes.length) {
7011 this.body(node2);
7012 after = this.raw(node2, "after");
7013 } else after = this.raw(node2, "after", "emptyBody");
7014 if (after) this.builder(after);
7015 this.builder("}", node2, "end");
7016 };
7017 _proto.body = function body(node2) {
7018 var last = node2.nodes.length - 1;
7019 while (last > 0) {
7020 if (node2.nodes[last].type !== "comment") break;
7021 last -= 1;
7022 }
7023 var semicolon = this.raw(node2, "semicolon");
7024 for (var i2 = 0; i2 < node2.nodes.length; i2++) {
7025 var child = node2.nodes[i2];
7026 var before = this.raw(child, "before");
7027 if (before) this.builder(before);
7028 this.stringify(child, last !== i2 || semicolon);
7029 }
7030 };
7031 _proto.comment = function comment(node2) {
7032 var left = this.raw(node2, "left", "commentLeft");
7033 var right = this.raw(node2, "right", "commentRight");
7034 this.builder("/*" + left + node2.text + right + "*/", node2);
7035 };
7036 _proto.decl = function decl(node2, semicolon) {
7037 var between = this.raw(node2, "between", "colon");
7038 var string = node2.prop + between + this.rawValue(node2, "value");
7039 if (node2.important) string += node2.raws.important || " !important";
7040 if (semicolon) string += ";";
7041 this.builder(string, node2);
7042 };
7043 _proto.document = function document1(node2) {
7044 this.body(node2);
7045 };
7046 _proto.raw = function raw(node2, own, detect) {
7047 var value;
7048 if (!detect) detect = own;
7049 if (own) {
7050 value = node2.raws[own];
7051 if (typeof value !== "undefined") return value;
7052 }
7053 var parent = node2.parent;
7054 if (detect === "before") {
7055 if (!parent || parent.type === "root" && parent.first === node2) return "";
7056 if (parent && parent.type === "document") return "";
7057 }
7058 if (!parent) return DEFAULT_RAW$1[detect];
7059 var root2 = node2.root();
7060 if (!root2.rawCache) root2.rawCache = {};
7061 if (typeof root2.rawCache[detect] !== "undefined") return root2.rawCache[detect];
7062 if (detect === "before" || detect === "after") return this.beforeAfter(node2, detect);
7063 else {
7064 var method = "raw" + capitalize$1(detect);
7065 if (this[method]) value = this[method](root2, node2);
7066 else root2.walk(function(i2) {
7067 value = i2.raws[own];
7068 if (typeof value !== "undefined") return false;
7069 });
7070 }
7071 if (typeof value === "undefined") value = DEFAULT_RAW$1[detect];
7072 root2.rawCache[detect] = value;
7073 return value;
7074 };
7075 _proto.rawBeforeClose = function rawBeforeClose(root2) {
7076 var value;
7077 root2.walk(function(i2) {
7078 if (i2.nodes && i2.nodes.length > 0) {
7079 if (typeof i2.raws.after !== "undefined") {
7080 value = i2.raws.after;
7081 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
7082 return false;
7083 }
7084 }
7085 });
7086 if (value) value = value.replace(/\S/g, "");
7087 return value;
7088 };
7089 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
7090 var value;
7091 root2.walkComments(function(i2) {
7092 if (typeof i2.raws.before !== "undefined") {
7093 value = i2.raws.before;
7094 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
7095 return false;
7096 }
7097 });
7098 if (typeof value === "undefined") value = this.raw(node2, null, "beforeDecl");
7099 else if (value) value = value.replace(/\S/g, "");
7100 return value;
7101 };
7102 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
7103 var value;
7104 root2.walkDecls(function(i2) {
7105 if (typeof i2.raws.before !== "undefined") {
7106 value = i2.raws.before;
7107 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
7108 return false;
7109 }
7110 });
7111 if (typeof value === "undefined") value = this.raw(node2, null, "beforeRule");
7112 else if (value) value = value.replace(/\S/g, "");
7113 return value;
7114 };
7115 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
7116 var value;
7117 root2.walk(function(i2) {
7118 if (i2.type !== "decl") {
7119 value = i2.raws.between;
7120 if (typeof value !== "undefined") return false;
7121 }
7122 });
7123 return value;
7124 };
7125 _proto.rawBeforeRule = function rawBeforeRule(root2) {
7126 var value;
7127 root2.walk(function(i2) {
7128 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
7129 if (typeof i2.raws.before !== "undefined") {
7130 value = i2.raws.before;
7131 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
7132 return false;
7133 }
7134 }
7135 });
7136 if (value) value = value.replace(/\S/g, "");
7137 return value;
7138 };
7139 _proto.rawColon = function rawColon(root2) {
7140 var value;
7141 root2.walkDecls(function(i2) {
7142 if (typeof i2.raws.between !== "undefined") {
7143 value = i2.raws.between.replace(/[^\s:]/g, "");
7144 return false;
7145 }
7146 });
7147 return value;
7148 };
7149 _proto.rawEmptyBody = function rawEmptyBody(root2) {
7150 var value;
7151 root2.walk(function(i2) {
7152 if (i2.nodes && i2.nodes.length === 0) {
7153 value = i2.raws.after;
7154 if (typeof value !== "undefined") return false;
7155 }
7156 });
7157 return value;
7158 };
7159 _proto.rawIndent = function rawIndent(root2) {
7160 if (root2.raws.indent) return root2.raws.indent;
7161 var value;
7162 root2.walk(function(i2) {
7163 var p = i2.parent;
7164 if (p && p !== root2 && p.parent && p.parent === root2) {
7165 if (typeof i2.raws.before !== "undefined") {
7166 var parts = i2.raws.before.split("\n");
7167 value = parts[parts.length - 1];
7168 value = value.replace(/\S/g, "");
7169 return false;
7170 }
7171 }
7172 });
7173 return value;
7174 };
7175 _proto.rawSemicolon = function rawSemicolon(root2) {
7176 var value;
7177 root2.walk(function(i2) {
7178 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
7179 value = i2.raws.semicolon;
7180 if (typeof value !== "undefined") return false;
7181 }
7182 });
7183 return value;
7184 };
7185 _proto.rawValue = function rawValue(node2, prop) {
7186 var value = node2[prop];
7187 var raw = node2.raws[prop];
7188 if (raw && raw.value === value) return raw.raw;
7189 return value;
7190 };
7191 _proto.root = function root(node2) {
7192 this.body(node2);
7193 if (node2.raws.after) this.builder(node2.raws.after);
7194 };
7195 _proto.rule = function rule(node2) {
7196 this.block(node2, this.rawValue(node2, "selector"));
7197 if (node2.raws.ownSemicolon) this.builder(node2.raws.ownSemicolon, node2, "end");
7198 };
7199 _proto.stringify = function stringify(node2, semicolon) {
7200 if (!this[node2.type]) throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
7201 this[node2.type](node2, semicolon);
7202 };
7203 return Stringifier;
7204 }();
7205 var stringifier$1 = Stringifier$2$1;
7206 Stringifier$2$1.default = Stringifier$2$1;
7207 var Stringifier$1$1 = stringifier$1;
7208 function stringify$4$1(node2, builder) {
7209 new Stringifier$1$1(builder).stringify(node2);
7210 }
7211 var stringify_1$1 = stringify$4$1;
7212 stringify$4$1.default = stringify$4$1;
7213 var isClean$2$1 = symbols$1.isClean;
7214 var my$2$1 = symbols$1.my;
7215 var CssSyntaxError$2$1 = cssSyntaxError$1;
7216 var Stringifier2$1 = stringifier$1;
7217 var stringify$3$1 = stringify_1$1;
7218 function cloneNode$1(obj, parent) {
7219 var cloned = new obj.constructor();
7220 for (var i2 in obj) {
7221 if (!Object.prototype.hasOwnProperty.call(obj, i2)) continue;
7222 if (i2 === "proxyCache") continue;
7223 var value = obj[i2];
7224 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
7225 if (i2 === "parent" && type === "object") {
7226 if (parent) cloned[i2] = parent;
7227 } else if (i2 === "source") cloned[i2] = value;
7228 else if (Array.isArray(value)) cloned[i2] = value.map(function(j) {
7229 return cloneNode$1(j, cloned);
7230 });
7231 else {
7232 if (type === "object" && value !== null) value = cloneNode$1(value);
7233 cloned[i2] = value;
7234 }
7235 }
7236 return cloned;
7237 }
7238 var Node$4$1 = /*#__PURE__*/ function() {
7239 function Node2(defaults) {
7240 if (defaults === void 0) defaults = {};
7241 this.raws = {};
7242 this[isClean$2$1] = false;
7243 this[my$2$1] = true;
7244 for (var name in defaults) if (name === "nodes") {
7245 this.nodes = [];
7246 for (var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;) {
7247 var node2 = _step.value;
7248 if (typeof node2.clone === "function") this.append(node2.clone());
7249 else this.append(node2);
7250 }
7251 } else this[name] = defaults[name];
7252 }
7253 var _proto = Node2.prototype;
7254 _proto.addToError = function addToError(error) {
7255 error.postcssNode = this;
7256 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
7257 var s2 = this.source;
7258 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
7259 }
7260 return error;
7261 };
7262 _proto.after = function after(add) {
7263 this.parent.insertAfter(this, add);
7264 return this;
7265 };
7266 _proto.assign = function assign(overrides) {
7267 if (overrides === void 0) overrides = {};
7268 for (var name in overrides) this[name] = overrides[name];
7269 return this;
7270 };
7271 _proto.before = function before(add) {
7272 this.parent.insertBefore(this, add);
7273 return this;
7274 };
7275 _proto.cleanRaws = function cleanRaws(keepBetween) {
7276 delete this.raws.before;
7277 delete this.raws.after;
7278 if (!keepBetween) delete this.raws.between;
7279 };
7280 _proto.clone = function clone(overrides) {
7281 if (overrides === void 0) overrides = {};
7282 var cloned = cloneNode$1(this);
7283 for (var name in overrides) cloned[name] = overrides[name];
7284 return cloned;
7285 };
7286 _proto.cloneAfter = function cloneAfter(overrides) {
7287 if (overrides === void 0) overrides = {};
7288 var cloned = this.clone(overrides);
7289 this.parent.insertAfter(this, cloned);
7290 return cloned;
7291 };
7292 _proto.cloneBefore = function cloneBefore(overrides) {
7293 if (overrides === void 0) overrides = {};
7294 var cloned = this.clone(overrides);
7295 this.parent.insertBefore(this, cloned);
7296 return cloned;
7297 };
7298 _proto.error = function error(message, opts) {
7299 if (opts === void 0) opts = {};
7300 if (this.source) {
7301 var _this_rangeBy = this.rangeBy(opts);
7302 var end = _this_rangeBy.end;
7303 var start = _this_rangeBy.start;
7304 return this.source.input.error(message, {
7305 column: start.column,
7306 line: start.line
7307 }, {
7308 column: end.column,
7309 line: end.line
7310 }, opts);
7311 }
7312 return new CssSyntaxError$2$1(message);
7313 };
7314 _proto.getProxyProcessor = function getProxyProcessor() {
7315 return {
7316 get: function get(node2, prop) {
7317 if (prop === "proxyOf") return node2;
7318 else if (prop === "root") return function() {
7319 return node2.root().toProxy();
7320 };
7321 else return node2[prop];
7322 },
7323 set: function set(node2, prop, value) {
7324 if (node2[prop] === value) return true;
7325 node2[prop] = value;
7326 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || prop === "text") node2.markDirty();
7327 return true;
7328 }
7329 };
7330 };
7331 _proto.markDirty = function markDirty() {
7332 if (this[isClean$2$1]) {
7333 this[isClean$2$1] = false;
7334 var next = this;
7335 while (next = next.parent) next[isClean$2$1] = false;
7336 }
7337 };
7338 _proto.next = function next() {
7339 if (!this.parent) return void 0;
7340 var index2 = this.parent.index(this);
7341 return this.parent.nodes[index2 + 1];
7342 };
7343 _proto.positionBy = function positionBy(opts, stringRepresentation) {
7344 var pos = this.source.start;
7345 if (opts.index) pos = this.positionInside(opts.index, stringRepresentation);
7346 else if (opts.word) {
7347 stringRepresentation = this.toString();
7348 var index2 = stringRepresentation.indexOf(opts.word);
7349 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
7350 }
7351 return pos;
7352 };
7353 _proto.positionInside = function positionInside(index2, stringRepresentation) {
7354 var string = stringRepresentation || this.toString();
7355 var column = this.source.start.column;
7356 var line = this.source.start.line;
7357 for (var i2 = 0; i2 < index2; i2++) if (string[i2] === "\n") {
7358 column = 1;
7359 line += 1;
7360 } else column += 1;
7361 return {
7362 column,
7363 line
7364 };
7365 };
7366 _proto.prev = function prev() {
7367 if (!this.parent) return void 0;
7368 var index2 = this.parent.index(this);
7369 return this.parent.nodes[index2 - 1];
7370 };
7371 _proto.rangeBy = function rangeBy(opts) {
7372 var start = {
7373 column: this.source.start.column,
7374 line: this.source.start.line
7375 };
7376 var end = this.source.end ? {
7377 column: this.source.end.column + 1,
7378 line: this.source.end.line
7379 } : {
7380 column: start.column + 1,
7381 line: start.line
7382 };
7383 if (opts.word) {
7384 var stringRepresentation = this.toString();
7385 var index2 = stringRepresentation.indexOf(opts.word);
7386 if (index2 !== -1) {
7387 start = this.positionInside(index2, stringRepresentation);
7388 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
7389 }
7390 } else {
7391 if (opts.start) start = {
7392 column: opts.start.column,
7393 line: opts.start.line
7394 };
7395 else if (opts.index) start = this.positionInside(opts.index);
7396 if (opts.end) end = {
7397 column: opts.end.column,
7398 line: opts.end.line
7399 };
7400 else if (typeof opts.endIndex === "number") end = this.positionInside(opts.endIndex);
7401 else if (opts.index) end = this.positionInside(opts.index + 1);
7402 }
7403 if (end.line < start.line || end.line === start.line && end.column <= start.column) end = {
7404 column: start.column + 1,
7405 line: start.line
7406 };
7407 return {
7408 end,
7409 start
7410 };
7411 };
7412 _proto.raw = function raw(prop, defaultType) {
7413 return new Stringifier2$1().raw(this, prop, defaultType);
7414 };
7415 _proto.remove = function remove() {
7416 if (this.parent) this.parent.removeChild(this);
7417 this.parent = void 0;
7418 return this;
7419 };
7420 _proto.replaceWith = function replaceWith() {
7421 for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) nodes[_key] = arguments[_key];
7422 if (this.parent) {
7423 var bookmark = this;
7424 var foundSelf = false;
7425 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
7426 var node2 = _step.value;
7427 if (node2 === this) foundSelf = true;
7428 else if (foundSelf) {
7429 this.parent.insertAfter(bookmark, node2);
7430 bookmark = node2;
7431 } else this.parent.insertBefore(bookmark, node2);
7432 }
7433 if (!foundSelf) this.remove();
7434 }
7435 return this;
7436 };
7437 _proto.root = function root() {
7438 var result2 = this;
7439 while (result2.parent && result2.parent.type !== "document") result2 = result2.parent;
7440 return result2;
7441 };
7442 _proto.toJSON = function toJSON(_, inputs) {
7443 var fixed = {};
7444 var emitInputs = inputs == null;
7445 inputs = inputs || /* @__PURE__ */ new Map();
7446 var inputsNextIndex = 0;
7447 for (var name in this) {
7448 if (!Object.prototype.hasOwnProperty.call(this, name)) continue;
7449 if (name === "parent" || name === "proxyCache") continue;
7450 var value = this[name];
7451 if (Array.isArray(value)) fixed[name] = value.map(function(i2) {
7452 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) return i2.toJSON(null, inputs);
7453 else return i2;
7454 });
7455 else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) fixed[name] = value.toJSON(null, inputs);
7456 else if (name === "source") {
7457 var inputId = inputs.get(value.input);
7458 if (inputId == null) {
7459 inputId = inputsNextIndex;
7460 inputs.set(value.input, inputsNextIndex);
7461 inputsNextIndex++;
7462 }
7463 fixed[name] = {
7464 end: value.end,
7465 inputId,
7466 start: value.start
7467 };
7468 } else fixed[name] = value;
7469 }
7470 if (emitInputs) fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
7471 return input2.toJSON();
7472 });
7473 return fixed;
7474 };
7475 _proto.toProxy = function toProxy() {
7476 if (!this.proxyCache) this.proxyCache = new Proxy(this, this.getProxyProcessor());
7477 return this.proxyCache;
7478 };
7479 _proto.toString = function toString(stringifier2) {
7480 if (stringifier2 === void 0) stringifier2 = stringify$3$1;
7481 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
7482 var result2 = "";
7483 stringifier2(this, function(i2) {
7484 result2 += i2;
7485 });
7486 return result2;
7487 };
7488 _proto.warn = function warn(result2, text, opts) {
7489 var data = { node: this };
7490 for (var i2 in opts) data[i2] = opts[i2];
7491 return result2.warn(text, data);
7492 };
7493 _create_class(Node2, [{
7494 key: "proxyOf",
7495 get: function get() {
7496 return this;
7497 }
7498 }]);
7499 return Node2;
7500 }();
7501 var node$1 = Node$4$1;
7502 Node$4$1.default = Node$4$1;
7503 var Declaration$4$1 = /*#__PURE__*/ function(Node$3$1) {
7504 _inherits(Declaration, Node$3$1);
7505 function Declaration(defaults) {
7506 var _this;
7507 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") defaults = _extends({}, defaults, { value: String(defaults.value) });
7508 _this = Node$3$1.call(this, defaults) || this;
7509 _this.type = "decl";
7510 return _this;
7511 }
7512 _create_class(Declaration, [{
7513 key: "variable",
7514 get: function get() {
7515 return this.prop.startsWith("--") || this.prop[0] === "$";
7516 }
7517 }]);
7518 return Declaration;
7519 }(node$1);
7520 var declaration$1 = Declaration$4$1;
7521 Declaration$4$1.default = Declaration$4$1;
7522 var urlAlphabet$1 = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
7523 var nanoid$1$1 = function(size) {
7524 if (size === void 0) size = 21;
7525 var id = "";
7526 var i2 = size;
7527 while (i2--) id += urlAlphabet$1[Math.random() * 64 | 0];
7528 return id;
7529 };
7530 var nonSecure$1 = { nanoid: nanoid$1$1 };
7531 var SourceMapConsumer$2$1 = require$$2$1.SourceMapConsumer;
7532 var SourceMapGenerator$2$1 = require$$2$1.SourceMapGenerator;
7533 var existsSync$1 = require$$2$1.existsSync;
7534 var readFileSync$1 = require$$2$1.readFileSync;
7535 var dirname$1$1 = require$$2$1.dirname;
7536 var join$1 = require$$2$1.join;
7537 function fromBase64$1(str) {
7538 if (Buffer) return Buffer.from(str, "base64").toString();
7539 else return window.atob(str);
7540 }
7541 var PreviousMap$2$1 = /*#__PURE__*/ function() {
7542 function PreviousMap(css, opts) {
7543 if (opts.map === false) return;
7544 this.loadAnnotation(css);
7545 this.inline = this.startWith(this.annotation, "data:");
7546 var prev = opts.map ? opts.map.prev : void 0;
7547 var text = this.loadMap(opts.from, prev);
7548 if (!this.mapFile && opts.from) this.mapFile = opts.from;
7549 if (this.mapFile) this.root = dirname$1$1(this.mapFile);
7550 if (text) this.text = text;
7551 }
7552 var _proto = PreviousMap.prototype;
7553 _proto.consumer = function consumer() {
7554 if (!this.consumerCache) this.consumerCache = new SourceMapConsumer$2$1(this.text);
7555 return this.consumerCache;
7556 };
7557 _proto.decodeInline = function decodeInline(text) {
7558 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
7559 var baseUri = /^data:application\/json;base64,/;
7560 if (/^data:application\/json;charset=utf-?8,/.test(text) || /^data:application\/json,/.test(text)) return decodeURIComponent(text.substr(RegExp.lastMatch.length));
7561 if (baseCharsetUri.test(text) || baseUri.test(text)) return fromBase64$1(text.substr(RegExp.lastMatch.length));
7562 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
7563 throw new Error("Unsupported source map encoding " + encoding);
7564 };
7565 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
7566 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
7567 };
7568 _proto.isMap = function isMap(map) {
7569 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
7570 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
7571 };
7572 _proto.loadAnnotation = function loadAnnotation(css) {
7573 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
7574 if (!comments) return;
7575 var start = css.lastIndexOf(comments.pop());
7576 var end = css.indexOf("*/", start);
7577 if (start > -1 && end > -1) this.annotation = this.getAnnotationURL(css.substring(start, end));
7578 };
7579 _proto.loadFile = function loadFile(path) {
7580 this.root = dirname$1$1(path);
7581 if (existsSync$1(path)) {
7582 this.mapFile = path;
7583 return readFileSync$1(path, "utf-8").toString().trim();
7584 }
7585 };
7586 _proto.loadMap = function loadMap(file, prev) {
7587 if (prev === false) return false;
7588 if (prev) if (typeof prev === "string") return prev;
7589 else if (typeof prev === "function") {
7590 var prevPath = prev(file);
7591 if (prevPath) {
7592 var map = this.loadFile(prevPath);
7593 if (!map) throw new Error("Unable to load previous source map: " + prevPath.toString());
7594 return map;
7595 }
7596 } else if (_instanceof(prev, SourceMapConsumer$2$1)) return SourceMapGenerator$2$1.fromSourceMap(prev).toString();
7597 else if (_instanceof(prev, SourceMapGenerator$2$1)) return prev.toString();
7598 else if (this.isMap(prev)) return JSON.stringify(prev);
7599 else throw new Error("Unsupported previous source map format: " + prev.toString());
7600 else if (this.inline) return this.decodeInline(this.annotation);
7601 else if (this.annotation) {
7602 var map1 = this.annotation;
7603 if (file) map1 = join$1(dirname$1$1(file), map1);
7604 return this.loadFile(map1);
7605 }
7606 };
7607 _proto.startWith = function startWith(string, start) {
7608 if (!string) return false;
7609 return string.substr(0, start.length) === start;
7610 };
7611 _proto.withContent = function withContent() {
7612 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
7613 };
7614 return PreviousMap;
7615 }();
7616 var previousMap$1 = PreviousMap$2$1;
7617 PreviousMap$2$1.default = PreviousMap$2$1;
7618 var SourceMapConsumer$1$1 = require$$2$1.SourceMapConsumer;
7619 var SourceMapGenerator$1$1 = require$$2$1.SourceMapGenerator;
7620 var fileURLToPath$1 = require$$2$1.fileURLToPath;
7621 var pathToFileURL$1$1 = require$$2$1.pathToFileURL;
7622 var isAbsolute$1 = require$$2$1.isAbsolute;
7623 var resolve$1$1 = require$$2$1.resolve;
7624 var nanoid$2 = nonSecure$1.nanoid;
7625 var terminalHighlight$2 = require$$2$1;
7626 var CssSyntaxError$1$1 = cssSyntaxError$1;
7627 var PreviousMap$1$1 = previousMap$1;
7628 var fromOffsetCache$1 = Symbol("fromOffsetCache");
7629 var sourceMapAvailable$1$1 = Boolean(SourceMapConsumer$1$1 && SourceMapGenerator$1$1);
7630 var pathAvailable$1$1 = Boolean(resolve$1$1 && isAbsolute$1);
7631 var Input$4$1 = /*#__PURE__*/ function() {
7632 function Input(css, opts) {
7633 if (opts === void 0) opts = {};
7634 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) throw new Error("PostCSS received " + css + " instead of CSS string");
7635 this.css = css.toString();
7636 if (this.css[0] === "" || this.css[0] === "￾") {
7637 this.hasBOM = true;
7638 this.css = this.css.slice(1);
7639 } else this.hasBOM = false;
7640 if (opts.from) if (!pathAvailable$1$1 || /^\w+:\/\//.test(opts.from) || isAbsolute$1(opts.from)) this.file = opts.from;
7641 else this.file = resolve$1$1(opts.from);
7642 if (pathAvailable$1$1 && sourceMapAvailable$1$1) {
7643 var map = new PreviousMap$1$1(this.css, opts);
7644 if (map.text) {
7645 this.map = map;
7646 var file = map.consumer().file;
7647 if (!this.file && file) this.file = this.mapResolve(file);
7648 }
7649 }
7650 if (!this.file) this.id = "<input css " + nanoid$2(6) + ">";
7651 if (this.map) this.map.file = this.from;
7652 }
7653 var _proto = Input.prototype;
7654 _proto.error = function error(message, line, column, opts) {
7655 if (opts === void 0) opts = {};
7656 var result2;
7657 var endLine;
7658 var endColumn;
7659 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
7660 var start = line;
7661 var end = column;
7662 if (typeof start.offset === "number") {
7663 var pos = this.fromOffset(start.offset);
7664 line = pos.line;
7665 column = pos.col;
7666 } else {
7667 line = start.line;
7668 column = start.column;
7669 }
7670 if (typeof end.offset === "number") {
7671 var pos1 = this.fromOffset(end.offset);
7672 endLine = pos1.line;
7673 endColumn = pos1.col;
7674 } else {
7675 endLine = end.line;
7676 endColumn = end.column;
7677 }
7678 } else if (!column) {
7679 var pos2 = this.fromOffset(line);
7680 line = pos2.line;
7681 column = pos2.col;
7682 }
7683 var origin = this.origin(line, column, endLine, endColumn);
7684 if (origin) result2 = new CssSyntaxError$1$1(message, origin.endLine === void 0 ? origin.line : {
7685 column: origin.column,
7686 line: origin.line
7687 }, origin.endLine === void 0 ? origin.column : {
7688 column: origin.endColumn,
7689 line: origin.endLine
7690 }, origin.source, origin.file, opts.plugin);
7691 else result2 = new CssSyntaxError$1$1(message, endLine === void 0 ? line : {
7692 column,
7693 line
7694 }, endLine === void 0 ? column : {
7695 column: endColumn,
7696 line: endLine
7697 }, this.css, this.file, opts.plugin);
7698 result2.input = {
7699 column,
7700 endColumn,
7701 endLine,
7702 line,
7703 source: this.css
7704 };
7705 if (this.file) {
7706 if (pathToFileURL$1$1) result2.input.url = pathToFileURL$1$1(this.file).toString();
7707 result2.input.file = this.file;
7708 }
7709 return result2;
7710 };
7711 _proto.fromOffset = function fromOffset(offset) {
7712 var lastLine;
7713 var lineToIndex;
7714 if (!this[fromOffsetCache$1]) {
7715 var lines = this.css.split("\n");
7716 lineToIndex = new Array(lines.length);
7717 var prevIndex = 0;
7718 for (var i2 = 0, l2 = lines.length; i2 < l2; i2++) {
7719 lineToIndex[i2] = prevIndex;
7720 prevIndex += lines[i2].length + 1;
7721 }
7722 this[fromOffsetCache$1] = lineToIndex;
7723 } else lineToIndex = this[fromOffsetCache$1];
7724 lastLine = lineToIndex[lineToIndex.length - 1];
7725 var min = 0;
7726 if (offset >= lastLine) min = lineToIndex.length - 1;
7727 else {
7728 var max = lineToIndex.length - 2;
7729 var mid;
7730 while (min < max) {
7731 mid = min + (max - min >> 1);
7732 if (offset < lineToIndex[mid]) max = mid - 1;
7733 else if (offset >= lineToIndex[mid + 1]) min = mid + 1;
7734 else {
7735 min = mid;
7736 break;
7737 }
7738 }
7739 }
7740 return {
7741 col: offset - lineToIndex[min] + 1,
7742 line: min + 1
7743 };
7744 };
7745 _proto.mapResolve = function mapResolve(file) {
7746 if (/^\w+:\/\//.test(file)) return file;
7747 return resolve$1$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
7748 };
7749 _proto.origin = function origin(line, column, endLine, endColumn) {
7750 if (!this.map) return false;
7751 var consumer = this.map.consumer();
7752 var from = consumer.originalPositionFor({
7753 column,
7754 line
7755 });
7756 if (!from.source) return false;
7757 var to;
7758 if (typeof endLine === "number") to = consumer.originalPositionFor({
7759 column: endColumn,
7760 line: endLine
7761 });
7762 var fromUrl;
7763 if (isAbsolute$1(from.source)) fromUrl = pathToFileURL$1$1(from.source);
7764 else fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1$1(this.map.mapFile));
7765 var result2 = {
7766 column: from.column,
7767 endColumn: to && to.column,
7768 endLine: to && to.line,
7769 line: from.line,
7770 url: fromUrl.toString()
7771 };
7772 if (fromUrl.protocol === "file:") if (fileURLToPath$1) result2.file = fileURLToPath$1(fromUrl);
7773 else throw new Error("file: protocol is not available in this PostCSS build");
7774 var source = consumer.sourceContentFor(from.source);
7775 if (source) result2.source = source;
7776 return result2;
7777 };
7778 _proto.toJSON = function toJSON() {
7779 var json = {};
7780 for (var _i = 0, _iter = [
7781 "hasBOM",
7782 "css",
7783 "file",
7784 "id"
7785 ]; _i < _iter.length; _i++) {
7786 var name = _iter[_i];
7787 if (this[name] != null) json[name] = this[name];
7788 }
7789 if (this.map) {
7790 json.map = _extends({}, this.map);
7791 if (json.map.consumerCache) json.map.consumerCache = void 0;
7792 }
7793 return json;
7794 };
7795 _create_class(Input, [{
7796 key: "from",
7797 get: function get() {
7798 return this.file || this.id;
7799 }
7800 }]);
7801 return Input;
7802 }();
7803 var input$1 = Input$4$1;
7804 Input$4$1.default = Input$4$1;
7805 if (terminalHighlight$2 && terminalHighlight$2.registerInput) terminalHighlight$2.registerInput(Input$4$1);
7806 var SourceMapConsumer$3 = require$$2$1.SourceMapConsumer;
7807 var SourceMapGenerator$3 = require$$2$1.SourceMapGenerator;
7808 var dirname$2 = require$$2$1.dirname;
7809 var relative$1 = require$$2$1.relative;
7810 var resolve$2 = require$$2$1.resolve;
7811 var sep$1 = require$$2$1.sep;
7812 var pathToFileURL$2 = require$$2$1.pathToFileURL;
7813 var Input$3$1 = input$1;
7814 var sourceMapAvailable$2 = Boolean(SourceMapConsumer$3 && SourceMapGenerator$3);
7815 var pathAvailable$2 = Boolean(dirname$2 && resolve$2 && relative$1 && sep$1);
7816 var mapGenerator$1 = /* @__PURE__ */ function() {
7817 function MapGenerator(stringify2, root2, opts, cssString) {
7818 this.stringify = stringify2;
7819 this.mapOpts = opts.map || {};
7820 this.root = root2;
7821 this.opts = opts;
7822 this.css = cssString;
7823 this.originalCSS = cssString;
7824 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
7825 this.memoizedFileURLs = /* @__PURE__ */ new Map();
7826 this.memoizedPaths = /* @__PURE__ */ new Map();
7827 this.memoizedURLs = /* @__PURE__ */ new Map();
7828 }
7829 var _proto = MapGenerator.prototype;
7830 _proto.addAnnotation = function addAnnotation() {
7831 var content;
7832 if (this.isInline()) content = "data:application/json;base64," + this.toBase64(this.map.toString());
7833 else if (typeof this.mapOpts.annotation === "string") content = this.mapOpts.annotation;
7834 else if (typeof this.mapOpts.annotation === "function") content = this.mapOpts.annotation(this.opts.to, this.root);
7835 else content = this.outputFile() + ".map";
7836 var eol = "\n";
7837 if (this.css.includes("\r\n")) eol = "\r\n";
7838 this.css += eol + "/*# sourceMappingURL=" + content + " */";
7839 };
7840 _proto.applyPrevMaps = function applyPrevMaps() {
7841 for (var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;) {
7842 var prev = _step.value;
7843 var from = this.toUrl(this.path(prev.file));
7844 var root2 = prev.root || dirname$2(prev.file);
7845 var map = void 0;
7846 if (this.mapOpts.sourcesContent === false) {
7847 map = new SourceMapConsumer$3(prev.text);
7848 if (map.sourcesContent) map.sourcesContent = null;
7849 } else map = prev.consumer();
7850 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
7851 }
7852 };
7853 _proto.clearAnnotation = function clearAnnotation() {
7854 if (this.mapOpts.annotation === false) return;
7855 if (this.root) {
7856 var node2;
7857 for (var i2 = this.root.nodes.length - 1; i2 >= 0; i2--) {
7858 node2 = this.root.nodes[i2];
7859 if (node2.type !== "comment") continue;
7860 if (node2.text.indexOf("# sourceMappingURL=") === 0) this.root.removeChild(i2);
7861 }
7862 } else if (this.css) this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
7863 };
7864 _proto.generate = function generate() {
7865 this.clearAnnotation();
7866 if (pathAvailable$2 && sourceMapAvailable$2 && this.isMap()) return this.generateMap();
7867 else {
7868 var result2 = "";
7869 this.stringify(this.root, function(i2) {
7870 result2 += i2;
7871 });
7872 return [result2];
7873 }
7874 };
7875 _proto.generateMap = function generateMap() {
7876 if (this.root) this.generateString();
7877 else if (this.previous().length === 1) {
7878 var prev = this.previous()[0].consumer();
7879 prev.file = this.outputFile();
7880 this.map = SourceMapGenerator$3.fromSourceMap(prev, { ignoreInvalidMapping: true });
7881 } else {
7882 this.map = new SourceMapGenerator$3({
7883 file: this.outputFile(),
7884 ignoreInvalidMapping: true
7885 });
7886 this.map.addMapping({
7887 generated: {
7888 column: 0,
7889 line: 1
7890 },
7891 original: {
7892 column: 0,
7893 line: 1
7894 },
7895 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
7896 });
7897 }
7898 if (this.isSourcesContent()) this.setSourcesContent();
7899 if (this.root && this.previous().length > 0) this.applyPrevMaps();
7900 if (this.isAnnotation()) this.addAnnotation();
7901 if (this.isInline()) return [this.css];
7902 else return [this.css, this.map];
7903 };
7904 _proto.generateString = function generateString() {
7905 var _this = this;
7906 this.css = "";
7907 this.map = new SourceMapGenerator$3({
7908 file: this.outputFile(),
7909 ignoreInvalidMapping: true
7910 });
7911 var line = 1;
7912 var column = 1;
7913 var noSource = "<no source>";
7914 var mapping = {
7915 generated: {
7916 column: 0,
7917 line: 0
7918 },
7919 original: {
7920 column: 0,
7921 line: 0
7922 },
7923 source: ""
7924 };
7925 var lines;
7926 var last;
7927 this.stringify(this.root, function(str, node2, type) {
7928 _this.css += str;
7929 if (node2 && type !== "end") {
7930 mapping.generated.line = line;
7931 mapping.generated.column = column - 1;
7932 if (node2.source && node2.source.start) {
7933 mapping.source = _this.sourcePath(node2);
7934 mapping.original.line = node2.source.start.line;
7935 mapping.original.column = node2.source.start.column - 1;
7936 _this.map.addMapping(mapping);
7937 } else {
7938 mapping.source = noSource;
7939 mapping.original.line = 1;
7940 mapping.original.column = 0;
7941 _this.map.addMapping(mapping);
7942 }
7943 }
7944 lines = str.match(/\n/g);
7945 if (lines) {
7946 line += lines.length;
7947 last = str.lastIndexOf("\n");
7948 column = str.length - last;
7949 } else column += str.length;
7950 if (node2 && type !== "start") {
7951 var p = node2.parent || { raws: {} };
7952 if (!(node2.type === "decl" || node2.type === "atrule" && !node2.nodes) || node2 !== p.last || p.raws.semicolon) if (node2.source && node2.source.end) {
7953 mapping.source = _this.sourcePath(node2);
7954 mapping.original.line = node2.source.end.line;
7955 mapping.original.column = node2.source.end.column - 1;
7956 mapping.generated.line = line;
7957 mapping.generated.column = column - 2;
7958 _this.map.addMapping(mapping);
7959 } else {
7960 mapping.source = noSource;
7961 mapping.original.line = 1;
7962 mapping.original.column = 0;
7963 mapping.generated.line = line;
7964 mapping.generated.column = column - 1;
7965 _this.map.addMapping(mapping);
7966 }
7967 }
7968 });
7969 };
7970 _proto.isAnnotation = function isAnnotation() {
7971 if (this.isInline()) return true;
7972 if (typeof this.mapOpts.annotation !== "undefined") return this.mapOpts.annotation;
7973 if (this.previous().length) return this.previous().some(function(i2) {
7974 return i2.annotation;
7975 });
7976 return true;
7977 };
7978 _proto.isInline = function isInline() {
7979 if (typeof this.mapOpts.inline !== "undefined") return this.mapOpts.inline;
7980 var annotation = this.mapOpts.annotation;
7981 if (typeof annotation !== "undefined" && annotation !== true) return false;
7982 if (this.previous().length) return this.previous().some(function(i2) {
7983 return i2.inline;
7984 });
7985 return true;
7986 };
7987 _proto.isMap = function isMap() {
7988 if (typeof this.opts.map !== "undefined") return !!this.opts.map;
7989 return this.previous().length > 0;
7990 };
7991 _proto.isSourcesContent = function isSourcesContent() {
7992 if (typeof this.mapOpts.sourcesContent !== "undefined") return this.mapOpts.sourcesContent;
7993 if (this.previous().length) return this.previous().some(function(i2) {
7994 return i2.withContent();
7995 });
7996 return true;
7997 };
7998 _proto.outputFile = function outputFile() {
7999 if (this.opts.to) return this.path(this.opts.to);
8000 else if (this.opts.from) return this.path(this.opts.from);
8001 else return "to.css";
8002 };
8003 _proto.path = function path(file) {
8004 if (this.mapOpts.absolute) return file;
8005 if (file.charCodeAt(0) === 60) return file;
8006 if (/^\w+:\/\//.test(file)) return file;
8007 var cached = this.memoizedPaths.get(file);
8008 if (cached) return cached;
8009 var from = this.opts.to ? dirname$2(this.opts.to) : ".";
8010 if (typeof this.mapOpts.annotation === "string") from = dirname$2(resolve$2(from, this.mapOpts.annotation));
8011 var path = relative$1(from, file);
8012 this.memoizedPaths.set(file, path);
8013 return path;
8014 };
8015 _proto.previous = function previous() {
8016 var _this = this;
8017 if (!this.previousMaps) {
8018 this.previousMaps = [];
8019 if (this.root) this.root.walk(function(node2) {
8020 if (node2.source && node2.source.input.map) {
8021 var map = node2.source.input.map;
8022 if (!_this.previousMaps.includes(map)) _this.previousMaps.push(map);
8023 }
8024 });
8025 else {
8026 var input2 = new Input$3$1(this.originalCSS, this.opts);
8027 if (input2.map) this.previousMaps.push(input2.map);
8028 }
8029 }
8030 return this.previousMaps;
8031 };
8032 _proto.setSourcesContent = function setSourcesContent() {
8033 var _this = this;
8034 var already = {};
8035 if (this.root) this.root.walk(function(node2) {
8036 if (node2.source) {
8037 var from = node2.source.input.from;
8038 if (from && !already[from]) {
8039 already[from] = true;
8040 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
8041 _this.map.setSourceContent(fromUrl, node2.source.input.css);
8042 }
8043 }
8044 });
8045 else if (this.css) {
8046 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
8047 this.map.setSourceContent(from, this.css);
8048 }
8049 };
8050 _proto.sourcePath = function sourcePath(node2) {
8051 if (this.mapOpts.from) return this.toUrl(this.mapOpts.from);
8052 else if (this.usesFileUrls) return this.toFileUrl(node2.source.input.from);
8053 else return this.toUrl(this.path(node2.source.input.from));
8054 };
8055 _proto.toBase64 = function toBase64(str) {
8056 if (Buffer) return Buffer.from(str).toString("base64");
8057 else return window.btoa(unescape(encodeURIComponent(str)));
8058 };
8059 _proto.toFileUrl = function toFileUrl(path) {
8060 var cached = this.memoizedFileURLs.get(path);
8061 if (cached) return cached;
8062 if (pathToFileURL$2) {
8063 var fileURL = pathToFileURL$2(path).toString();
8064 this.memoizedFileURLs.set(path, fileURL);
8065 return fileURL;
8066 } else throw new Error("`map.absolute` option is not available in this PostCSS build");
8067 };
8068 _proto.toUrl = function toUrl(path) {
8069 var cached = this.memoizedURLs.get(path);
8070 if (cached) return cached;
8071 if (sep$1 === "\\") path = path.replace(/\\/g, "/");
8072 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
8073 this.memoizedURLs.set(path, url);
8074 return url;
8075 };
8076 return MapGenerator;
8077 }();
8078 var Comment$4$1 = /*#__PURE__*/ function(Node$2$1) {
8079 _inherits(Comment, Node$2$1);
8080 function Comment(defaults) {
8081 var _this = Node$2$1.call(this, defaults) || this;
8082 _this.type = "comment";
8083 return _this;
8084 }
8085 return Comment;
8086 }(node$1);
8087 var comment$1 = Comment$4$1;
8088 Comment$4$1.default = Comment$4$1;
8089 var isClean$1$1 = symbols$1.isClean;
8090 var my$1$1 = symbols$1.my;
8091 var Declaration$3$1 = declaration$1;
8092 var Comment$3$1 = comment$1;
8093 var Node$1$1 = node$1;
8094 var parse$4$1;
8095 var Rule$4$1;
8096 var AtRule$4$1;
8097 var Root$6$1;
8098 function cleanSource$1(nodes) {
8099 return nodes.map(function(i2) {
8100 if (i2.nodes) i2.nodes = cleanSource$1(i2.nodes);
8101 delete i2.source;
8102 return i2;
8103 });
8104 }
8105 function markDirtyUp$1(node2) {
8106 node2[isClean$1$1] = false;
8107 if (node2.proxyOf.nodes) for (var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;) {
8108 var i2 = _step.value;
8109 markDirtyUp$1(i2);
8110 }
8111 }
8112 var Container$7$1 = /*#__PURE__*/ function(Node$1$1) {
8113 _inherits(Container, Node$1$1);
8114 function Container() {
8115 return Node$1$1.apply(this, arguments) || this;
8116 }
8117 var _proto = Container.prototype;
8118 _proto.append = function append() {
8119 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
8120 for (var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;) {
8121 var child = _step.value;
8122 for (var _iterator1 = _create_for_of_iterator_helper_loose(this.normalize(child, this.last)), _step1; !(_step1 = _iterator1()).done;) {
8123 var node2 = _step1.value;
8124 this.proxyOf.nodes.push(node2);
8125 }
8126 }
8127 this.markDirty();
8128 return this;
8129 };
8130 _proto.cleanRaws = function cleanRaws(keepBetween) {
8131 Node$1$1.prototype.cleanRaws.call(this, keepBetween);
8132 if (this.nodes) for (var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;) _step.value.cleanRaws(keepBetween);
8133 };
8134 _proto.each = function each(callback) {
8135 if (!this.proxyOf.nodes) return void 0;
8136 var iterator = this.getIterator();
8137 var index2;
8138 var result2;
8139 while (this.indexes[iterator] < this.proxyOf.nodes.length) {
8140 index2 = this.indexes[iterator];
8141 result2 = callback(this.proxyOf.nodes[index2], index2);
8142 if (result2 === false) break;
8143 this.indexes[iterator] += 1;
8144 }
8145 delete this.indexes[iterator];
8146 return result2;
8147 };
8148 _proto.every = function every(condition) {
8149 return this.nodes.every(condition);
8150 };
8151 _proto.getIterator = function getIterator() {
8152 if (!this.lastEach) this.lastEach = 0;
8153 if (!this.indexes) this.indexes = {};
8154 this.lastEach += 1;
8155 var iterator = this.lastEach;
8156 this.indexes[iterator] = 0;
8157 return iterator;
8158 };
8159 _proto.getProxyProcessor = function getProxyProcessor() {
8160 return {
8161 get: function get(node2, prop) {
8162 if (prop === "proxyOf") return node2;
8163 else if (!node2[prop]) return node2[prop];
8164 else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) return function() {
8165 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
8166 var _node2;
8167 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
8168 if (typeof i2 === "function") return function(child, index2) {
8169 return i2(child.toProxy(), index2);
8170 };
8171 else return i2;
8172 })));
8173 };
8174 else if (prop === "every" || prop === "some") return function(cb) {
8175 return node2[prop](function(child) {
8176 for (var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) other[_key - 1] = arguments[_key];
8177 return cb.apply(void 0, [].concat([child.toProxy()], other));
8178 });
8179 };
8180 else if (prop === "root") return function() {
8181 return node2.root().toProxy();
8182 };
8183 else if (prop === "nodes") return node2.nodes.map(function(i2) {
8184 return i2.toProxy();
8185 });
8186 else if (prop === "first" || prop === "last") return node2[prop].toProxy();
8187 else return node2[prop];
8188 },
8189 set: function set(node2, prop, value) {
8190 if (node2[prop] === value) return true;
8191 node2[prop] = value;
8192 if (prop === "name" || prop === "params" || prop === "selector") node2.markDirty();
8193 return true;
8194 }
8195 };
8196 };
8197 _proto.index = function index(child) {
8198 if (typeof child === "number") return child;
8199 if (child.proxyOf) child = child.proxyOf;
8200 return this.proxyOf.nodes.indexOf(child);
8201 };
8202 _proto.insertAfter = function insertAfter(exist, add) {
8203 var existIndex = this.index(exist);
8204 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
8205 existIndex = this.index(exist);
8206 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
8207 var node2 = _step.value;
8208 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
8209 }
8210 var index2;
8211 for (var id in this.indexes) {
8212 index2 = this.indexes[id];
8213 if (existIndex < index2) this.indexes[id] = index2 + nodes.length;
8214 }
8215 this.markDirty();
8216 return this;
8217 };
8218 _proto.insertBefore = function insertBefore(exist, add) {
8219 var existIndex = this.index(exist);
8220 var type = existIndex === 0 ? "prepend" : false;
8221 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
8222 existIndex = this.index(exist);
8223 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
8224 var node2 = _step.value;
8225 this.proxyOf.nodes.splice(existIndex, 0, node2);
8226 }
8227 var index2;
8228 for (var id in this.indexes) {
8229 index2 = this.indexes[id];
8230 if (existIndex <= index2) this.indexes[id] = index2 + nodes.length;
8231 }
8232 this.markDirty();
8233 return this;
8234 };
8235 _proto.normalize = function normalize(nodes, sample) {
8236 var _this = this;
8237 if (typeof nodes === "string") nodes = cleanSource$1(parse$4$1(nodes).nodes);
8238 else if (typeof nodes === "undefined") nodes = [];
8239 else if (Array.isArray(nodes)) {
8240 nodes = nodes.slice(0);
8241 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
8242 var i2 = _step.value;
8243 if (i2.parent) i2.parent.removeChild(i2, "ignore");
8244 }
8245 } else if (nodes.type === "root" && this.type !== "document") {
8246 nodes = nodes.nodes.slice(0);
8247 for (var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;) {
8248 var i21 = _step1.value;
8249 if (i21.parent) i21.parent.removeChild(i21, "ignore");
8250 }
8251 } else if (nodes.type) nodes = [nodes];
8252 else if (nodes.prop) {
8253 if (typeof nodes.value === "undefined") throw new Error("Value field is missed in node creation");
8254 else if (typeof nodes.value !== "string") nodes.value = String(nodes.value);
8255 nodes = [new Declaration$3$1(nodes)];
8256 } else if (nodes.selector) nodes = [new Rule$4$1(nodes)];
8257 else if (nodes.name) nodes = [new AtRule$4$1(nodes)];
8258 else if (nodes.text) nodes = [new Comment$3$1(nodes)];
8259 else throw new Error("Unknown node type in node creation");
8260 return nodes.map(function(i2) {
8261 if (!i2[my$1$1]) Container.rebuild(i2);
8262 i2 = i2.proxyOf;
8263 if (i2.parent) i2.parent.removeChild(i2);
8264 if (i2[isClean$1$1]) markDirtyUp$1(i2);
8265 if (typeof i2.raws.before === "undefined") {
8266 if (sample && typeof sample.raws.before !== "undefined") i2.raws.before = sample.raws.before.replace(/\S/g, "");
8267 }
8268 i2.parent = _this.proxyOf;
8269 return i2;
8270 });
8271 };
8272 _proto.prepend = function prepend() {
8273 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
8274 children = children.reverse();
8275 for (var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;) {
8276 var child = _step.value;
8277 var nodes = this.normalize(child, this.first, "prepend").reverse();
8278 for (var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;) {
8279 var node2 = _step1.value;
8280 this.proxyOf.nodes.unshift(node2);
8281 }
8282 for (var id in this.indexes) this.indexes[id] = this.indexes[id] + nodes.length;
8283 }
8284 this.markDirty();
8285 return this;
8286 };
8287 _proto.push = function push(child) {
8288 child.parent = this;
8289 this.proxyOf.nodes.push(child);
8290 return this;
8291 };
8292 _proto.removeAll = function removeAll() {
8293 for (var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;) {
8294 var node2 = _step.value;
8295 node2.parent = void 0;
8296 }
8297 this.proxyOf.nodes = [];
8298 this.markDirty();
8299 return this;
8300 };
8301 _proto.removeChild = function removeChild(child) {
8302 child = this.index(child);
8303 this.proxyOf.nodes[child].parent = void 0;
8304 this.proxyOf.nodes.splice(child, 1);
8305 var index2;
8306 for (var id in this.indexes) {
8307 index2 = this.indexes[id];
8308 if (index2 >= child) this.indexes[id] = index2 - 1;
8309 }
8310 this.markDirty();
8311 return this;
8312 };
8313 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
8314 if (!callback) {
8315 callback = opts;
8316 opts = {};
8317 }
8318 this.walkDecls(function(decl) {
8319 if (opts.props && !opts.props.includes(decl.prop)) return;
8320 if (opts.fast && !decl.value.includes(opts.fast)) return;
8321 decl.value = decl.value.replace(pattern, callback);
8322 });
8323 this.markDirty();
8324 return this;
8325 };
8326 _proto.some = function some(condition) {
8327 return this.nodes.some(condition);
8328 };
8329 _proto.walk = function walk(callback) {
8330 return this.each(function(child, i2) {
8331 var result2;
8332 try {
8333 result2 = callback(child, i2);
8334 } catch (e2) {
8335 throw child.addToError(e2);
8336 }
8337 if (result2 !== false && child.walk) result2 = child.walk(callback);
8338 return result2;
8339 });
8340 };
8341 _proto.walkAtRules = function walkAtRules(name, callback) {
8342 if (!callback) {
8343 callback = name;
8344 return this.walk(function(child, i2) {
8345 if (child.type === "atrule") return callback(child, i2);
8346 });
8347 }
8348 if (_instanceof(name, RegExp)) return this.walk(function(child, i2) {
8349 if (child.type === "atrule" && name.test(child.name)) return callback(child, i2);
8350 });
8351 return this.walk(function(child, i2) {
8352 if (child.type === "atrule" && child.name === name) return callback(child, i2);
8353 });
8354 };
8355 _proto.walkComments = function walkComments(callback) {
8356 return this.walk(function(child, i2) {
8357 if (child.type === "comment") return callback(child, i2);
8358 });
8359 };
8360 _proto.walkDecls = function walkDecls(prop, callback) {
8361 if (!callback) {
8362 callback = prop;
8363 return this.walk(function(child, i2) {
8364 if (child.type === "decl") return callback(child, i2);
8365 });
8366 }
8367 if (_instanceof(prop, RegExp)) return this.walk(function(child, i2) {
8368 if (child.type === "decl" && prop.test(child.prop)) return callback(child, i2);
8369 });
8370 return this.walk(function(child, i2) {
8371 if (child.type === "decl" && child.prop === prop) return callback(child, i2);
8372 });
8373 };
8374 _proto.walkRules = function walkRules(selector, callback) {
8375 if (!callback) {
8376 callback = selector;
8377 return this.walk(function(child, i2) {
8378 if (child.type === "rule") return callback(child, i2);
8379 });
8380 }
8381 if (_instanceof(selector, RegExp)) return this.walk(function(child, i2) {
8382 if (child.type === "rule" && selector.test(child.selector)) return callback(child, i2);
8383 });
8384 return this.walk(function(child, i2) {
8385 if (child.type === "rule" && child.selector === selector) return callback(child, i2);
8386 });
8387 };
8388 _create_class(Container, [{
8389 key: "first",
8390 get: function get() {
8391 if (!this.proxyOf.nodes) return void 0;
8392 return this.proxyOf.nodes[0];
8393 }
8394 }, {
8395 key: "last",
8396 get: function get() {
8397 if (!this.proxyOf.nodes) return void 0;
8398 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
8399 }
8400 }]);
8401 return Container;
8402 }(Node$1$1);
8403 Container$7$1.registerParse = function(dependant) {
8404 parse$4$1 = dependant;
8405 };
8406 Container$7$1.registerRule = function(dependant) {
8407 Rule$4$1 = dependant;
8408 };
8409 Container$7$1.registerAtRule = function(dependant) {
8410 AtRule$4$1 = dependant;
8411 };
8412 Container$7$1.registerRoot = function(dependant) {
8413 Root$6$1 = dependant;
8414 };
8415 var container$1 = Container$7$1;
8416 Container$7$1.default = Container$7$1;
8417 Container$7$1.rebuild = function(node2) {
8418 if (node2.type === "atrule") Object.setPrototypeOf(node2, AtRule$4$1.prototype);
8419 else if (node2.type === "rule") Object.setPrototypeOf(node2, Rule$4$1.prototype);
8420 else if (node2.type === "decl") Object.setPrototypeOf(node2, Declaration$3$1.prototype);
8421 else if (node2.type === "comment") Object.setPrototypeOf(node2, Comment$3$1.prototype);
8422 else if (node2.type === "root") Object.setPrototypeOf(node2, Root$6$1.prototype);
8423 node2[my$1$1] = true;
8424 if (node2.nodes) node2.nodes.forEach(function(child) {
8425 Container$7$1.rebuild(child);
8426 });
8427 };
8428 var Container$6$1 = container$1;
8429 var LazyResult$4$1;
8430 var Processor$3$1;
8431 var Document$3$1 = /*#__PURE__*/ function(Container$6$1) {
8432 _inherits(Document2, Container$6$1);
8433 function Document2(defaults) {
8434 var _this = Container$6$1.call(this, _extends({ type: "document" }, defaults)) || this;
8435 if (!_this.nodes) _this.nodes = [];
8436 return _this;
8437 }
8438 var _proto = Document2.prototype;
8439 _proto.toResult = function toResult(opts) {
8440 if (opts === void 0) opts = {};
8441 return new LazyResult$4$1(new Processor$3$1(), this, opts).stringify();
8442 };
8443 return Document2;
8444 }(Container$6$1);
8445 Document$3$1.registerLazyResult = function(dependant) {
8446 LazyResult$4$1 = dependant;
8447 };
8448 Document$3$1.registerProcessor = function(dependant) {
8449 Processor$3$1 = dependant;
8450 };
8451 var document$1$1 = Document$3$1;
8452 Document$3$1.default = Document$3$1;
8453 var printed$1 = {};
8454 var warnOnce$2$1 = function warnOnce(message) {
8455 if (printed$1[message]) return;
8456 printed$1[message] = true;
8457 if (typeof console !== "undefined" && console.warn) console.warn(message);
8458 };
8459 var Warning$2$1 = /*#__PURE__*/ function() {
8460 function Warning(text, opts) {
8461 if (opts === void 0) opts = {};
8462 this.type = "warning";
8463 this.text = text;
8464 if (opts.node && opts.node.source) {
8465 var range = opts.node.rangeBy(opts);
8466 this.line = range.start.line;
8467 this.column = range.start.column;
8468 this.endLine = range.end.line;
8469 this.endColumn = range.end.column;
8470 }
8471 for (var opt in opts) this[opt] = opts[opt];
8472 }
8473 var _proto = Warning.prototype;
8474 _proto.toString = function toString() {
8475 if (this.node) return this.node.error(this.text, {
8476 index: this.index,
8477 plugin: this.plugin,
8478 word: this.word
8479 }).message;
8480 if (this.plugin) return this.plugin + ": " + this.text;
8481 return this.text;
8482 };
8483 return Warning;
8484 }();
8485 var warning$1 = Warning$2$1;
8486 Warning$2$1.default = Warning$2$1;
8487 var Warning$1$1 = warning$1;
8488 var Result$3$1 = /*#__PURE__*/ function() {
8489 function Result(processor2, root2, opts) {
8490 this.processor = processor2;
8491 this.messages = [];
8492 this.root = root2;
8493 this.opts = opts;
8494 this.css = void 0;
8495 this.map = void 0;
8496 }
8497 var _proto = Result.prototype;
8498 _proto.toString = function toString() {
8499 return this.css;
8500 };
8501 _proto.warn = function warn(text, opts) {
8502 if (opts === void 0) opts = {};
8503 if (!opts.plugin) {
8504 if (this.lastPlugin && this.lastPlugin.postcssPlugin) opts.plugin = this.lastPlugin.postcssPlugin;
8505 }
8506 var warning2 = new Warning$1$1(text, opts);
8507 this.messages.push(warning2);
8508 return warning2;
8509 };
8510 _proto.warnings = function warnings() {
8511 return this.messages.filter(function(i2) {
8512 return i2.type === "warning";
8513 });
8514 };
8515 _create_class(Result, [{
8516 key: "content",
8517 get: function get() {
8518 return this.css;
8519 }
8520 }]);
8521 return Result;
8522 }();
8523 var result$1 = Result$3$1;
8524 Result$3$1.default = Result$3$1;
8525 var SINGLE_QUOTE$1 = "'".charCodeAt(0);
8526 var DOUBLE_QUOTE$1 = "\"".charCodeAt(0);
8527 var BACKSLASH$1 = "\\".charCodeAt(0);
8528 var SLASH$1 = "/".charCodeAt(0);
8529 var NEWLINE$1 = "\n".charCodeAt(0);
8530 var SPACE$1 = " ".charCodeAt(0);
8531 var FEED$1 = "\f".charCodeAt(0);
8532 var TAB$1 = " ".charCodeAt(0);
8533 var CR$1 = "\r".charCodeAt(0);
8534 var OPEN_SQUARE$1 = "[".charCodeAt(0);
8535 var CLOSE_SQUARE$1 = "]".charCodeAt(0);
8536 var OPEN_PARENTHESES$1 = "(".charCodeAt(0);
8537 var CLOSE_PARENTHESES$1 = ")".charCodeAt(0);
8538 var OPEN_CURLY$1 = "{".charCodeAt(0);
8539 var CLOSE_CURLY$1 = "}".charCodeAt(0);
8540 var SEMICOLON$1 = ";".charCodeAt(0);
8541 var ASTERISK$1 = "*".charCodeAt(0);
8542 var COLON$1 = ":".charCodeAt(0);
8543 var AT$1 = "@".charCodeAt(0);
8544 var RE_AT_END$1 = /[\t\n\f\r "#'()/;[\\\]{}]/g;
8545 var RE_WORD_END$1 = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
8546 var RE_BAD_BRACKET$1 = /.[\r\n"'(/\\]/;
8547 var RE_HEX_ESCAPE$1 = /[\da-f]/i;
8548 var tokenize$1 = function tokenizer(input2, options) {
8549 if (options === void 0) options = {};
8550 var css = input2.css.valueOf();
8551 var ignore = options.ignoreErrors;
8552 var code;
8553 var next;
8554 var quote;
8555 var content;
8556 var escape;
8557 var escaped;
8558 var escapePos;
8559 var prev;
8560 var n2;
8561 var currentToken;
8562 var length = css.length;
8563 var pos = 0;
8564 var buffer = [];
8565 var returned = [];
8566 function position() {
8567 return pos;
8568 }
8569 function unclosed(what) {
8570 throw input2.error("Unclosed " + what, pos);
8571 }
8572 function endOfFile() {
8573 return returned.length === 0 && pos >= length;
8574 }
8575 function nextToken(opts) {
8576 if (returned.length) return returned.pop();
8577 if (pos >= length) return;
8578 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
8579 code = css.charCodeAt(pos);
8580 switch (code) {
8581 case NEWLINE$1:
8582 case SPACE$1:
8583 case TAB$1:
8584 case CR$1:
8585 case FEED$1:
8586 next = pos;
8587 do {
8588 next += 1;
8589 code = css.charCodeAt(next);
8590 } while (code === SPACE$1 || code === NEWLINE$1 || code === TAB$1 || code === CR$1 || code === FEED$1);
8591 currentToken = ["space", css.slice(pos, next)];
8592 pos = next - 1;
8593 break;
8594 case OPEN_SQUARE$1:
8595 case CLOSE_SQUARE$1:
8596 case OPEN_CURLY$1:
8597 case CLOSE_CURLY$1:
8598 case COLON$1:
8599 case SEMICOLON$1:
8600 case CLOSE_PARENTHESES$1:
8601 var controlChar = String.fromCharCode(code);
8602 currentToken = [
8603 controlChar,
8604 controlChar,
8605 pos
8606 ];
8607 break;
8608 case OPEN_PARENTHESES$1:
8609 prev = buffer.length ? buffer.pop()[1] : "";
8610 n2 = css.charCodeAt(pos + 1);
8611 if (prev === "url" && n2 !== SINGLE_QUOTE$1 && n2 !== DOUBLE_QUOTE$1 && n2 !== SPACE$1 && n2 !== NEWLINE$1 && n2 !== TAB$1 && n2 !== FEED$1 && n2 !== CR$1) {
8612 next = pos;
8613 do {
8614 escaped = false;
8615 next = css.indexOf(")", next + 1);
8616 if (next === -1) if (ignore || ignoreUnclosed) {
8617 next = pos;
8618 break;
8619 } else unclosed("bracket");
8620 escapePos = next;
8621 while (css.charCodeAt(escapePos - 1) === BACKSLASH$1) {
8622 escapePos -= 1;
8623 escaped = !escaped;
8624 }
8625 } while (escaped);
8626 currentToken = [
8627 "brackets",
8628 css.slice(pos, next + 1),
8629 pos,
8630 next
8631 ];
8632 pos = next;
8633 } else {
8634 next = css.indexOf(")", pos + 1);
8635 content = css.slice(pos, next + 1);
8636 if (next === -1 || RE_BAD_BRACKET$1.test(content)) currentToken = [
8637 "(",
8638 "(",
8639 pos
8640 ];
8641 else {
8642 currentToken = [
8643 "brackets",
8644 content,
8645 pos,
8646 next
8647 ];
8648 pos = next;
8649 }
8650 }
8651 break;
8652 case SINGLE_QUOTE$1:
8653 case DOUBLE_QUOTE$1:
8654 quote = code === SINGLE_QUOTE$1 ? "'" : "\"";
8655 next = pos;
8656 do {
8657 escaped = false;
8658 next = css.indexOf(quote, next + 1);
8659 if (next === -1) if (ignore || ignoreUnclosed) {
8660 next = pos + 1;
8661 break;
8662 } else unclosed("string");
8663 escapePos = next;
8664 while (css.charCodeAt(escapePos - 1) === BACKSLASH$1) {
8665 escapePos -= 1;
8666 escaped = !escaped;
8667 }
8668 } while (escaped);
8669 currentToken = [
8670 "string",
8671 css.slice(pos, next + 1),
8672 pos,
8673 next
8674 ];
8675 pos = next;
8676 break;
8677 case AT$1:
8678 RE_AT_END$1.lastIndex = pos + 1;
8679 RE_AT_END$1.test(css);
8680 if (RE_AT_END$1.lastIndex === 0) next = css.length - 1;
8681 else next = RE_AT_END$1.lastIndex - 2;
8682 currentToken = [
8683 "at-word",
8684 css.slice(pos, next + 1),
8685 pos,
8686 next
8687 ];
8688 pos = next;
8689 break;
8690 case BACKSLASH$1:
8691 next = pos;
8692 escape = true;
8693 while (css.charCodeAt(next + 1) === BACKSLASH$1) {
8694 next += 1;
8695 escape = !escape;
8696 }
8697 code = css.charCodeAt(next + 1);
8698 if (escape && code !== SLASH$1 && code !== SPACE$1 && code !== NEWLINE$1 && code !== TAB$1 && code !== CR$1 && code !== FEED$1) {
8699 next += 1;
8700 if (RE_HEX_ESCAPE$1.test(css.charAt(next))) {
8701 while (RE_HEX_ESCAPE$1.test(css.charAt(next + 1))) next += 1;
8702 if (css.charCodeAt(next + 1) === SPACE$1) next += 1;
8703 }
8704 }
8705 currentToken = [
8706 "word",
8707 css.slice(pos, next + 1),
8708 pos,
8709 next
8710 ];
8711 pos = next;
8712 break;
8713 default:
8714 if (code === SLASH$1 && css.charCodeAt(pos + 1) === ASTERISK$1) {
8715 next = css.indexOf("*/", pos + 2) + 1;
8716 if (next === 0) if (ignore || ignoreUnclosed) next = css.length;
8717 else unclosed("comment");
8718 currentToken = [
8719 "comment",
8720 css.slice(pos, next + 1),
8721 pos,
8722 next
8723 ];
8724 pos = next;
8725 } else {
8726 RE_WORD_END$1.lastIndex = pos + 1;
8727 RE_WORD_END$1.test(css);
8728 if (RE_WORD_END$1.lastIndex === 0) next = css.length - 1;
8729 else next = RE_WORD_END$1.lastIndex - 2;
8730 currentToken = [
8731 "word",
8732 css.slice(pos, next + 1),
8733 pos,
8734 next
8735 ];
8736 buffer.push(currentToken);
8737 pos = next;
8738 }
8739 break;
8740 }
8741 pos++;
8742 return currentToken;
8743 }
8744 function back(token) {
8745 returned.push(token);
8746 }
8747 return {
8748 back,
8749 endOfFile,
8750 nextToken,
8751 position
8752 };
8753 };
8754 var Container$5$1 = container$1;
8755 var AtRule$3$1 = /*#__PURE__*/ function(Container$5$1) {
8756 _inherits(AtRule, Container$5$1);
8757 function AtRule(defaults) {
8758 var _this = Container$5$1.call(this, defaults) || this;
8759 _this.type = "atrule";
8760 return _this;
8761 }
8762 var _proto = AtRule.prototype;
8763 _proto.append = function append() {
8764 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
8765 var _Container$5$1_prototype_append;
8766 if (!this.proxyOf.nodes) this.nodes = [];
8767 return (_Container$5$1_prototype_append = Container$5$1.prototype.append).call.apply(_Container$5$1_prototype_append, [].concat([this], children));
8768 };
8769 _proto.prepend = function prepend() {
8770 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
8771 var _Container$5$1_prototype_prepend;
8772 if (!this.proxyOf.nodes) this.nodes = [];
8773 return (_Container$5$1_prototype_prepend = Container$5$1.prototype.prepend).call.apply(_Container$5$1_prototype_prepend, [].concat([this], children));
8774 };
8775 return AtRule;
8776 }(Container$5$1);
8777 var atRule$1 = AtRule$3$1;
8778 AtRule$3$1.default = AtRule$3$1;
8779 Container$5$1.registerAtRule(AtRule$3$1);
8780 var Container$4$1 = container$1;
8781 var LazyResult$3$1;
8782 var Processor$2$1;
8783 var Root$5$1 = /*#__PURE__*/ function(Container$4$1) {
8784 _inherits(Root, Container$4$1);
8785 function Root(defaults) {
8786 var _this = Container$4$1.call(this, defaults) || this;
8787 _this.type = "root";
8788 if (!_this.nodes) _this.nodes = [];
8789 return _this;
8790 }
8791 var _proto = Root.prototype;
8792 _proto.normalize = function normalize(child, sample, type) {
8793 var nodes = Container$4$1.prototype.normalize.call(this, child);
8794 if (sample) {
8795 if (type === "prepend") if (this.nodes.length > 1) sample.raws.before = this.nodes[1].raws.before;
8796 else delete sample.raws.before;
8797 else if (this.first !== sample) for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
8798 var node2 = _step.value;
8799 node2.raws.before = sample.raws.before;
8800 }
8801 }
8802 return nodes;
8803 };
8804 _proto.removeChild = function removeChild(child, ignore) {
8805 var index2 = this.index(child);
8806 if (!ignore && index2 === 0 && this.nodes.length > 1) this.nodes[1].raws.before = this.nodes[index2].raws.before;
8807 return Container$4$1.prototype.removeChild.call(this, child);
8808 };
8809 _proto.toResult = function toResult(opts) {
8810 if (opts === void 0) opts = {};
8811 return new LazyResult$3$1(new Processor$2$1(), this, opts).stringify();
8812 };
8813 return Root;
8814 }(Container$4$1);
8815 Root$5$1.registerLazyResult = function(dependant) {
8816 LazyResult$3$1 = dependant;
8817 };
8818 Root$5$1.registerProcessor = function(dependant) {
8819 Processor$2$1 = dependant;
8820 };
8821 var root$1 = Root$5$1;
8822 Root$5$1.default = Root$5$1;
8823 Container$4$1.registerRoot(Root$5$1);
8824 var list$2$1 = {
8825 comma: function comma(string) {
8826 return list$2$1.split(string, [","], true);
8827 },
8828 space: function space(string) {
8829 return list$2$1.split(string, [
8830 " ",
8831 "\n",
8832 " "
8833 ]);
8834 },
8835 split: function split(string, separators, last) {
8836 var array = [];
8837 var current = "";
8838 var split = false;
8839 var func = 0;
8840 var inQuote = false;
8841 var prevQuote = "";
8842 var escape = false;
8843 for (var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;) {
8844 var letter = _step.value;
8845 if (escape) escape = false;
8846 else if (letter === "\\") escape = true;
8847 else if (inQuote) {
8848 if (letter === prevQuote) inQuote = false;
8849 } else if (letter === "\"" || letter === "'") {
8850 inQuote = true;
8851 prevQuote = letter;
8852 } else if (letter === "(") func += 1;
8853 else if (letter === ")") {
8854 if (func > 0) func -= 1;
8855 } else if (func === 0) {
8856 if (separators.includes(letter)) split = true;
8857 }
8858 if (split) {
8859 if (current !== "") array.push(current.trim());
8860 current = "";
8861 split = false;
8862 } else current += letter;
8863 }
8864 if (last || current !== "") array.push(current.trim());
8865 return array;
8866 }
8867 };
8868 var list_1$1 = list$2$1;
8869 list$2$1.default = list$2$1;
8870 var Container$3$1 = container$1;
8871 var list$1$1 = list_1$1;
8872 var Rule$3$1 = /*#__PURE__*/ function(Container$3$1) {
8873 _inherits(Rule, Container$3$1);
8874 function Rule(defaults) {
8875 var _this = Container$3$1.call(this, defaults) || this;
8876 _this.type = "rule";
8877 if (!_this.nodes) _this.nodes = [];
8878 return _this;
8879 }
8880 _create_class(Rule, [{
8881 key: "selectors",
8882 get: function get() {
8883 return list$1$1.comma(this.selector);
8884 },
8885 set: function set(values) {
8886 var match = this.selector ? this.selector.match(/,\s*/) : null;
8887 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
8888 this.selector = values.join(sep2);
8889 }
8890 }]);
8891 return Rule;
8892 }(Container$3$1);
8893 var rule$1 = Rule$3$1;
8894 Rule$3$1.default = Rule$3$1;
8895 Container$3$1.registerRule(Rule$3$1);
8896 var Declaration$2$1 = declaration$1;
8897 var tokenizer2$1 = tokenize$1;
8898 var Comment$2$1 = comment$1;
8899 var AtRule$2$1 = atRule$1;
8900 var Root$4$1 = root$1;
8901 var Rule$2$1 = rule$1;
8902 var SAFE_COMMENT_NEIGHBOR$1 = {
8903 empty: true,
8904 space: true
8905 };
8906 function findLastWithPosition$1(tokens) {
8907 for (var i2 = tokens.length - 1; i2 >= 0; i2--) {
8908 var token = tokens[i2];
8909 var pos = token[3] || token[2];
8910 if (pos) return pos;
8911 }
8912 }
8913 var parser$1 = /* @__PURE__ */ function() {
8914 function Parser(input2) {
8915 this.input = input2;
8916 this.root = new Root$4$1();
8917 this.current = this.root;
8918 this.spaces = "";
8919 this.semicolon = false;
8920 this.createTokenizer();
8921 this.root.source = {
8922 input: input2,
8923 start: {
8924 column: 1,
8925 line: 1,
8926 offset: 0
8927 }
8928 };
8929 }
8930 var _proto = Parser.prototype;
8931 _proto.atrule = function atrule(token) {
8932 var node2 = new AtRule$2$1();
8933 node2.name = token[1].slice(1);
8934 if (node2.name === "") this.unnamedAtrule(node2, token);
8935 this.init(node2, token[2]);
8936 var type;
8937 var prev;
8938 var shift;
8939 var last = false;
8940 var open = false;
8941 var params = [];
8942 var brackets = [];
8943 while (!this.tokenizer.endOfFile()) {
8944 token = this.tokenizer.nextToken();
8945 type = token[0];
8946 if (type === "(" || type === "[") brackets.push(type === "(" ? ")" : "]");
8947 else if (type === "{" && brackets.length > 0) brackets.push("}");
8948 else if (type === brackets[brackets.length - 1]) brackets.pop();
8949 if (brackets.length === 0) if (type === ";") {
8950 node2.source.end = this.getPosition(token[2]);
8951 node2.source.end.offset++;
8952 this.semicolon = true;
8953 break;
8954 } else if (type === "{") {
8955 open = true;
8956 break;
8957 } else if (type === "}") {
8958 if (params.length > 0) {
8959 shift = params.length - 1;
8960 prev = params[shift];
8961 while (prev && prev[0] === "space") prev = params[--shift];
8962 if (prev) {
8963 node2.source.end = this.getPosition(prev[3] || prev[2]);
8964 node2.source.end.offset++;
8965 }
8966 }
8967 this.end(token);
8968 break;
8969 } else params.push(token);
8970 else params.push(token);
8971 if (this.tokenizer.endOfFile()) {
8972 last = true;
8973 break;
8974 }
8975 }
8976 node2.raws.between = this.spacesAndCommentsFromEnd(params);
8977 if (params.length) {
8978 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
8979 this.raw(node2, "params", params);
8980 if (last) {
8981 token = params[params.length - 1];
8982 node2.source.end = this.getPosition(token[3] || token[2]);
8983 node2.source.end.offset++;
8984 this.spaces = node2.raws.between;
8985 node2.raws.between = "";
8986 }
8987 } else {
8988 node2.raws.afterName = "";
8989 node2.params = "";
8990 }
8991 if (open) {
8992 node2.nodes = [];
8993 this.current = node2;
8994 }
8995 };
8996 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
8997 var colon = this.colon(tokens);
8998 if (colon === false) return;
8999 var founded = 0;
9000 var token;
9001 for (var j = colon - 1; j >= 0; j--) {
9002 token = tokens[j];
9003 if (token[0] !== "space") {
9004 founded += 1;
9005 if (founded === 2) break;
9006 }
9007 }
9008 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
9009 };
9010 _proto.colon = function colon(tokens) {
9011 var brackets = 0;
9012 var token;
9013 var type;
9014 var prev;
9015 for (var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;) {
9016 var _step_value = _step.value;
9017 var i2 = _step_value[0];
9018 token = _step_value[1];
9019 type = token[0];
9020 if (type === "(") brackets += 1;
9021 if (type === ")") brackets -= 1;
9022 if (brackets === 0 && type === ":") if (!prev) this.doubleColon(token);
9023 else if (prev[0] === "word" && prev[1] === "progid") continue;
9024 else return i2;
9025 prev = token;
9026 }
9027 return false;
9028 };
9029 _proto.comment = function comment(token) {
9030 var node2 = new Comment$2$1();
9031 this.init(node2, token[2]);
9032 node2.source.end = this.getPosition(token[3] || token[2]);
9033 node2.source.end.offset++;
9034 var text = token[1].slice(2, -2);
9035 if (/^\s*$/.test(text)) {
9036 node2.text = "";
9037 node2.raws.left = text;
9038 node2.raws.right = "";
9039 } else {
9040 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
9041 node2.text = match[2];
9042 node2.raws.left = match[1];
9043 node2.raws.right = match[3];
9044 }
9045 };
9046 _proto.createTokenizer = function createTokenizer() {
9047 this.tokenizer = tokenizer2$1(this.input);
9048 };
9049 _proto.decl = function decl(tokens, customProperty) {
9050 var node2 = new Declaration$2$1();
9051 this.init(node2, tokens[0][2]);
9052 var last = tokens[tokens.length - 1];
9053 if (last[0] === ";") {
9054 this.semicolon = true;
9055 tokens.pop();
9056 }
9057 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition$1(tokens));
9058 node2.source.end.offset++;
9059 while (tokens[0][0] !== "word") {
9060 if (tokens.length === 1) this.unknownWord(tokens);
9061 node2.raws.before += tokens.shift()[1];
9062 }
9063 node2.source.start = this.getPosition(tokens[0][2]);
9064 node2.prop = "";
9065 while (tokens.length) {
9066 var type = tokens[0][0];
9067 if (type === ":" || type === "space" || type === "comment") break;
9068 node2.prop += tokens.shift()[1];
9069 }
9070 node2.raws.between = "";
9071 var token;
9072 while (tokens.length) {
9073 token = tokens.shift();
9074 if (token[0] === ":") {
9075 node2.raws.between += token[1];
9076 break;
9077 } else {
9078 if (token[0] === "word" && /\w/.test(token[1])) this.unknownWord([token]);
9079 node2.raws.between += token[1];
9080 }
9081 }
9082 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
9083 node2.raws.before += node2.prop[0];
9084 node2.prop = node2.prop.slice(1);
9085 }
9086 var firstSpaces = [];
9087 var next;
9088 while (tokens.length) {
9089 next = tokens[0][0];
9090 if (next !== "space" && next !== "comment") break;
9091 firstSpaces.push(tokens.shift());
9092 }
9093 this.precheckMissedSemicolon(tokens);
9094 for (var i2 = tokens.length - 1; i2 >= 0; i2--) {
9095 token = tokens[i2];
9096 if (token[1].toLowerCase() === "!important") {
9097 node2.important = true;
9098 var string = this.stringFrom(tokens, i2);
9099 string = this.spacesFromEnd(tokens) + string;
9100 if (string !== " !important") node2.raws.important = string;
9101 break;
9102 } else if (token[1].toLowerCase() === "important") {
9103 var cache = tokens.slice(0);
9104 var str = "";
9105 for (var j = i2; j > 0; j--) {
9106 var type1 = cache[j][0];
9107 if (str.trim().indexOf("!") === 0 && type1 !== "space") break;
9108 str = cache.pop()[1] + str;
9109 }
9110 if (str.trim().indexOf("!") === 0) {
9111 node2.important = true;
9112 node2.raws.important = str;
9113 tokens = cache;
9114 }
9115 }
9116 if (token[0] !== "space" && token[0] !== "comment") break;
9117 }
9118 if (tokens.some(function(i2) {
9119 return i2[0] !== "space" && i2[0] !== "comment";
9120 })) {
9121 node2.raws.between += firstSpaces.map(function(i2) {
9122 return i2[1];
9123 }).join("");
9124 firstSpaces = [];
9125 }
9126 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
9127 if (node2.value.includes(":") && !customProperty) this.checkMissedSemicolon(tokens);
9128 };
9129 _proto.doubleColon = function doubleColon(token) {
9130 throw this.input.error("Double colon", { offset: token[2] }, { offset: token[2] + token[1].length });
9131 };
9132 _proto.emptyRule = function emptyRule(token) {
9133 var node2 = new Rule$2$1();
9134 this.init(node2, token[2]);
9135 node2.selector = "";
9136 node2.raws.between = "";
9137 this.current = node2;
9138 };
9139 _proto.end = function end(token) {
9140 if (this.current.nodes && this.current.nodes.length) this.current.raws.semicolon = this.semicolon;
9141 this.semicolon = false;
9142 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
9143 this.spaces = "";
9144 if (this.current.parent) {
9145 this.current.source.end = this.getPosition(token[2]);
9146 this.current.source.end.offset++;
9147 this.current = this.current.parent;
9148 } else this.unexpectedClose(token);
9149 };
9150 _proto.endFile = function endFile() {
9151 if (this.current.parent) this.unclosedBlock();
9152 if (this.current.nodes && this.current.nodes.length) this.current.raws.semicolon = this.semicolon;
9153 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
9154 this.root.source.end = this.getPosition(this.tokenizer.position());
9155 };
9156 _proto.freeSemicolon = function freeSemicolon(token) {
9157 this.spaces += token[1];
9158 if (this.current.nodes) {
9159 var prev = this.current.nodes[this.current.nodes.length - 1];
9160 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
9161 prev.raws.ownSemicolon = this.spaces;
9162 this.spaces = "";
9163 }
9164 }
9165 };
9166 _proto.getPosition = function getPosition(offset) {
9167 var pos = this.input.fromOffset(offset);
9168 return {
9169 column: pos.col,
9170 line: pos.line,
9171 offset
9172 };
9173 };
9174 _proto.init = function init(node2, offset) {
9175 this.current.push(node2);
9176 node2.source = {
9177 input: this.input,
9178 start: this.getPosition(offset)
9179 };
9180 node2.raws.before = this.spaces;
9181 this.spaces = "";
9182 if (node2.type !== "comment") this.semicolon = false;
9183 };
9184 _proto.other = function other(start) {
9185 var end = false;
9186 var type = null;
9187 var colon = false;
9188 var bracket = null;
9189 var brackets = [];
9190 var customProperty = start[1].startsWith("--");
9191 var tokens = [];
9192 var token = start;
9193 while (token) {
9194 type = token[0];
9195 tokens.push(token);
9196 if (type === "(" || type === "[") {
9197 if (!bracket) bracket = token;
9198 brackets.push(type === "(" ? ")" : "]");
9199 } else if (customProperty && colon && type === "{") {
9200 if (!bracket) bracket = token;
9201 brackets.push("}");
9202 } else if (brackets.length === 0) {
9203 if (type === ";") if (colon) {
9204 this.decl(tokens, customProperty);
9205 return;
9206 } else break;
9207 else if (type === "{") {
9208 this.rule(tokens);
9209 return;
9210 } else if (type === "}") {
9211 this.tokenizer.back(tokens.pop());
9212 end = true;
9213 break;
9214 } else if (type === ":") colon = true;
9215 } else if (type === brackets[brackets.length - 1]) {
9216 brackets.pop();
9217 if (brackets.length === 0) bracket = null;
9218 }
9219 token = this.tokenizer.nextToken();
9220 }
9221 if (this.tokenizer.endOfFile()) end = true;
9222 if (brackets.length > 0) this.unclosedBracket(bracket);
9223 if (end && colon) {
9224 if (!customProperty) while (tokens.length) {
9225 token = tokens[tokens.length - 1][0];
9226 if (token !== "space" && token !== "comment") break;
9227 this.tokenizer.back(tokens.pop());
9228 }
9229 this.decl(tokens, customProperty);
9230 } else this.unknownWord(tokens);
9231 };
9232 _proto.parse = function parse() {
9233 var token;
9234 while (!this.tokenizer.endOfFile()) {
9235 token = this.tokenizer.nextToken();
9236 switch (token[0]) {
9237 case "space":
9238 this.spaces += token[1];
9239 break;
9240 case ";":
9241 this.freeSemicolon(token);
9242 break;
9243 case "}":
9244 this.end(token);
9245 break;
9246 case "comment":
9247 this.comment(token);
9248 break;
9249 case "at-word":
9250 this.atrule(token);
9251 break;
9252 case "{":
9253 this.emptyRule(token);
9254 break;
9255 default:
9256 this.other(token);
9257 break;
9258 }
9259 }
9260 this.endFile();
9261 };
9262 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
9263 _proto.raw = function raw(node2, prop, tokens, customProperty) {
9264 var token;
9265 var type;
9266 var length = tokens.length;
9267 var value = "";
9268 var clean = true;
9269 var next;
9270 var prev;
9271 for (var i2 = 0; i2 < length; i2 += 1) {
9272 token = tokens[i2];
9273 type = token[0];
9274 if (type === "space" && i2 === length - 1 && !customProperty) clean = false;
9275 else if (type === "comment") {
9276 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
9277 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
9278 if (!SAFE_COMMENT_NEIGHBOR$1[prev] && !SAFE_COMMENT_NEIGHBOR$1[next]) if (value.slice(-1) === ",") clean = false;
9279 else value += token[1];
9280 else clean = false;
9281 } else value += token[1];
9282 }
9283 if (!clean) {
9284 var raw = tokens.reduce(function(all, i2) {
9285 return all + i2[1];
9286 }, "");
9287 node2.raws[prop] = {
9288 raw,
9289 value
9290 };
9291 }
9292 node2[prop] = value;
9293 };
9294 _proto.rule = function rule(tokens) {
9295 tokens.pop();
9296 var node2 = new Rule$2$1();
9297 this.init(node2, tokens[0][2]);
9298 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
9299 this.raw(node2, "selector", tokens);
9300 this.current = node2;
9301 };
9302 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
9303 var lastTokenType;
9304 var spaces = "";
9305 while (tokens.length) {
9306 lastTokenType = tokens[tokens.length - 1][0];
9307 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
9308 spaces = tokens.pop()[1] + spaces;
9309 }
9310 return spaces;
9311 };
9312 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
9313 var next;
9314 var spaces = "";
9315 while (tokens.length) {
9316 next = tokens[0][0];
9317 if (next !== "space" && next !== "comment") break;
9318 spaces += tokens.shift()[1];
9319 }
9320 return spaces;
9321 };
9322 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
9323 var lastTokenType;
9324 var spaces = "";
9325 while (tokens.length) {
9326 lastTokenType = tokens[tokens.length - 1][0];
9327 if (lastTokenType !== "space") break;
9328 spaces = tokens.pop()[1] + spaces;
9329 }
9330 return spaces;
9331 };
9332 _proto.stringFrom = function stringFrom(tokens, from) {
9333 var result2 = "";
9334 for (var i2 = from; i2 < tokens.length; i2++) result2 += tokens[i2][1];
9335 tokens.splice(from, tokens.length - from);
9336 return result2;
9337 };
9338 _proto.unclosedBlock = function unclosedBlock() {
9339 var pos = this.current.source.start;
9340 throw this.input.error("Unclosed block", pos.line, pos.column);
9341 };
9342 _proto.unclosedBracket = function unclosedBracket(bracket) {
9343 throw this.input.error("Unclosed bracket", { offset: bracket[2] }, { offset: bracket[2] + 1 });
9344 };
9345 _proto.unexpectedClose = function unexpectedClose(token) {
9346 throw this.input.error("Unexpected }", { offset: token[2] }, { offset: token[2] + 1 });
9347 };
9348 _proto.unknownWord = function unknownWord(tokens) {
9349 throw this.input.error("Unknown word", { offset: tokens[0][2] }, { offset: tokens[0][2] + tokens[0][1].length });
9350 };
9351 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
9352 throw this.input.error("At-rule without name", { offset: token[2] }, { offset: token[2] + token[1].length });
9353 };
9354 return Parser;
9355 }();
9356 var Container$2$1 = container$1;
9357 var Parser2$1 = parser$1;
9358 var Input$2$1 = input$1;
9359 function parse$3$1(css, opts) {
9360 var parser2 = new Parser2$1(new Input$2$1(css, opts));
9361 try {
9362 parser2.parse();
9363 } catch (e2) {
9364 if (e2.name === "CssSyntaxError" && opts && opts.from) {
9365 if (/\.scss$/i.test(opts.from)) e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
9366 else if (/\.sass/i.test(opts.from)) e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
9367 else if (/\.less$/i.test(opts.from)) e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
9368 }
9369 throw e2;
9370 }
9371 return parser2.root;
9372 }
9373 var parse_1$1 = parse$3$1;
9374 parse$3$1.default = parse$3$1;
9375 Container$2$1.registerParse(parse$3$1);
9376 var isClean$3 = symbols$1.isClean;
9377 var my$3 = symbols$1.my;
9378 var MapGenerator$1$1 = mapGenerator$1;
9379 var stringify$2$1 = stringify_1$1;
9380 var Container$1$1 = container$1;
9381 var Document$2$1 = document$1$1;
9382 var warnOnce$1$1 = warnOnce$2$1;
9383 var Result$2$1 = result$1;
9384 var parse$2$1 = parse_1$1;
9385 var Root$3$1 = root$1;
9386 var TYPE_TO_CLASS_NAME$1 = {
9387 atrule: "AtRule",
9388 comment: "Comment",
9389 decl: "Declaration",
9390 document: "Document",
9391 root: "Root",
9392 rule: "Rule"
9393 };
9394 var PLUGIN_PROPS$1 = {
9395 AtRule: true,
9396 AtRuleExit: true,
9397 Comment: true,
9398 CommentExit: true,
9399 Declaration: true,
9400 DeclarationExit: true,
9401 Document: true,
9402 DocumentExit: true,
9403 Once: true,
9404 OnceExit: true,
9405 postcssPlugin: true,
9406 prepare: true,
9407 Root: true,
9408 RootExit: true,
9409 Rule: true,
9410 RuleExit: true
9411 };
9412 var NOT_VISITORS$1 = {
9413 Once: true,
9414 postcssPlugin: true,
9415 prepare: true
9416 };
9417 var CHILDREN$1 = 0;
9418 function isPromise$1(obj) {
9419 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
9420 }
9421 function getEvents$1(node2) {
9422 var key = false;
9423 var type = TYPE_TO_CLASS_NAME$1[node2.type];
9424 if (node2.type === "decl") key = node2.prop.toLowerCase();
9425 else if (node2.type === "atrule") key = node2.name.toLowerCase();
9426 if (key && node2.append) return [
9427 type,
9428 type + "-" + key,
9429 CHILDREN$1,
9430 type + "Exit",
9431 type + "Exit-" + key
9432 ];
9433 else if (key) return [
9434 type,
9435 type + "-" + key,
9436 type + "Exit",
9437 type + "Exit-" + key
9438 ];
9439 else if (node2.append) return [
9440 type,
9441 CHILDREN$1,
9442 type + "Exit"
9443 ];
9444 else return [type, type + "Exit"];
9445 }
9446 function toStack$1(node2) {
9447 var events;
9448 if (node2.type === "document") events = [
9449 "Document",
9450 CHILDREN$1,
9451 "DocumentExit"
9452 ];
9453 else if (node2.type === "root") events = [
9454 "Root",
9455 CHILDREN$1,
9456 "RootExit"
9457 ];
9458 else events = getEvents$1(node2);
9459 return {
9460 eventIndex: 0,
9461 events,
9462 iterator: 0,
9463 node: node2,
9464 visitorIndex: 0,
9465 visitors: []
9466 };
9467 }
9468 function cleanMarks$1(node2) {
9469 node2[isClean$3] = false;
9470 if (node2.nodes) node2.nodes.forEach(function(i2) {
9471 return cleanMarks$1(i2);
9472 });
9473 return node2;
9474 }
9475 var postcss$2$1 = {};
9476 var LazyResult$2$1 = /*#__PURE__*/ function() {
9477 function LazyResult(processor2, css, opts) {
9478 var _this = this;
9479 this.stringified = false;
9480 this.processed = false;
9481 var root2;
9482 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) root2 = cleanMarks$1(css);
9483 else if (_instanceof(css, LazyResult) || _instanceof(css, Result$2$1)) {
9484 root2 = cleanMarks$1(css.root);
9485 if (css.map) {
9486 if (typeof opts.map === "undefined") opts.map = {};
9487 if (!opts.map.inline) opts.map.inline = false;
9488 opts.map.prev = css.map;
9489 }
9490 } else {
9491 var parser2 = parse$2$1;
9492 if (opts.syntax) parser2 = opts.syntax.parse;
9493 if (opts.parser) parser2 = opts.parser;
9494 if (parser2.parse) parser2 = parser2.parse;
9495 try {
9496 root2 = parser2(css, opts);
9497 } catch (error) {
9498 this.processed = true;
9499 this.error = error;
9500 }
9501 if (root2 && !root2[my$3]) Container$1$1.rebuild(root2);
9502 }
9503 this.result = new Result$2$1(processor2, root2, opts);
9504 this.helpers = _extends({}, postcss$2$1, {
9505 postcss: postcss$2$1,
9506 result: this.result
9507 });
9508 this.plugins = this.processor.plugins.map(function(plugin22) {
9509 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) return _extends({}, plugin22, plugin22.prepare(_this.result));
9510 else return plugin22;
9511 });
9512 }
9513 var _proto = LazyResult.prototype;
9514 _proto.async = function async() {
9515 if (this.error) return Promise.reject(this.error);
9516 if (this.processed) return Promise.resolve(this.result);
9517 if (!this.processing) this.processing = this.runAsync();
9518 return this.processing;
9519 };
9520 _proto.catch = function _catch(onRejected) {
9521 return this.async().catch(onRejected);
9522 };
9523 _proto.finally = function _finally(onFinally) {
9524 return this.async().then(onFinally, onFinally);
9525 };
9526 _proto.getAsyncError = function getAsyncError() {
9527 throw new Error("Use process(css).then(cb) to work with async plugins");
9528 };
9529 _proto.handleError = function handleError(error, node2) {
9530 var plugin22 = this.result.lastPlugin;
9531 try {
9532 if (node2) node2.addToError(error);
9533 this.error = error;
9534 if (error.name === "CssSyntaxError" && !error.plugin) {
9535 error.plugin = plugin22.postcssPlugin;
9536 error.setMessage();
9537 } else if (plugin22.postcssVersion) {
9538 var pluginName = plugin22.postcssPlugin;
9539 var pluginVer = plugin22.postcssVersion;
9540 var runtimeVer = this.result.processor.version;
9541 var a2 = pluginVer.split(".");
9542 var b = runtimeVer.split(".");
9543 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) console.error("Unknown error from PostCSS plugin. Your current PostCSS version is " + runtimeVer + ", but " + pluginName + " uses " + pluginVer + ". Perhaps this is the source of the error below.");
9544 }
9545 } catch (err) {
9546 if (console && console.error) console.error(err);
9547 }
9548 return error;
9549 };
9550 _proto.prepareVisitors = function prepareVisitors() {
9551 var _this = this;
9552 this.listeners = {};
9553 var add = function(plugin22, type, cb) {
9554 if (!_this.listeners[type]) _this.listeners[type] = [];
9555 _this.listeners[type].push([plugin22, cb]);
9556 };
9557 for (var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;) {
9558 var plugin22 = _step.value;
9559 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") for (var event in plugin22) {
9560 if (!PLUGIN_PROPS$1[event] && /^[A-Z]/.test(event)) throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
9561 if (!NOT_VISITORS$1[event]) {
9562 if (_type_of(plugin22[event]) === "object") for (var filter in plugin22[event]) if (filter === "*") add(plugin22, event, plugin22[event][filter]);
9563 else add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
9564 else if (typeof plugin22[event] === "function") add(plugin22, event, plugin22[event]);
9565 }
9566 }
9567 }
9568 this.hasListener = Object.keys(this.listeners).length > 0;
9569 };
9570 _proto.runAsync = function runAsync() {
9571 var _this = this;
9572 return _async_to_generator(function() {
9573 var i2;
9574 var plugin22;
9575 var promise;
9576 var error;
9577 var root2;
9578 var stack;
9579 var promise1;
9580 var e2;
9581 var node2;
9582 var _loop;
9583 var _iterator;
9584 var _step;
9585 return _ts_generator(this, function(_state) {
9586 switch (_state.label) {
9587 case 0:
9588 _this.plugin = 0;
9589 i2 = 0;
9590 _state.label = 1;
9591 case 1:
9592 if (!(i2 < _this.plugins.length)) return [3, 6];
9593 plugin22 = _this.plugins[i2];
9594 promise = _this.runOnRoot(plugin22);
9595 if (!isPromise$1(promise)) return [3, 5];
9596 _state.label = 2;
9597 case 2:
9598 _state.trys.push([
9599 2,
9600 4,
9601 ,
9602 5
9603 ]);
9604 return [4, promise];
9605 case 3:
9606 _state.sent();
9607 return [3, 5];
9608 case 4:
9609 error = _state.sent();
9610 throw _this.handleError(error);
9611 case 5:
9612 i2++;
9613 return [3, 1];
9614 case 6:
9615 _this.prepareVisitors();
9616 if (!_this.hasListener) return [3, 18];
9617 root2 = _this.result.root;
9618 _state.label = 7;
9619 case 7:
9620 if (!!root2[isClean$3]) return [3, 14];
9621 root2[isClean$3] = true;
9622 stack = [toStack$1(root2)];
9623 _state.label = 8;
9624 case 8:
9625 if (!(stack.length > 0)) return [3, 13];
9626 promise1 = _this.visitTick(stack);
9627 if (!isPromise$1(promise1)) return [3, 12];
9628 _state.label = 9;
9629 case 9:
9630 _state.trys.push([
9631 9,
9632 11,
9633 ,
9634 12
9635 ]);
9636 return [4, promise1];
9637 case 10:
9638 _state.sent();
9639 return [3, 12];
9640 case 11:
9641 e2 = _state.sent();
9642 node2 = stack[stack.length - 1].node;
9643 throw _this.handleError(e2, node2);
9644 case 12: return [3, 8];
9645 case 13: return [3, 7];
9646 case 14:
9647 if (!_this.listeners.OnceExit) return [3, 18];
9648 _loop = function() {
9649 var _step_value;
9650 var plugin22;
9651 var visitor;
9652 var roots;
9653 var e2;
9654 return _ts_generator(this, function(_state) {
9655 switch (_state.label) {
9656 case 0:
9657 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
9658 _this.result.lastPlugin = plugin22;
9659 _state.label = 1;
9660 case 1:
9661 _state.trys.push([
9662 1,
9663 6,
9664 ,
9665 7
9666 ]);
9667 if (!(root2.type === "document")) return [3, 3];
9668 roots = root2.nodes.map(function(subRoot) {
9669 return visitor(subRoot, _this.helpers);
9670 });
9671 return [4, Promise.all(roots)];
9672 case 2:
9673 _state.sent();
9674 return [3, 5];
9675 case 3: return [4, visitor(root2, _this.helpers)];
9676 case 4:
9677 _state.sent();
9678 _state.label = 5;
9679 case 5: return [3, 7];
9680 case 6:
9681 e2 = _state.sent();
9682 throw _this.handleError(e2);
9683 case 7: return [2];
9684 }
9685 });
9686 };
9687 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
9688 _state.label = 15;
9689 case 15:
9690 if (!!(_step = _iterator()).done) return [3, 18];
9691 return [5, _ts_values(_loop())];
9692 case 16:
9693 _state.sent();
9694 _state.label = 17;
9695 case 17: return [3, 15];
9696 case 18:
9697 _this.processed = true;
9698 return [2, _this.stringify()];
9699 }
9700 });
9701 })();
9702 };
9703 _proto.runOnRoot = function runOnRoot(plugin22) {
9704 var _this = this;
9705 this.result.lastPlugin = plugin22;
9706 try {
9707 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
9708 if (this.result.root.type === "document") {
9709 var roots = this.result.root.nodes.map(function(root2) {
9710 return plugin22.Once(root2, _this.helpers);
9711 });
9712 if (isPromise$1(roots[0])) return Promise.all(roots);
9713 return roots;
9714 }
9715 return plugin22.Once(this.result.root, this.helpers);
9716 } else if (typeof plugin22 === "function") return plugin22(this.result.root, this.result);
9717 } catch (error) {
9718 throw this.handleError(error);
9719 }
9720 };
9721 _proto.stringify = function stringify() {
9722 if (this.error) throw this.error;
9723 if (this.stringified) return this.result;
9724 this.stringified = true;
9725 this.sync();
9726 var opts = this.result.opts;
9727 var str = stringify$2$1;
9728 if (opts.syntax) str = opts.syntax.stringify;
9729 if (opts.stringifier) str = opts.stringifier;
9730 if (str.stringify) str = str.stringify;
9731 var data = new MapGenerator$1$1(str, this.result.root, this.result.opts).generate();
9732 this.result.css = data[0];
9733 this.result.map = data[1];
9734 return this.result;
9735 };
9736 _proto.sync = function sync() {
9737 if (this.error) throw this.error;
9738 if (this.processed) return this.result;
9739 this.processed = true;
9740 if (this.processing) throw this.getAsyncError();
9741 for (var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;) {
9742 var plugin22 = _step.value;
9743 if (isPromise$1(this.runOnRoot(plugin22))) throw this.getAsyncError();
9744 }
9745 this.prepareVisitors();
9746 if (this.hasListener) {
9747 var root2 = this.result.root;
9748 while (!root2[isClean$3]) {
9749 root2[isClean$3] = true;
9750 this.walkSync(root2);
9751 }
9752 if (this.listeners.OnceExit) if (root2.type === "document") for (var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;) {
9753 var subRoot = _step1.value;
9754 this.visitSync(this.listeners.OnceExit, subRoot);
9755 }
9756 else this.visitSync(this.listeners.OnceExit, root2);
9757 }
9758 return this.result;
9759 };
9760 _proto.then = function then(onFulfilled, onRejected) {
9761 if (!("from" in this.opts)) warnOnce$1$1("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.");
9762 return this.async().then(onFulfilled, onRejected);
9763 };
9764 _proto.toString = function toString() {
9765 return this.css;
9766 };
9767 _proto.visitSync = function visitSync(visitors, node2) {
9768 for (var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;) {
9769 var _step_value = _step.value;
9770 var plugin22 = _step_value[0];
9771 var visitor = _step_value[1];
9772 this.result.lastPlugin = plugin22;
9773 var promise = void 0;
9774 try {
9775 promise = visitor(node2, this.helpers);
9776 } catch (e2) {
9777 throw this.handleError(e2, node2.proxyOf);
9778 }
9779 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) return true;
9780 if (isPromise$1(promise)) throw this.getAsyncError();
9781 }
9782 };
9783 _proto.visitTick = function visitTick(stack) {
9784 var visit2 = stack[stack.length - 1];
9785 var node2 = visit2.node;
9786 var visitors = visit2.visitors;
9787 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
9788 stack.pop();
9789 return;
9790 }
9791 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
9792 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex];
9793 var plugin22 = _visitors_visit2_visitorIndex[0];
9794 var visitor = _visitors_visit2_visitorIndex[1];
9795 visit2.visitorIndex += 1;
9796 if (visit2.visitorIndex === visitors.length) {
9797 visit2.visitors = [];
9798 visit2.visitorIndex = 0;
9799 }
9800 this.result.lastPlugin = plugin22;
9801 try {
9802 return visitor(node2.toProxy(), this.helpers);
9803 } catch (e2) {
9804 throw this.handleError(e2, node2);
9805 }
9806 }
9807 if (visit2.iterator !== 0) {
9808 var iterator = visit2.iterator;
9809 var child;
9810 while (child = node2.nodes[node2.indexes[iterator]]) {
9811 node2.indexes[iterator] += 1;
9812 if (!child[isClean$3]) {
9813 child[isClean$3] = true;
9814 stack.push(toStack$1(child));
9815 return;
9816 }
9817 }
9818 visit2.iterator = 0;
9819 delete node2.indexes[iterator];
9820 }
9821 var events = visit2.events;
9822 while (visit2.eventIndex < events.length) {
9823 var event = events[visit2.eventIndex];
9824 visit2.eventIndex += 1;
9825 if (event === CHILDREN$1) {
9826 if (node2.nodes && node2.nodes.length) {
9827 node2[isClean$3] = true;
9828 visit2.iterator = node2.getIterator();
9829 }
9830 return;
9831 } else if (this.listeners[event]) {
9832 visit2.visitors = this.listeners[event];
9833 return;
9834 }
9835 }
9836 stack.pop();
9837 };
9838 _proto.walkSync = function walkSync(node2) {
9839 var _this = this;
9840 node2[isClean$3] = true;
9841 for (var _iterator = _create_for_of_iterator_helper_loose(getEvents$1(node2)), _step; !(_step = _iterator()).done;) {
9842 var event = _step.value;
9843 if (event === CHILDREN$1) {
9844 if (node2.nodes) node2.each(function(child) {
9845 if (!child[isClean$3]) _this.walkSync(child);
9846 });
9847 } else {
9848 var visitors = this.listeners[event];
9849 if (visitors) {
9850 if (this.visitSync(visitors, node2.toProxy())) return;
9851 }
9852 }
9853 }
9854 };
9855 _proto.warnings = function warnings() {
9856 return this.sync().warnings();
9857 };
9858 _create_class(LazyResult, [
9859 {
9860 key: "content",
9861 get: function get() {
9862 return this.stringify().content;
9863 }
9864 },
9865 {
9866 key: "css",
9867 get: function get() {
9868 return this.stringify().css;
9869 }
9870 },
9871 {
9872 key: "map",
9873 get: function get() {
9874 return this.stringify().map;
9875 }
9876 },
9877 {
9878 key: "messages",
9879 get: function get() {
9880 return this.sync().messages;
9881 }
9882 },
9883 {
9884 key: "opts",
9885 get: function get() {
9886 return this.result.opts;
9887 }
9888 },
9889 {
9890 key: "processor",
9891 get: function get() {
9892 return this.result.processor;
9893 }
9894 },
9895 {
9896 key: "root",
9897 get: function get() {
9898 return this.sync().root;
9899 }
9900 },
9901 {
9902 key: Symbol.toStringTag,
9903 get: function get() {
9904 return "LazyResult";
9905 }
9906 }
9907 ]);
9908 return LazyResult;
9909 }();
9910 LazyResult$2$1.registerPostcss = function(dependant) {
9911 postcss$2$1 = dependant;
9912 };
9913 var lazyResult$1 = LazyResult$2$1;
9914 LazyResult$2$1.default = LazyResult$2$1;
9915 Root$3$1.registerLazyResult(LazyResult$2$1);
9916 Document$2$1.registerLazyResult(LazyResult$2$1);
9917 var MapGenerator2$1 = mapGenerator$1;
9918 var stringify$1$1 = stringify_1$1;
9919 var warnOnce2$1 = warnOnce$2$1;
9920 var parse$1$1 = parse_1$1;
9921 var Result$1$1 = result$1;
9922 var NoWorkResult$1$1 = /*#__PURE__*/ function() {
9923 function NoWorkResult(processor2, css, opts) {
9924 css = css.toString();
9925 this.stringified = false;
9926 this._processor = processor2;
9927 this._css = css;
9928 this._opts = opts;
9929 this._map = void 0;
9930 var root2;
9931 var str = stringify$1$1;
9932 this.result = new Result$1$1(this._processor, root2, this._opts);
9933 this.result.css = css;
9934 var self = this;
9935 Object.defineProperty(this.result, "root", { get: function get() {
9936 return self.root;
9937 } });
9938 var map = new MapGenerator2$1(str, root2, this._opts, css);
9939 if (map.isMap()) {
9940 var _map_generate = map.generate();
9941 var generatedCSS = _map_generate[0];
9942 var generatedMap = _map_generate[1];
9943 if (generatedCSS) this.result.css = generatedCSS;
9944 if (generatedMap) this.result.map = generatedMap;
9945 } else {
9946 map.clearAnnotation();
9947 this.result.css = map.css;
9948 }
9949 }
9950 var _proto = NoWorkResult.prototype;
9951 _proto.async = function async() {
9952 if (this.error) return Promise.reject(this.error);
9953 return Promise.resolve(this.result);
9954 };
9955 _proto.catch = function _catch(onRejected) {
9956 return this.async().catch(onRejected);
9957 };
9958 _proto.finally = function _finally(onFinally) {
9959 return this.async().then(onFinally, onFinally);
9960 };
9961 _proto.sync = function sync() {
9962 if (this.error) throw this.error;
9963 return this.result;
9964 };
9965 _proto.then = function then(onFulfilled, onRejected) {
9966 if (!("from" in this._opts)) warnOnce2$1("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.");
9967 return this.async().then(onFulfilled, onRejected);
9968 };
9969 _proto.toString = function toString() {
9970 return this._css;
9971 };
9972 _proto.warnings = function warnings() {
9973 return [];
9974 };
9975 _create_class(NoWorkResult, [
9976 {
9977 key: "content",
9978 get: function get() {
9979 return this.result.css;
9980 }
9981 },
9982 {
9983 key: "css",
9984 get: function get() {
9985 return this.result.css;
9986 }
9987 },
9988 {
9989 key: "map",
9990 get: function get() {
9991 return this.result.map;
9992 }
9993 },
9994 {
9995 key: "messages",
9996 get: function get() {
9997 return [];
9998 }
9999 },
10000 {
10001 key: "opts",
10002 get: function get() {
10003 return this.result.opts;
10004 }
10005 },
10006 {
10007 key: "processor",
10008 get: function get() {
10009 return this.result.processor;
10010 }
10011 },
10012 {
10013 key: "root",
10014 get: function get() {
10015 if (this._root) return this._root;
10016 var root2;
10017 var parser2 = parse$1$1;
10018 try {
10019 root2 = parser2(this._css, this._opts);
10020 } catch (error) {
10021 this.error = error;
10022 }
10023 if (this.error) throw this.error;
10024 else {
10025 this._root = root2;
10026 return root2;
10027 }
10028 }
10029 },
10030 {
10031 key: Symbol.toStringTag,
10032 get: function get() {
10033 return "NoWorkResult";
10034 }
10035 }
10036 ]);
10037 return NoWorkResult;
10038 }();
10039 var noWorkResult$1 = NoWorkResult$1$1;
10040 NoWorkResult$1$1.default = NoWorkResult$1$1;
10041 var NoWorkResult2$1 = noWorkResult$1;
10042 var LazyResult$1$1 = lazyResult$1;
10043 var Document$1$1 = document$1$1;
10044 var Root$2$1 = root$1;
10045 var Processor$1$1 = /*#__PURE__*/ function() {
10046 function Processor(plugins) {
10047 if (plugins === void 0) plugins = [];
10048 this.version = "8.4.38";
10049 this.plugins = this.normalize(plugins);
10050 }
10051 var _proto = Processor.prototype;
10052 _proto.normalize = function normalize(plugins) {
10053 var normalized = [];
10054 for (var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;) {
10055 var i2 = _step.value;
10056 if (i2.postcss === true) i2 = i2();
10057 else if (i2.postcss) i2 = i2.postcss;
10058 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) normalized = normalized.concat(i2.plugins);
10059 else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) normalized.push(i2);
10060 else if (typeof i2 === "function") normalized.push(i2);
10061 else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.");
10062 else throw new Error(i2 + " is not a PostCSS plugin");
10063 }
10064 return normalized;
10065 };
10066 _proto.process = function process1(css, opts) {
10067 if (opts === void 0) opts = {};
10068 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) return new NoWorkResult2$1(this, css, opts);
10069 else return new LazyResult$1$1(this, css, opts);
10070 };
10071 _proto.use = function use(plugin22) {
10072 this.plugins = this.plugins.concat(this.normalize([plugin22]));
10073 return this;
10074 };
10075 return Processor;
10076 }();
10077 var processor$1 = Processor$1$1;
10078 Processor$1$1.default = Processor$1$1;
10079 Root$2$1.registerProcessor(Processor$1$1);
10080 Document$1$1.registerProcessor(Processor$1$1);
10081 var Declaration$1$1 = declaration$1;
10082 var PreviousMap2$1 = previousMap$1;
10083 var Comment$1$1 = comment$1;
10084 var AtRule$1$1 = atRule$1;
10085 var Input$1$1 = input$1;
10086 var Root$1$1 = root$1;
10087 var Rule$1$1 = rule$1;
10088 function fromJSON$1$1(json, inputs) {
10089 if (Array.isArray(json)) return json.map(function(n2) {
10090 return fromJSON$1$1(n2);
10091 });
10092 var ownInputs = json.inputs;
10093 var defaults = _object_without_properties_loose(json, ["inputs"]);
10094 if (ownInputs) {
10095 inputs = [];
10096 for (var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;) {
10097 var input2 = _step.value;
10098 var inputHydrated = _extends({}, input2, { __proto__: Input$1$1.prototype });
10099 if (inputHydrated.map) inputHydrated.map = _extends({}, inputHydrated.map, { __proto__: PreviousMap2$1.prototype });
10100 inputs.push(inputHydrated);
10101 }
10102 }
10103 if (defaults.nodes) defaults.nodes = json.nodes.map(function(n2) {
10104 return fromJSON$1$1(n2, inputs);
10105 });
10106 if (defaults.source) {
10107 var _defaults_source = defaults.source;
10108 var inputId = _defaults_source.inputId;
10109 defaults.source = _object_without_properties_loose(_defaults_source, ["inputId"]);
10110 if (inputId != null) defaults.source.input = inputs[inputId];
10111 }
10112 if (defaults.type === "root") return new Root$1$1(defaults);
10113 else if (defaults.type === "decl") return new Declaration$1$1(defaults);
10114 else if (defaults.type === "rule") return new Rule$1$1(defaults);
10115 else if (defaults.type === "comment") return new Comment$1$1(defaults);
10116 else if (defaults.type === "atrule") return new AtRule$1$1(defaults);
10117 else throw new Error("Unknown node type: " + json.type);
10118 }
10119 var fromJSON_1$1 = fromJSON$1$1;
10120 fromJSON$1$1.default = fromJSON$1$1;
10121 var CssSyntaxError2$1 = cssSyntaxError$1;
10122 var Declaration2$1 = declaration$1;
10123 var LazyResult2$1 = lazyResult$1;
10124 var Container2$1 = container$1;
10125 var Processor2$1 = processor$1;
10126 var stringify$5 = stringify_1$1;
10127 var fromJSON$2 = fromJSON_1$1;
10128 var Document22 = document$1$1;
10129 var Warning2$1 = warning$1;
10130 var Comment2$1 = comment$1;
10131 var AtRule2$1 = atRule$1;
10132 var Result2$1 = result$1;
10133 var Input2$1 = input$1;
10134 var parse$5 = parse_1$1;
10135 var list$3 = list_1$1;
10136 var Rule2$1 = rule$1;
10137 var Root2$1 = root$1;
10138 var Node2$1 = node$1;
10139 function postcss$3() {
10140 for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) plugins[_key] = arguments[_key];
10141 if (plugins.length === 1 && Array.isArray(plugins[0])) plugins = plugins[0];
10142 return new Processor2$1(plugins);
10143 }
10144 postcss$3.plugin = function plugin(name, initializer) {
10145 var warningPrinted = false;
10146 function creator() {
10147 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
10148 if (console && console.warn && !warningPrinted) {
10149 warningPrinted = true;
10150 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
10151 if ({}.LANG && {}.LANG.startsWith("cn")) console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
10152 }
10153 var transformer = initializer.apply(void 0, [].concat(args));
10154 transformer.postcssPlugin = name;
10155 transformer.postcssVersion = new Processor2$1().version;
10156 return transformer;
10157 }
10158 var cache;
10159 Object.defineProperty(creator, "postcss", { get: function get() {
10160 if (!cache) cache = creator();
10161 return cache;
10162 } });
10163 creator.process = function(css, processOpts, pluginOpts) {
10164 return postcss$3([creator(pluginOpts)]).process(css, processOpts);
10165 };
10166 return creator;
10167 };
10168 postcss$3.stringify = stringify$5;
10169 postcss$3.parse = parse$5;
10170 postcss$3.fromJSON = fromJSON$2;
10171 postcss$3.list = list$3;
10172 postcss$3.comment = function(defaults) {
10173 return new Comment2$1(defaults);
10174 };
10175 postcss$3.atRule = function(defaults) {
10176 return new AtRule2$1(defaults);
10177 };
10178 postcss$3.decl = function(defaults) {
10179 return new Declaration2$1(defaults);
10180 };
10181 postcss$3.rule = function(defaults) {
10182 return new Rule2$1(defaults);
10183 };
10184 postcss$3.root = function(defaults) {
10185 return new Root2$1(defaults);
10186 };
10187 postcss$3.document = function(defaults) {
10188 return new Document22(defaults);
10189 };
10190 postcss$3.CssSyntaxError = CssSyntaxError2$1;
10191 postcss$3.Declaration = Declaration2$1;
10192 postcss$3.Container = Container2$1;
10193 postcss$3.Processor = Processor2$1;
10194 postcss$3.Document = Document22;
10195 postcss$3.Comment = Comment2$1;
10196 postcss$3.Warning = Warning2$1;
10197 postcss$3.AtRule = AtRule2$1;
10198 postcss$3.Result = Result2$1;
10199 postcss$3.Input = Input2$1;
10200 postcss$3.Rule = Rule2$1;
10201 postcss$3.Root = Root2$1;
10202 postcss$3.Node = Node2$1;
10203 LazyResult2$1.registerPostcss(postcss$3);
10204 var postcss_1$1 = postcss$3;
10205 postcss$3.default = postcss$3;
10206 var postcss$1$1 = /* @__PURE__ */ getDefaultExportFromCjs$1(postcss_1$1);
10207 postcss$1$1.stringify;
10208 postcss$1$1.fromJSON;
10209 postcss$1$1.plugin;
10210 postcss$1$1.parse;
10211 postcss$1$1.list;
10212 postcss$1$1.document;
10213 postcss$1$1.comment;
10214 postcss$1$1.atRule;
10215 postcss$1$1.rule;
10216 postcss$1$1.decl;
10217 postcss$1$1.root;
10218 postcss$1$1.CssSyntaxError;
10219 postcss$1$1.Declaration;
10220 postcss$1$1.Container;
10221 postcss$1$1.Processor;
10222 postcss$1$1.Document;
10223 postcss$1$1.Comment;
10224 postcss$1$1.Warning;
10225 postcss$1$1.AtRule;
10226 postcss$1$1.Result;
10227 postcss$1$1.Input;
10228 postcss$1$1.Rule;
10229 postcss$1$1.Root;
10230 postcss$1$1.Node;
10231 var __defProp2 = Object.defineProperty;
10232 var __defNormalProp2 = function(obj, key, value) {
10233 return key in obj ? __defProp2(obj, key, {
10234 enumerable: true,
10235 configurable: true,
10236 writable: true,
10237 value
10238 }) : obj[key] = value;
10239 };
10240 var __publicField2 = function(obj, key, value) {
10241 return __defNormalProp2(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
10242 };
10243 function getDefaultExportFromCjs(x2) {
10244 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
10245 }
10246 function getAugmentedNamespace(n2) {
10247 if (n2.__esModule) return n2;
10248 var f2 = n2.default;
10249 if (typeof f2 == "function") {
10250 var a2 = function a22() {
10251 if (_instanceof(this, a22)) return Reflect.construct(f2, arguments, this.constructor);
10252 return f2.apply(this, arguments);
10253 };
10254 a2.prototype = f2.prototype;
10255 } else a2 = {};
10256 Object.defineProperty(a2, "__esModule", { value: true });
10257 Object.keys(n2).forEach(function(k) {
10258 var d = Object.getOwnPropertyDescriptor(n2, k);
10259 Object.defineProperty(a2, k, d.get ? d : {
10260 enumerable: true,
10261 get: function get() {
10262 return n2[k];
10263 }
10264 });
10265 });
10266 return a2;
10267 }
10268 var picocolors_browser = { exports: {} };
10269 var x = String;
10270 var create = function create() {
10271 return {
10272 isColorSupported: false,
10273 reset: x,
10274 bold: x,
10275 dim: x,
10276 italic: x,
10277 underline: x,
10278 inverse: x,
10279 hidden: x,
10280 strikethrough: x,
10281 black: x,
10282 red: x,
10283 green: x,
10284 yellow: x,
10285 blue: x,
10286 magenta: x,
10287 cyan: x,
10288 white: x,
10289 gray: x,
10290 bgBlack: x,
10291 bgRed: x,
10292 bgGreen: x,
10293 bgYellow: x,
10294 bgBlue: x,
10295 bgMagenta: x,
10296 bgCyan: x,
10297 bgWhite: x
10298 };
10299 };
10300 picocolors_browser.exports = create();
10301 picocolors_browser.exports.createColors = create;
10302 var picocolors_browserExports = picocolors_browser.exports;
10303 var require$$2 = /* @__PURE__ */ getAugmentedNamespace(/* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
10304 __proto__: null,
10305 default: {}
10306 }, Symbol.toStringTag, { value: "Module" })));
10307 var pico = picocolors_browserExports;
10308 var terminalHighlight$1 = require$$2;
10309 var CssSyntaxError$3 = /*#__PURE__*/ function(Error1) {
10310 _inherits(CssSyntaxError2, Error1);
10311 function CssSyntaxError2(message, line, column, source, file, plugin22) {
10312 var _this = Error1.call(this, message) || this;
10313 _this.name = "CssSyntaxError";
10314 _this.reason = message;
10315 if (file) _this.file = file;
10316 if (source) _this.source = source;
10317 if (plugin22) _this.plugin = plugin22;
10318 if (typeof line !== "undefined" && typeof column !== "undefined") if (typeof line === "number") {
10319 _this.line = line;
10320 _this.column = column;
10321 } else {
10322 _this.line = line.line;
10323 _this.column = line.column;
10324 _this.endLine = column.line;
10325 _this.endColumn = column.column;
10326 }
10327 _this.setMessage();
10328 if (Error.captureStackTrace) Error.captureStackTrace(_this, CssSyntaxError2);
10329 return _this;
10330 }
10331 var _proto = CssSyntaxError2.prototype;
10332 _proto.setMessage = function setMessage() {
10333 this.message = this.plugin ? this.plugin + ": " : "";
10334 this.message += this.file ? this.file : "<css input>";
10335 if (typeof this.line !== "undefined") this.message += ":" + this.line + ":" + this.column;
10336 this.message += ": " + this.reason;
10337 };
10338 _proto.showSourceCode = function showSourceCode(color) {
10339 var _this = this;
10340 if (!this.source) return "";
10341 var css = this.source;
10342 if (color == null) color = pico.isColorSupported;
10343 if (terminalHighlight$1) {
10344 if (color) css = terminalHighlight$1(css);
10345 }
10346 var lines = css.split(/\r?\n/);
10347 var start = Math.max(this.line - 3, 0);
10348 var end = Math.min(this.line + 2, lines.length);
10349 var maxWidth = String(end).length;
10350 var mark;
10351 var aside;
10352 if (color) {
10353 var _pico_createColors = pico.createColors(true);
10354 var bold = _pico_createColors.bold;
10355 var gray = _pico_createColors.gray;
10356 var red = _pico_createColors.red;
10357 mark = function(text) {
10358 return bold(red(text));
10359 };
10360 aside = function(text) {
10361 return gray(text);
10362 };
10363 } else mark = aside = function(str) {
10364 return str;
10365 };
10366 return lines.slice(start, end).map(function(line, index2) {
10367 var number = start + 1 + index2;
10368 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
10369 if (number === _this.line) {
10370 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
10371 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
10372 }
10373 return " " + aside(gutter) + line;
10374 }).join("\n");
10375 };
10376 _proto.toString = function toString() {
10377 var code = this.showSourceCode();
10378 if (code) code = "\n\n" + code + "\n";
10379 return this.name + ": " + this.message + code;
10380 };
10381 return CssSyntaxError2;
10382 }(_wrap_native_super(Error));
10383 var cssSyntaxError = CssSyntaxError$3;
10384 CssSyntaxError$3.default = CssSyntaxError$3;
10385 var symbols = {};
10386 symbols.isClean = Symbol("isClean");
10387 symbols.my = Symbol("my");
10388 var DEFAULT_RAW = {
10389 after: "\n",
10390 beforeClose: "\n",
10391 beforeComment: "\n",
10392 beforeDecl: "\n",
10393 beforeOpen: " ",
10394 beforeRule: "\n",
10395 colon: ": ",
10396 commentLeft: " ",
10397 commentRight: " ",
10398 emptyBody: "",
10399 indent: " ",
10400 semicolon: false
10401 };
10402 function capitalize(str) {
10403 return str[0].toUpperCase() + str.slice(1);
10404 }
10405 var Stringifier$2 = /*#__PURE__*/ function() {
10406 function Stringifier2(builder) {
10407 this.builder = builder;
10408 }
10409 var _proto = Stringifier2.prototype;
10410 _proto.atrule = function atrule(node2, semicolon) {
10411 var name = "@" + node2.name;
10412 var params = node2.params ? this.rawValue(node2, "params") : "";
10413 if (typeof node2.raws.afterName !== "undefined") name += node2.raws.afterName;
10414 else if (params) name += " ";
10415 if (node2.nodes) this.block(node2, name + params);
10416 else {
10417 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
10418 this.builder(name + params + end, node2);
10419 }
10420 };
10421 _proto.beforeAfter = function beforeAfter(node2, detect) {
10422 var value;
10423 if (node2.type === "decl") value = this.raw(node2, null, "beforeDecl");
10424 else if (node2.type === "comment") value = this.raw(node2, null, "beforeComment");
10425 else if (detect === "before") value = this.raw(node2, null, "beforeRule");
10426 else value = this.raw(node2, null, "beforeClose");
10427 var buf = node2.parent;
10428 var depth = 0;
10429 while (buf && buf.type !== "root") {
10430 depth += 1;
10431 buf = buf.parent;
10432 }
10433 if (value.includes("\n")) {
10434 var indent = this.raw(node2, null, "indent");
10435 if (indent.length) for (var step = 0; step < depth; step++) value += indent;
10436 }
10437 return value;
10438 };
10439 _proto.block = function block(node2, start) {
10440 var between = this.raw(node2, "between", "beforeOpen");
10441 this.builder(start + between + "{", node2, "start");
10442 var after;
10443 if (node2.nodes && node2.nodes.length) {
10444 this.body(node2);
10445 after = this.raw(node2, "after");
10446 } else after = this.raw(node2, "after", "emptyBody");
10447 if (after) this.builder(after);
10448 this.builder("}", node2, "end");
10449 };
10450 _proto.body = function body(node2) {
10451 var last = node2.nodes.length - 1;
10452 while (last > 0) {
10453 if (node2.nodes[last].type !== "comment") break;
10454 last -= 1;
10455 }
10456 var semicolon = this.raw(node2, "semicolon");
10457 for (var i2 = 0; i2 < node2.nodes.length; i2++) {
10458 var child = node2.nodes[i2];
10459 var before = this.raw(child, "before");
10460 if (before) this.builder(before);
10461 this.stringify(child, last !== i2 || semicolon);
10462 }
10463 };
10464 _proto.comment = function comment(node2) {
10465 var left = this.raw(node2, "left", "commentLeft");
10466 var right = this.raw(node2, "right", "commentRight");
10467 this.builder("/*" + left + node2.text + right + "*/", node2);
10468 };
10469 _proto.decl = function decl(node2, semicolon) {
10470 var between = this.raw(node2, "between", "colon");
10471 var string = node2.prop + between + this.rawValue(node2, "value");
10472 if (node2.important) string += node2.raws.important || " !important";
10473 if (semicolon) string += ";";
10474 this.builder(string, node2);
10475 };
10476 _proto.document = function document1(node2) {
10477 this.body(node2);
10478 };
10479 _proto.raw = function raw(node2, own, detect) {
10480 var value;
10481 if (!detect) detect = own;
10482 if (own) {
10483 value = node2.raws[own];
10484 if (typeof value !== "undefined") return value;
10485 }
10486 var parent = node2.parent;
10487 if (detect === "before") {
10488 if (!parent || parent.type === "root" && parent.first === node2) return "";
10489 if (parent && parent.type === "document") return "";
10490 }
10491 if (!parent) return DEFAULT_RAW[detect];
10492 var root2 = node2.root();
10493 if (!root2.rawCache) root2.rawCache = {};
10494 if (typeof root2.rawCache[detect] !== "undefined") return root2.rawCache[detect];
10495 if (detect === "before" || detect === "after") return this.beforeAfter(node2, detect);
10496 else {
10497 var method = "raw" + capitalize(detect);
10498 if (this[method]) value = this[method](root2, node2);
10499 else root2.walk(function(i2) {
10500 value = i2.raws[own];
10501 if (typeof value !== "undefined") return false;
10502 });
10503 }
10504 if (typeof value === "undefined") value = DEFAULT_RAW[detect];
10505 root2.rawCache[detect] = value;
10506 return value;
10507 };
10508 _proto.rawBeforeClose = function rawBeforeClose(root2) {
10509 var value;
10510 root2.walk(function(i2) {
10511 if (i2.nodes && i2.nodes.length > 0) {
10512 if (typeof i2.raws.after !== "undefined") {
10513 value = i2.raws.after;
10514 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
10515 return false;
10516 }
10517 }
10518 });
10519 if (value) value = value.replace(/\S/g, "");
10520 return value;
10521 };
10522 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
10523 var value;
10524 root2.walkComments(function(i2) {
10525 if (typeof i2.raws.before !== "undefined") {
10526 value = i2.raws.before;
10527 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
10528 return false;
10529 }
10530 });
10531 if (typeof value === "undefined") value = this.raw(node2, null, "beforeDecl");
10532 else if (value) value = value.replace(/\S/g, "");
10533 return value;
10534 };
10535 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
10536 var value;
10537 root2.walkDecls(function(i2) {
10538 if (typeof i2.raws.before !== "undefined") {
10539 value = i2.raws.before;
10540 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
10541 return false;
10542 }
10543 });
10544 if (typeof value === "undefined") value = this.raw(node2, null, "beforeRule");
10545 else if (value) value = value.replace(/\S/g, "");
10546 return value;
10547 };
10548 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
10549 var value;
10550 root2.walk(function(i2) {
10551 if (i2.type !== "decl") {
10552 value = i2.raws.between;
10553 if (typeof value !== "undefined") return false;
10554 }
10555 });
10556 return value;
10557 };
10558 _proto.rawBeforeRule = function rawBeforeRule(root2) {
10559 var value;
10560 root2.walk(function(i2) {
10561 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
10562 if (typeof i2.raws.before !== "undefined") {
10563 value = i2.raws.before;
10564 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
10565 return false;
10566 }
10567 }
10568 });
10569 if (value) value = value.replace(/\S/g, "");
10570 return value;
10571 };
10572 _proto.rawColon = function rawColon(root2) {
10573 var value;
10574 root2.walkDecls(function(i2) {
10575 if (typeof i2.raws.between !== "undefined") {
10576 value = i2.raws.between.replace(/[^\s:]/g, "");
10577 return false;
10578 }
10579 });
10580 return value;
10581 };
10582 _proto.rawEmptyBody = function rawEmptyBody(root2) {
10583 var value;
10584 root2.walk(function(i2) {
10585 if (i2.nodes && i2.nodes.length === 0) {
10586 value = i2.raws.after;
10587 if (typeof value !== "undefined") return false;
10588 }
10589 });
10590 return value;
10591 };
10592 _proto.rawIndent = function rawIndent(root2) {
10593 if (root2.raws.indent) return root2.raws.indent;
10594 var value;
10595 root2.walk(function(i2) {
10596 var p = i2.parent;
10597 if (p && p !== root2 && p.parent && p.parent === root2) {
10598 if (typeof i2.raws.before !== "undefined") {
10599 var parts = i2.raws.before.split("\n");
10600 value = parts[parts.length - 1];
10601 value = value.replace(/\S/g, "");
10602 return false;
10603 }
10604 }
10605 });
10606 return value;
10607 };
10608 _proto.rawSemicolon = function rawSemicolon(root2) {
10609 var value;
10610 root2.walk(function(i2) {
10611 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
10612 value = i2.raws.semicolon;
10613 if (typeof value !== "undefined") return false;
10614 }
10615 });
10616 return value;
10617 };
10618 _proto.rawValue = function rawValue(node2, prop) {
10619 var value = node2[prop];
10620 var raw = node2.raws[prop];
10621 if (raw && raw.value === value) return raw.raw;
10622 return value;
10623 };
10624 _proto.root = function root(node2) {
10625 this.body(node2);
10626 if (node2.raws.after) this.builder(node2.raws.after);
10627 };
10628 _proto.rule = function rule(node2) {
10629 this.block(node2, this.rawValue(node2, "selector"));
10630 if (node2.raws.ownSemicolon) this.builder(node2.raws.ownSemicolon, node2, "end");
10631 };
10632 _proto.stringify = function stringify(node2, semicolon) {
10633 if (!this[node2.type]) throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
10634 this[node2.type](node2, semicolon);
10635 };
10636 return Stringifier2;
10637 }();
10638 var stringifier = Stringifier$2;
10639 Stringifier$2.default = Stringifier$2;
10640 var Stringifier$1 = stringifier;
10641 function stringify$4(node2, builder) {
10642 new Stringifier$1(builder).stringify(node2);
10643 }
10644 var stringify_1 = stringify$4;
10645 stringify$4.default = stringify$4;
10646 var isClean$2 = symbols.isClean;
10647 var my$2 = symbols.my;
10648 var CssSyntaxError$2 = cssSyntaxError;
10649 var Stringifier22 = stringifier;
10650 var stringify$3 = stringify_1;
10651 function cloneNode(obj, parent) {
10652 var cloned = new obj.constructor();
10653 for (var i2 in obj) {
10654 if (!Object.prototype.hasOwnProperty.call(obj, i2)) continue;
10655 if (i2 === "proxyCache") continue;
10656 var value = obj[i2];
10657 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
10658 if (i2 === "parent" && type === "object") {
10659 if (parent) cloned[i2] = parent;
10660 } else if (i2 === "source") cloned[i2] = value;
10661 else if (Array.isArray(value)) cloned[i2] = value.map(function(j) {
10662 return cloneNode(j, cloned);
10663 });
10664 else {
10665 if (type === "object" && value !== null) value = cloneNode(value);
10666 cloned[i2] = value;
10667 }
10668 }
10669 return cloned;
10670 }
10671 var Node$4 = /*#__PURE__*/ function() {
10672 function Node3(defaults) {
10673 if (defaults === void 0) defaults = {};
10674 this.raws = {};
10675 this[isClean$2] = false;
10676 this[my$2] = true;
10677 for (var name in defaults) if (name === "nodes") {
10678 this.nodes = [];
10679 for (var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;) {
10680 var node2 = _step.value;
10681 if (typeof node2.clone === "function") this.append(node2.clone());
10682 else this.append(node2);
10683 }
10684 } else this[name] = defaults[name];
10685 }
10686 var _proto = Node3.prototype;
10687 _proto.addToError = function addToError(error) {
10688 error.postcssNode = this;
10689 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
10690 var s2 = this.source;
10691 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
10692 }
10693 return error;
10694 };
10695 _proto.after = function after(add) {
10696 this.parent.insertAfter(this, add);
10697 return this;
10698 };
10699 _proto.assign = function assign(overrides) {
10700 if (overrides === void 0) overrides = {};
10701 for (var name in overrides) this[name] = overrides[name];
10702 return this;
10703 };
10704 _proto.before = function before(add) {
10705 this.parent.insertBefore(this, add);
10706 return this;
10707 };
10708 _proto.cleanRaws = function cleanRaws(keepBetween) {
10709 delete this.raws.before;
10710 delete this.raws.after;
10711 if (!keepBetween) delete this.raws.between;
10712 };
10713 _proto.clone = function clone(overrides) {
10714 if (overrides === void 0) overrides = {};
10715 var cloned = cloneNode(this);
10716 for (var name in overrides) cloned[name] = overrides[name];
10717 return cloned;
10718 };
10719 _proto.cloneAfter = function cloneAfter(overrides) {
10720 if (overrides === void 0) overrides = {};
10721 var cloned = this.clone(overrides);
10722 this.parent.insertAfter(this, cloned);
10723 return cloned;
10724 };
10725 _proto.cloneBefore = function cloneBefore(overrides) {
10726 if (overrides === void 0) overrides = {};
10727 var cloned = this.clone(overrides);
10728 this.parent.insertBefore(this, cloned);
10729 return cloned;
10730 };
10731 _proto.error = function error(message, opts) {
10732 if (opts === void 0) opts = {};
10733 if (this.source) {
10734 var _this_rangeBy = this.rangeBy(opts);
10735 var end = _this_rangeBy.end;
10736 var start = _this_rangeBy.start;
10737 return this.source.input.error(message, {
10738 column: start.column,
10739 line: start.line
10740 }, {
10741 column: end.column,
10742 line: end.line
10743 }, opts);
10744 }
10745 return new CssSyntaxError$2(message);
10746 };
10747 _proto.getProxyProcessor = function getProxyProcessor() {
10748 return {
10749 get: function get(node2, prop) {
10750 if (prop === "proxyOf") return node2;
10751 else if (prop === "root") return function() {
10752 return node2.root().toProxy();
10753 };
10754 else return node2[prop];
10755 },
10756 set: function set(node2, prop, value) {
10757 if (node2[prop] === value) return true;
10758 node2[prop] = value;
10759 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || prop === "text") node2.markDirty();
10760 return true;
10761 }
10762 };
10763 };
10764 _proto.markDirty = function markDirty() {
10765 if (this[isClean$2]) {
10766 this[isClean$2] = false;
10767 var next = this;
10768 while (next = next.parent) next[isClean$2] = false;
10769 }
10770 };
10771 _proto.next = function next() {
10772 if (!this.parent) return void 0;
10773 var index2 = this.parent.index(this);
10774 return this.parent.nodes[index2 + 1];
10775 };
10776 _proto.positionBy = function positionBy(opts, stringRepresentation) {
10777 var pos = this.source.start;
10778 if (opts.index) pos = this.positionInside(opts.index, stringRepresentation);
10779 else if (opts.word) {
10780 stringRepresentation = this.toString();
10781 var index2 = stringRepresentation.indexOf(opts.word);
10782 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
10783 }
10784 return pos;
10785 };
10786 _proto.positionInside = function positionInside(index2, stringRepresentation) {
10787 var string = stringRepresentation || this.toString();
10788 var column = this.source.start.column;
10789 var line = this.source.start.line;
10790 for (var i2 = 0; i2 < index2; i2++) if (string[i2] === "\n") {
10791 column = 1;
10792 line += 1;
10793 } else column += 1;
10794 return {
10795 column,
10796 line
10797 };
10798 };
10799 _proto.prev = function prev() {
10800 if (!this.parent) return void 0;
10801 var index2 = this.parent.index(this);
10802 return this.parent.nodes[index2 - 1];
10803 };
10804 _proto.rangeBy = function rangeBy(opts) {
10805 var start = {
10806 column: this.source.start.column,
10807 line: this.source.start.line
10808 };
10809 var end = this.source.end ? {
10810 column: this.source.end.column + 1,
10811 line: this.source.end.line
10812 } : {
10813 column: start.column + 1,
10814 line: start.line
10815 };
10816 if (opts.word) {
10817 var stringRepresentation = this.toString();
10818 var index2 = stringRepresentation.indexOf(opts.word);
10819 if (index2 !== -1) {
10820 start = this.positionInside(index2, stringRepresentation);
10821 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
10822 }
10823 } else {
10824 if (opts.start) start = {
10825 column: opts.start.column,
10826 line: opts.start.line
10827 };
10828 else if (opts.index) start = this.positionInside(opts.index);
10829 if (opts.end) end = {
10830 column: opts.end.column,
10831 line: opts.end.line
10832 };
10833 else if (typeof opts.endIndex === "number") end = this.positionInside(opts.endIndex);
10834 else if (opts.index) end = this.positionInside(opts.index + 1);
10835 }
10836 if (end.line < start.line || end.line === start.line && end.column <= start.column) end = {
10837 column: start.column + 1,
10838 line: start.line
10839 };
10840 return {
10841 end,
10842 start
10843 };
10844 };
10845 _proto.raw = function raw(prop, defaultType) {
10846 return new Stringifier22().raw(this, prop, defaultType);
10847 };
10848 _proto.remove = function remove() {
10849 if (this.parent) this.parent.removeChild(this);
10850 this.parent = void 0;
10851 return this;
10852 };
10853 _proto.replaceWith = function replaceWith() {
10854 for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) nodes[_key] = arguments[_key];
10855 if (this.parent) {
10856 var bookmark = this;
10857 var foundSelf = false;
10858 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
10859 var node2 = _step.value;
10860 if (node2 === this) foundSelf = true;
10861 else if (foundSelf) {
10862 this.parent.insertAfter(bookmark, node2);
10863 bookmark = node2;
10864 } else this.parent.insertBefore(bookmark, node2);
10865 }
10866 if (!foundSelf) this.remove();
10867 }
10868 return this;
10869 };
10870 _proto.root = function root() {
10871 var result2 = this;
10872 while (result2.parent && result2.parent.type !== "document") result2 = result2.parent;
10873 return result2;
10874 };
10875 _proto.toJSON = function toJSON(_, inputs) {
10876 var fixed = {};
10877 var emitInputs = inputs == null;
10878 inputs = inputs || /* @__PURE__ */ new Map();
10879 var inputsNextIndex = 0;
10880 for (var name in this) {
10881 if (!Object.prototype.hasOwnProperty.call(this, name)) continue;
10882 if (name === "parent" || name === "proxyCache") continue;
10883 var value = this[name];
10884 if (Array.isArray(value)) fixed[name] = value.map(function(i2) {
10885 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) return i2.toJSON(null, inputs);
10886 else return i2;
10887 });
10888 else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) fixed[name] = value.toJSON(null, inputs);
10889 else if (name === "source") {
10890 var inputId = inputs.get(value.input);
10891 if (inputId == null) {
10892 inputId = inputsNextIndex;
10893 inputs.set(value.input, inputsNextIndex);
10894 inputsNextIndex++;
10895 }
10896 fixed[name] = {
10897 end: value.end,
10898 inputId,
10899 start: value.start
10900 };
10901 } else fixed[name] = value;
10902 }
10903 if (emitInputs) fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
10904 return input2.toJSON();
10905 });
10906 return fixed;
10907 };
10908 _proto.toProxy = function toProxy() {
10909 if (!this.proxyCache) this.proxyCache = new Proxy(this, this.getProxyProcessor());
10910 return this.proxyCache;
10911 };
10912 _proto.toString = function toString(stringifier2) {
10913 if (stringifier2 === void 0) stringifier2 = stringify$3;
10914 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
10915 var result2 = "";
10916 stringifier2(this, function(i2) {
10917 result2 += i2;
10918 });
10919 return result2;
10920 };
10921 _proto.warn = function warn(result2, text, opts) {
10922 var data = { node: this };
10923 for (var i2 in opts) data[i2] = opts[i2];
10924 return result2.warn(text, data);
10925 };
10926 _create_class(Node3, [{
10927 key: "proxyOf",
10928 get: function get() {
10929 return this;
10930 }
10931 }]);
10932 return Node3;
10933 }();
10934 var node = Node$4;
10935 Node$4.default = Node$4;
10936 var Declaration$4 = /*#__PURE__*/ function(Node$3) {
10937 _inherits(Declaration2, Node$3);
10938 function Declaration2(defaults) {
10939 var _this;
10940 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") defaults = _extends({}, defaults, { value: String(defaults.value) });
10941 _this = Node$3.call(this, defaults) || this;
10942 _this.type = "decl";
10943 return _this;
10944 }
10945 _create_class(Declaration2, [{
10946 key: "variable",
10947 get: function get() {
10948 return this.prop.startsWith("--") || this.prop[0] === "$";
10949 }
10950 }]);
10951 return Declaration2;
10952 }(node);
10953 var declaration = Declaration$4;
10954 Declaration$4.default = Declaration$4;
10955 var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
10956 var nanoid$1 = function(size) {
10957 if (size === void 0) size = 21;
10958 var id = "";
10959 var i2 = size;
10960 while (i2--) id += urlAlphabet[Math.random() * 64 | 0];
10961 return id;
10962 };
10963 var nonSecure = { nanoid: nanoid$1 };
10964 var SourceMapConsumer$2 = require$$2.SourceMapConsumer;
10965 var SourceMapGenerator$2 = require$$2.SourceMapGenerator;
10966 var existsSync = require$$2.existsSync;
10967 var readFileSync = require$$2.readFileSync;
10968 var dirname$1 = require$$2.dirname;
10969 var join = require$$2.join;
10970 function fromBase64(str) {
10971 if (Buffer) return Buffer.from(str, "base64").toString();
10972 else return window.atob(str);
10973 }
10974 var PreviousMap$2 = /*#__PURE__*/ function() {
10975 function PreviousMap2(css, opts) {
10976 if (opts.map === false) return;
10977 this.loadAnnotation(css);
10978 this.inline = this.startWith(this.annotation, "data:");
10979 var prev = opts.map ? opts.map.prev : void 0;
10980 var text = this.loadMap(opts.from, prev);
10981 if (!this.mapFile && opts.from) this.mapFile = opts.from;
10982 if (this.mapFile) this.root = dirname$1(this.mapFile);
10983 if (text) this.text = text;
10984 }
10985 var _proto = PreviousMap2.prototype;
10986 _proto.consumer = function consumer() {
10987 if (!this.consumerCache) this.consumerCache = new SourceMapConsumer$2(this.text);
10988 return this.consumerCache;
10989 };
10990 _proto.decodeInline = function decodeInline(text) {
10991 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
10992 var baseUri = /^data:application\/json;base64,/;
10993 if (/^data:application\/json;charset=utf-?8,/.test(text) || /^data:application\/json,/.test(text)) return decodeURIComponent(text.substr(RegExp.lastMatch.length));
10994 if (baseCharsetUri.test(text) || baseUri.test(text)) return fromBase64(text.substr(RegExp.lastMatch.length));
10995 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
10996 throw new Error("Unsupported source map encoding " + encoding);
10997 };
10998 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
10999 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
11000 };
11001 _proto.isMap = function isMap(map) {
11002 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
11003 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
11004 };
11005 _proto.loadAnnotation = function loadAnnotation(css) {
11006 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
11007 if (!comments) return;
11008 var start = css.lastIndexOf(comments.pop());
11009 var end = css.indexOf("*/", start);
11010 if (start > -1 && end > -1) this.annotation = this.getAnnotationURL(css.substring(start, end));
11011 };
11012 _proto.loadFile = function loadFile(path) {
11013 this.root = dirname$1(path);
11014 if (existsSync(path)) {
11015 this.mapFile = path;
11016 return readFileSync(path, "utf-8").toString().trim();
11017 }
11018 };
11019 _proto.loadMap = function loadMap(file, prev) {
11020 if (prev === false) return false;
11021 if (prev) if (typeof prev === "string") return prev;
11022 else if (typeof prev === "function") {
11023 var prevPath = prev(file);
11024 if (prevPath) {
11025 var map = this.loadFile(prevPath);
11026 if (!map) throw new Error("Unable to load previous source map: " + prevPath.toString());
11027 return map;
11028 }
11029 } else if (_instanceof(prev, SourceMapConsumer$2)) return SourceMapGenerator$2.fromSourceMap(prev).toString();
11030 else if (_instanceof(prev, SourceMapGenerator$2)) return prev.toString();
11031 else if (this.isMap(prev)) return JSON.stringify(prev);
11032 else throw new Error("Unsupported previous source map format: " + prev.toString());
11033 else if (this.inline) return this.decodeInline(this.annotation);
11034 else if (this.annotation) {
11035 var map1 = this.annotation;
11036 if (file) map1 = join(dirname$1(file), map1);
11037 return this.loadFile(map1);
11038 }
11039 };
11040 _proto.startWith = function startWith(string, start) {
11041 if (!string) return false;
11042 return string.substr(0, start.length) === start;
11043 };
11044 _proto.withContent = function withContent() {
11045 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
11046 };
11047 return PreviousMap2;
11048 }();
11049 var previousMap = PreviousMap$2;
11050 PreviousMap$2.default = PreviousMap$2;
11051 var SourceMapConsumer$1 = require$$2.SourceMapConsumer;
11052 var SourceMapGenerator$1 = require$$2.SourceMapGenerator;
11053 var fileURLToPath = require$$2.fileURLToPath;
11054 var pathToFileURL$1 = require$$2.pathToFileURL;
11055 var isAbsolute = require$$2.isAbsolute;
11056 var resolve$1 = require$$2.resolve;
11057 var nanoid = nonSecure.nanoid;
11058 var terminalHighlight = require$$2;
11059 var CssSyntaxError$1 = cssSyntaxError;
11060 var PreviousMap$1 = previousMap;
11061 var fromOffsetCache = Symbol("fromOffsetCache");
11062 var sourceMapAvailable$1 = Boolean(SourceMapConsumer$1 && SourceMapGenerator$1);
11063 var pathAvailable$1 = Boolean(resolve$1 && isAbsolute);
11064 var Input$4 = /*#__PURE__*/ function() {
11065 function Input2(css, opts) {
11066 if (opts === void 0) opts = {};
11067 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) throw new Error("PostCSS received " + css + " instead of CSS string");
11068 this.css = css.toString();
11069 if (this.css[0] === "" || this.css[0] === "￾") {
11070 this.hasBOM = true;
11071 this.css = this.css.slice(1);
11072 } else this.hasBOM = false;
11073 if (opts.from) if (!pathAvailable$1 || /^\w+:\/\//.test(opts.from) || isAbsolute(opts.from)) this.file = opts.from;
11074 else this.file = resolve$1(opts.from);
11075 if (pathAvailable$1 && sourceMapAvailable$1) {
11076 var map = new PreviousMap$1(this.css, opts);
11077 if (map.text) {
11078 this.map = map;
11079 var file = map.consumer().file;
11080 if (!this.file && file) this.file = this.mapResolve(file);
11081 }
11082 }
11083 if (!this.file) this.id = "<input css " + nanoid(6) + ">";
11084 if (this.map) this.map.file = this.from;
11085 }
11086 var _proto = Input2.prototype;
11087 _proto.error = function error(message, line, column, opts) {
11088 if (opts === void 0) opts = {};
11089 var result2;
11090 var endLine;
11091 var endColumn;
11092 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
11093 var start = line;
11094 var end = column;
11095 if (typeof start.offset === "number") {
11096 var pos = this.fromOffset(start.offset);
11097 line = pos.line;
11098 column = pos.col;
11099 } else {
11100 line = start.line;
11101 column = start.column;
11102 }
11103 if (typeof end.offset === "number") {
11104 var pos1 = this.fromOffset(end.offset);
11105 endLine = pos1.line;
11106 endColumn = pos1.col;
11107 } else {
11108 endLine = end.line;
11109 endColumn = end.column;
11110 }
11111 } else if (!column) {
11112 var pos2 = this.fromOffset(line);
11113 line = pos2.line;
11114 column = pos2.col;
11115 }
11116 var origin = this.origin(line, column, endLine, endColumn);
11117 if (origin) result2 = new CssSyntaxError$1(message, origin.endLine === void 0 ? origin.line : {
11118 column: origin.column,
11119 line: origin.line
11120 }, origin.endLine === void 0 ? origin.column : {
11121 column: origin.endColumn,
11122 line: origin.endLine
11123 }, origin.source, origin.file, opts.plugin);
11124 else result2 = new CssSyntaxError$1(message, endLine === void 0 ? line : {
11125 column,
11126 line
11127 }, endLine === void 0 ? column : {
11128 column: endColumn,
11129 line: endLine
11130 }, this.css, this.file, opts.plugin);
11131 result2.input = {
11132 column,
11133 endColumn,
11134 endLine,
11135 line,
11136 source: this.css
11137 };
11138 if (this.file) {
11139 if (pathToFileURL$1) result2.input.url = pathToFileURL$1(this.file).toString();
11140 result2.input.file = this.file;
11141 }
11142 return result2;
11143 };
11144 _proto.fromOffset = function fromOffset(offset) {
11145 var lastLine;
11146 var lineToIndex;
11147 if (!this[fromOffsetCache]) {
11148 var lines = this.css.split("\n");
11149 lineToIndex = new Array(lines.length);
11150 var prevIndex = 0;
11151 for (var i2 = 0, l2 = lines.length; i2 < l2; i2++) {
11152 lineToIndex[i2] = prevIndex;
11153 prevIndex += lines[i2].length + 1;
11154 }
11155 this[fromOffsetCache] = lineToIndex;
11156 } else lineToIndex = this[fromOffsetCache];
11157 lastLine = lineToIndex[lineToIndex.length - 1];
11158 var min = 0;
11159 if (offset >= lastLine) min = lineToIndex.length - 1;
11160 else {
11161 var max = lineToIndex.length - 2;
11162 var mid;
11163 while (min < max) {
11164 mid = min + (max - min >> 1);
11165 if (offset < lineToIndex[mid]) max = mid - 1;
11166 else if (offset >= lineToIndex[mid + 1]) min = mid + 1;
11167 else {
11168 min = mid;
11169 break;
11170 }
11171 }
11172 }
11173 return {
11174 col: offset - lineToIndex[min] + 1,
11175 line: min + 1
11176 };
11177 };
11178 _proto.mapResolve = function mapResolve(file) {
11179 if (/^\w+:\/\//.test(file)) return file;
11180 return resolve$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
11181 };
11182 _proto.origin = function origin(line, column, endLine, endColumn) {
11183 if (!this.map) return false;
11184 var consumer = this.map.consumer();
11185 var from = consumer.originalPositionFor({
11186 column,
11187 line
11188 });
11189 if (!from.source) return false;
11190 var to;
11191 if (typeof endLine === "number") to = consumer.originalPositionFor({
11192 column: endColumn,
11193 line: endLine
11194 });
11195 var fromUrl;
11196 if (isAbsolute(from.source)) fromUrl = pathToFileURL$1(from.source);
11197 else fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile));
11198 var result2 = {
11199 column: from.column,
11200 endColumn: to && to.column,
11201 endLine: to && to.line,
11202 line: from.line,
11203 url: fromUrl.toString()
11204 };
11205 if (fromUrl.protocol === "file:") if (fileURLToPath) result2.file = fileURLToPath(fromUrl);
11206 else throw new Error("file: protocol is not available in this PostCSS build");
11207 var source = consumer.sourceContentFor(from.source);
11208 if (source) result2.source = source;
11209 return result2;
11210 };
11211 _proto.toJSON = function toJSON() {
11212 var json = {};
11213 for (var _i = 0, _iter = [
11214 "hasBOM",
11215 "css",
11216 "file",
11217 "id"
11218 ]; _i < _iter.length; _i++) {
11219 var name = _iter[_i];
11220 if (this[name] != null) json[name] = this[name];
11221 }
11222 if (this.map) {
11223 json.map = _extends({}, this.map);
11224 if (json.map.consumerCache) json.map.consumerCache = void 0;
11225 }
11226 return json;
11227 };
11228 _create_class(Input2, [{
11229 key: "from",
11230 get: function get() {
11231 return this.file || this.id;
11232 }
11233 }]);
11234 return Input2;
11235 }();
11236 var input = Input$4;
11237 Input$4.default = Input$4;
11238 if (terminalHighlight && terminalHighlight.registerInput) terminalHighlight.registerInput(Input$4);
11239 var SourceMapConsumer = require$$2.SourceMapConsumer;
11240 var SourceMapGenerator = require$$2.SourceMapGenerator;
11241 var dirname = require$$2.dirname;
11242 var relative = require$$2.relative;
11243 var resolve$3 = require$$2.resolve;
11244 var sep = require$$2.sep;
11245 var pathToFileURL = require$$2.pathToFileURL;
11246 var Input$3 = input;
11247 var sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
11248 var pathAvailable = Boolean(dirname && resolve$3 && relative && sep);
11249 var mapGenerator = /* @__PURE__ */ function() {
11250 function MapGenerator2(stringify2, root2, opts, cssString) {
11251 this.stringify = stringify2;
11252 this.mapOpts = opts.map || {};
11253 this.root = root2;
11254 this.opts = opts;
11255 this.css = cssString;
11256 this.originalCSS = cssString;
11257 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
11258 this.memoizedFileURLs = /* @__PURE__ */ new Map();
11259 this.memoizedPaths = /* @__PURE__ */ new Map();
11260 this.memoizedURLs = /* @__PURE__ */ new Map();
11261 }
11262 var _proto = MapGenerator2.prototype;
11263 _proto.addAnnotation = function addAnnotation() {
11264 var content;
11265 if (this.isInline()) content = "data:application/json;base64," + this.toBase64(this.map.toString());
11266 else if (typeof this.mapOpts.annotation === "string") content = this.mapOpts.annotation;
11267 else if (typeof this.mapOpts.annotation === "function") content = this.mapOpts.annotation(this.opts.to, this.root);
11268 else content = this.outputFile() + ".map";
11269 var eol = "\n";
11270 if (this.css.includes("\r\n")) eol = "\r\n";
11271 this.css += eol + "/*# sourceMappingURL=" + content + " */";
11272 };
11273 _proto.applyPrevMaps = function applyPrevMaps() {
11274 for (var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;) {
11275 var prev = _step.value;
11276 var from = this.toUrl(this.path(prev.file));
11277 var root2 = prev.root || dirname(prev.file);
11278 var map = void 0;
11279 if (this.mapOpts.sourcesContent === false) {
11280 map = new SourceMapConsumer(prev.text);
11281 if (map.sourcesContent) map.sourcesContent = null;
11282 } else map = prev.consumer();
11283 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
11284 }
11285 };
11286 _proto.clearAnnotation = function clearAnnotation() {
11287 if (this.mapOpts.annotation === false) return;
11288 if (this.root) {
11289 var node2;
11290 for (var i2 = this.root.nodes.length - 1; i2 >= 0; i2--) {
11291 node2 = this.root.nodes[i2];
11292 if (node2.type !== "comment") continue;
11293 if (node2.text.indexOf("# sourceMappingURL=") === 0) this.root.removeChild(i2);
11294 }
11295 } else if (this.css) this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
11296 };
11297 _proto.generate = function generate() {
11298 this.clearAnnotation();
11299 if (pathAvailable && sourceMapAvailable && this.isMap()) return this.generateMap();
11300 else {
11301 var result2 = "";
11302 this.stringify(this.root, function(i2) {
11303 result2 += i2;
11304 });
11305 return [result2];
11306 }
11307 };
11308 _proto.generateMap = function generateMap() {
11309 if (this.root) this.generateString();
11310 else if (this.previous().length === 1) {
11311 var prev = this.previous()[0].consumer();
11312 prev.file = this.outputFile();
11313 this.map = SourceMapGenerator.fromSourceMap(prev, { ignoreInvalidMapping: true });
11314 } else {
11315 this.map = new SourceMapGenerator({
11316 file: this.outputFile(),
11317 ignoreInvalidMapping: true
11318 });
11319 this.map.addMapping({
11320 generated: {
11321 column: 0,
11322 line: 1
11323 },
11324 original: {
11325 column: 0,
11326 line: 1
11327 },
11328 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
11329 });
11330 }
11331 if (this.isSourcesContent()) this.setSourcesContent();
11332 if (this.root && this.previous().length > 0) this.applyPrevMaps();
11333 if (this.isAnnotation()) this.addAnnotation();
11334 if (this.isInline()) return [this.css];
11335 else return [this.css, this.map];
11336 };
11337 _proto.generateString = function generateString() {
11338 var _this = this;
11339 this.css = "";
11340 this.map = new SourceMapGenerator({
11341 file: this.outputFile(),
11342 ignoreInvalidMapping: true
11343 });
11344 var line = 1;
11345 var column = 1;
11346 var noSource = "<no source>";
11347 var mapping = {
11348 generated: {
11349 column: 0,
11350 line: 0
11351 },
11352 original: {
11353 column: 0,
11354 line: 0
11355 },
11356 source: ""
11357 };
11358 var lines;
11359 var last;
11360 this.stringify(this.root, function(str, node2, type) {
11361 _this.css += str;
11362 if (node2 && type !== "end") {
11363 mapping.generated.line = line;
11364 mapping.generated.column = column - 1;
11365 if (node2.source && node2.source.start) {
11366 mapping.source = _this.sourcePath(node2);
11367 mapping.original.line = node2.source.start.line;
11368 mapping.original.column = node2.source.start.column - 1;
11369 _this.map.addMapping(mapping);
11370 } else {
11371 mapping.source = noSource;
11372 mapping.original.line = 1;
11373 mapping.original.column = 0;
11374 _this.map.addMapping(mapping);
11375 }
11376 }
11377 lines = str.match(/\n/g);
11378 if (lines) {
11379 line += lines.length;
11380 last = str.lastIndexOf("\n");
11381 column = str.length - last;
11382 } else column += str.length;
11383 if (node2 && type !== "start") {
11384 var p = node2.parent || { raws: {} };
11385 if (!(node2.type === "decl" || node2.type === "atrule" && !node2.nodes) || node2 !== p.last || p.raws.semicolon) if (node2.source && node2.source.end) {
11386 mapping.source = _this.sourcePath(node2);
11387 mapping.original.line = node2.source.end.line;
11388 mapping.original.column = node2.source.end.column - 1;
11389 mapping.generated.line = line;
11390 mapping.generated.column = column - 2;
11391 _this.map.addMapping(mapping);
11392 } else {
11393 mapping.source = noSource;
11394 mapping.original.line = 1;
11395 mapping.original.column = 0;
11396 mapping.generated.line = line;
11397 mapping.generated.column = column - 1;
11398 _this.map.addMapping(mapping);
11399 }
11400 }
11401 });
11402 };
11403 _proto.isAnnotation = function isAnnotation() {
11404 if (this.isInline()) return true;
11405 if (typeof this.mapOpts.annotation !== "undefined") return this.mapOpts.annotation;
11406 if (this.previous().length) return this.previous().some(function(i2) {
11407 return i2.annotation;
11408 });
11409 return true;
11410 };
11411 _proto.isInline = function isInline() {
11412 if (typeof this.mapOpts.inline !== "undefined") return this.mapOpts.inline;
11413 var annotation = this.mapOpts.annotation;
11414 if (typeof annotation !== "undefined" && annotation !== true) return false;
11415 if (this.previous().length) return this.previous().some(function(i2) {
11416 return i2.inline;
11417 });
11418 return true;
11419 };
11420 _proto.isMap = function isMap() {
11421 if (typeof this.opts.map !== "undefined") return !!this.opts.map;
11422 return this.previous().length > 0;
11423 };
11424 _proto.isSourcesContent = function isSourcesContent() {
11425 if (typeof this.mapOpts.sourcesContent !== "undefined") return this.mapOpts.sourcesContent;
11426 if (this.previous().length) return this.previous().some(function(i2) {
11427 return i2.withContent();
11428 });
11429 return true;
11430 };
11431 _proto.outputFile = function outputFile() {
11432 if (this.opts.to) return this.path(this.opts.to);
11433 else if (this.opts.from) return this.path(this.opts.from);
11434 else return "to.css";
11435 };
11436 _proto.path = function path(file) {
11437 if (this.mapOpts.absolute) return file;
11438 if (file.charCodeAt(0) === 60) return file;
11439 if (/^\w+:\/\//.test(file)) return file;
11440 var cached = this.memoizedPaths.get(file);
11441 if (cached) return cached;
11442 var from = this.opts.to ? dirname(this.opts.to) : ".";
11443 if (typeof this.mapOpts.annotation === "string") from = dirname(resolve$3(from, this.mapOpts.annotation));
11444 var path = relative(from, file);
11445 this.memoizedPaths.set(file, path);
11446 return path;
11447 };
11448 _proto.previous = function previous() {
11449 var _this = this;
11450 if (!this.previousMaps) {
11451 this.previousMaps = [];
11452 if (this.root) this.root.walk(function(node2) {
11453 if (node2.source && node2.source.input.map) {
11454 var map = node2.source.input.map;
11455 if (!_this.previousMaps.includes(map)) _this.previousMaps.push(map);
11456 }
11457 });
11458 else {
11459 var input2 = new Input$3(this.originalCSS, this.opts);
11460 if (input2.map) this.previousMaps.push(input2.map);
11461 }
11462 }
11463 return this.previousMaps;
11464 };
11465 _proto.setSourcesContent = function setSourcesContent() {
11466 var _this = this;
11467 var already = {};
11468 if (this.root) this.root.walk(function(node2) {
11469 if (node2.source) {
11470 var from = node2.source.input.from;
11471 if (from && !already[from]) {
11472 already[from] = true;
11473 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
11474 _this.map.setSourceContent(fromUrl, node2.source.input.css);
11475 }
11476 }
11477 });
11478 else if (this.css) {
11479 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
11480 this.map.setSourceContent(from, this.css);
11481 }
11482 };
11483 _proto.sourcePath = function sourcePath(node2) {
11484 if (this.mapOpts.from) return this.toUrl(this.mapOpts.from);
11485 else if (this.usesFileUrls) return this.toFileUrl(node2.source.input.from);
11486 else return this.toUrl(this.path(node2.source.input.from));
11487 };
11488 _proto.toBase64 = function toBase64(str) {
11489 if (Buffer) return Buffer.from(str).toString("base64");
11490 else return window.btoa(unescape(encodeURIComponent(str)));
11491 };
11492 _proto.toFileUrl = function toFileUrl(path) {
11493 var cached = this.memoizedFileURLs.get(path);
11494 if (cached) return cached;
11495 if (pathToFileURL) {
11496 var fileURL = pathToFileURL(path).toString();
11497 this.memoizedFileURLs.set(path, fileURL);
11498 return fileURL;
11499 } else throw new Error("`map.absolute` option is not available in this PostCSS build");
11500 };
11501 _proto.toUrl = function toUrl(path) {
11502 var cached = this.memoizedURLs.get(path);
11503 if (cached) return cached;
11504 if (sep === "\\") path = path.replace(/\\/g, "/");
11505 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
11506 this.memoizedURLs.set(path, url);
11507 return url;
11508 };
11509 return MapGenerator2;
11510 }();
11511 var Comment$4 = /*#__PURE__*/ function(Node$2) {
11512 _inherits(Comment2, Node$2);
11513 function Comment2(defaults) {
11514 var _this = Node$2.call(this, defaults) || this;
11515 _this.type = "comment";
11516 return _this;
11517 }
11518 return Comment2;
11519 }(node);
11520 var comment = Comment$4;
11521 Comment$4.default = Comment$4;
11522 var isClean$1 = symbols.isClean;
11523 var my$1 = symbols.my;
11524 var Declaration$3 = declaration;
11525 var Comment$3 = comment;
11526 var Node$1 = node;
11527 var parse$4;
11528 var Rule$4;
11529 var AtRule$4;
11530 var Root$6;
11531 function cleanSource(nodes) {
11532 return nodes.map(function(i2) {
11533 if (i2.nodes) i2.nodes = cleanSource(i2.nodes);
11534 delete i2.source;
11535 return i2;
11536 });
11537 }
11538 function markDirtyUp(node2) {
11539 node2[isClean$1] = false;
11540 if (node2.proxyOf.nodes) for (var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;) {
11541 var i2 = _step.value;
11542 markDirtyUp(i2);
11543 }
11544 }
11545 var Container$7 = /*#__PURE__*/ function(Node$1) {
11546 _inherits(Container2, Node$1);
11547 function Container2() {
11548 return Node$1.apply(this, arguments) || this;
11549 }
11550 var _proto = Container2.prototype;
11551 _proto.append = function append() {
11552 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
11553 for (var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;) {
11554 var child = _step.value;
11555 for (var _iterator1 = _create_for_of_iterator_helper_loose(this.normalize(child, this.last)), _step1; !(_step1 = _iterator1()).done;) {
11556 var node2 = _step1.value;
11557 this.proxyOf.nodes.push(node2);
11558 }
11559 }
11560 this.markDirty();
11561 return this;
11562 };
11563 _proto.cleanRaws = function cleanRaws(keepBetween) {
11564 Node$1.prototype.cleanRaws.call(this, keepBetween);
11565 if (this.nodes) for (var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;) _step.value.cleanRaws(keepBetween);
11566 };
11567 _proto.each = function each(callback) {
11568 if (!this.proxyOf.nodes) return void 0;
11569 var iterator = this.getIterator();
11570 var index2;
11571 var result2;
11572 while (this.indexes[iterator] < this.proxyOf.nodes.length) {
11573 index2 = this.indexes[iterator];
11574 result2 = callback(this.proxyOf.nodes[index2], index2);
11575 if (result2 === false) break;
11576 this.indexes[iterator] += 1;
11577 }
11578 delete this.indexes[iterator];
11579 return result2;
11580 };
11581 _proto.every = function every(condition) {
11582 return this.nodes.every(condition);
11583 };
11584 _proto.getIterator = function getIterator() {
11585 if (!this.lastEach) this.lastEach = 0;
11586 if (!this.indexes) this.indexes = {};
11587 this.lastEach += 1;
11588 var iterator = this.lastEach;
11589 this.indexes[iterator] = 0;
11590 return iterator;
11591 };
11592 _proto.getProxyProcessor = function getProxyProcessor() {
11593 return {
11594 get: function get(node2, prop) {
11595 if (prop === "proxyOf") return node2;
11596 else if (!node2[prop]) return node2[prop];
11597 else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) return function() {
11598 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
11599 var _node2;
11600 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
11601 if (typeof i2 === "function") return function(child, index2) {
11602 return i2(child.toProxy(), index2);
11603 };
11604 else return i2;
11605 })));
11606 };
11607 else if (prop === "every" || prop === "some") return function(cb) {
11608 return node2[prop](function(child) {
11609 for (var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) other[_key - 1] = arguments[_key];
11610 return cb.apply(void 0, [].concat([child.toProxy()], other));
11611 });
11612 };
11613 else if (prop === "root") return function() {
11614 return node2.root().toProxy();
11615 };
11616 else if (prop === "nodes") return node2.nodes.map(function(i2) {
11617 return i2.toProxy();
11618 });
11619 else if (prop === "first" || prop === "last") return node2[prop].toProxy();
11620 else return node2[prop];
11621 },
11622 set: function set(node2, prop, value) {
11623 if (node2[prop] === value) return true;
11624 node2[prop] = value;
11625 if (prop === "name" || prop === "params" || prop === "selector") node2.markDirty();
11626 return true;
11627 }
11628 };
11629 };
11630 _proto.index = function index(child) {
11631 if (typeof child === "number") return child;
11632 if (child.proxyOf) child = child.proxyOf;
11633 return this.proxyOf.nodes.indexOf(child);
11634 };
11635 _proto.insertAfter = function insertAfter(exist, add) {
11636 var existIndex = this.index(exist);
11637 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
11638 existIndex = this.index(exist);
11639 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
11640 var node2 = _step.value;
11641 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
11642 }
11643 var index2;
11644 for (var id in this.indexes) {
11645 index2 = this.indexes[id];
11646 if (existIndex < index2) this.indexes[id] = index2 + nodes.length;
11647 }
11648 this.markDirty();
11649 return this;
11650 };
11651 _proto.insertBefore = function insertBefore(exist, add) {
11652 var existIndex = this.index(exist);
11653 var type = existIndex === 0 ? "prepend" : false;
11654 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
11655 existIndex = this.index(exist);
11656 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
11657 var node2 = _step.value;
11658 this.proxyOf.nodes.splice(existIndex, 0, node2);
11659 }
11660 var index2;
11661 for (var id in this.indexes) {
11662 index2 = this.indexes[id];
11663 if (existIndex <= index2) this.indexes[id] = index2 + nodes.length;
11664 }
11665 this.markDirty();
11666 return this;
11667 };
11668 _proto.normalize = function normalize(nodes, sample) {
11669 var _this = this;
11670 if (typeof nodes === "string") nodes = cleanSource(parse$4(nodes).nodes);
11671 else if (typeof nodes === "undefined") nodes = [];
11672 else if (Array.isArray(nodes)) {
11673 nodes = nodes.slice(0);
11674 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
11675 var i2 = _step.value;
11676 if (i2.parent) i2.parent.removeChild(i2, "ignore");
11677 }
11678 } else if (nodes.type === "root" && this.type !== "document") {
11679 nodes = nodes.nodes.slice(0);
11680 for (var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;) {
11681 var i21 = _step1.value;
11682 if (i21.parent) i21.parent.removeChild(i21, "ignore");
11683 }
11684 } else if (nodes.type) nodes = [nodes];
11685 else if (nodes.prop) {
11686 if (typeof nodes.value === "undefined") throw new Error("Value field is missed in node creation");
11687 else if (typeof nodes.value !== "string") nodes.value = String(nodes.value);
11688 nodes = [new Declaration$3(nodes)];
11689 } else if (nodes.selector) nodes = [new Rule$4(nodes)];
11690 else if (nodes.name) nodes = [new AtRule$4(nodes)];
11691 else if (nodes.text) nodes = [new Comment$3(nodes)];
11692 else throw new Error("Unknown node type in node creation");
11693 return nodes.map(function(i2) {
11694 if (!i2[my$1]) Container2.rebuild(i2);
11695 i2 = i2.proxyOf;
11696 if (i2.parent) i2.parent.removeChild(i2);
11697 if (i2[isClean$1]) markDirtyUp(i2);
11698 if (typeof i2.raws.before === "undefined") {
11699 if (sample && typeof sample.raws.before !== "undefined") i2.raws.before = sample.raws.before.replace(/\S/g, "");
11700 }
11701 i2.parent = _this.proxyOf;
11702 return i2;
11703 });
11704 };
11705 _proto.prepend = function prepend() {
11706 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
11707 children = children.reverse();
11708 for (var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;) {
11709 var child = _step.value;
11710 var nodes = this.normalize(child, this.first, "prepend").reverse();
11711 for (var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;) {
11712 var node2 = _step1.value;
11713 this.proxyOf.nodes.unshift(node2);
11714 }
11715 for (var id in this.indexes) this.indexes[id] = this.indexes[id] + nodes.length;
11716 }
11717 this.markDirty();
11718 return this;
11719 };
11720 _proto.push = function push(child) {
11721 child.parent = this;
11722 this.proxyOf.nodes.push(child);
11723 return this;
11724 };
11725 _proto.removeAll = function removeAll() {
11726 for (var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;) {
11727 var node2 = _step.value;
11728 node2.parent = void 0;
11729 }
11730 this.proxyOf.nodes = [];
11731 this.markDirty();
11732 return this;
11733 };
11734 _proto.removeChild = function removeChild(child) {
11735 child = this.index(child);
11736 this.proxyOf.nodes[child].parent = void 0;
11737 this.proxyOf.nodes.splice(child, 1);
11738 var index2;
11739 for (var id in this.indexes) {
11740 index2 = this.indexes[id];
11741 if (index2 >= child) this.indexes[id] = index2 - 1;
11742 }
11743 this.markDirty();
11744 return this;
11745 };
11746 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
11747 if (!callback) {
11748 callback = opts;
11749 opts = {};
11750 }
11751 this.walkDecls(function(decl) {
11752 if (opts.props && !opts.props.includes(decl.prop)) return;
11753 if (opts.fast && !decl.value.includes(opts.fast)) return;
11754 decl.value = decl.value.replace(pattern, callback);
11755 });
11756 this.markDirty();
11757 return this;
11758 };
11759 _proto.some = function some(condition) {
11760 return this.nodes.some(condition);
11761 };
11762 _proto.walk = function walk(callback) {
11763 return this.each(function(child, i2) {
11764 var result2;
11765 try {
11766 result2 = callback(child, i2);
11767 } catch (e2) {
11768 throw child.addToError(e2);
11769 }
11770 if (result2 !== false && child.walk) result2 = child.walk(callback);
11771 return result2;
11772 });
11773 };
11774 _proto.walkAtRules = function walkAtRules(name, callback) {
11775 if (!callback) {
11776 callback = name;
11777 return this.walk(function(child, i2) {
11778 if (child.type === "atrule") return callback(child, i2);
11779 });
11780 }
11781 if (_instanceof(name, RegExp)) return this.walk(function(child, i2) {
11782 if (child.type === "atrule" && name.test(child.name)) return callback(child, i2);
11783 });
11784 return this.walk(function(child, i2) {
11785 if (child.type === "atrule" && child.name === name) return callback(child, i2);
11786 });
11787 };
11788 _proto.walkComments = function walkComments(callback) {
11789 return this.walk(function(child, i2) {
11790 if (child.type === "comment") return callback(child, i2);
11791 });
11792 };
11793 _proto.walkDecls = function walkDecls(prop, callback) {
11794 if (!callback) {
11795 callback = prop;
11796 return this.walk(function(child, i2) {
11797 if (child.type === "decl") return callback(child, i2);
11798 });
11799 }
11800 if (_instanceof(prop, RegExp)) return this.walk(function(child, i2) {
11801 if (child.type === "decl" && prop.test(child.prop)) return callback(child, i2);
11802 });
11803 return this.walk(function(child, i2) {
11804 if (child.type === "decl" && child.prop === prop) return callback(child, i2);
11805 });
11806 };
11807 _proto.walkRules = function walkRules(selector, callback) {
11808 if (!callback) {
11809 callback = selector;
11810 return this.walk(function(child, i2) {
11811 if (child.type === "rule") return callback(child, i2);
11812 });
11813 }
11814 if (_instanceof(selector, RegExp)) return this.walk(function(child, i2) {
11815 if (child.type === "rule" && selector.test(child.selector)) return callback(child, i2);
11816 });
11817 return this.walk(function(child, i2) {
11818 if (child.type === "rule" && child.selector === selector) return callback(child, i2);
11819 });
11820 };
11821 _create_class(Container2, [{
11822 key: "first",
11823 get: function get() {
11824 if (!this.proxyOf.nodes) return void 0;
11825 return this.proxyOf.nodes[0];
11826 }
11827 }, {
11828 key: "last",
11829 get: function get() {
11830 if (!this.proxyOf.nodes) return void 0;
11831 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
11832 }
11833 }]);
11834 return Container2;
11835 }(Node$1);
11836 Container$7.registerParse = function(dependant) {
11837 parse$4 = dependant;
11838 };
11839 Container$7.registerRule = function(dependant) {
11840 Rule$4 = dependant;
11841 };
11842 Container$7.registerAtRule = function(dependant) {
11843 AtRule$4 = dependant;
11844 };
11845 Container$7.registerRoot = function(dependant) {
11846 Root$6 = dependant;
11847 };
11848 var container = Container$7;
11849 Container$7.default = Container$7;
11850 Container$7.rebuild = function(node2) {
11851 if (node2.type === "atrule") Object.setPrototypeOf(node2, AtRule$4.prototype);
11852 else if (node2.type === "rule") Object.setPrototypeOf(node2, Rule$4.prototype);
11853 else if (node2.type === "decl") Object.setPrototypeOf(node2, Declaration$3.prototype);
11854 else if (node2.type === "comment") Object.setPrototypeOf(node2, Comment$3.prototype);
11855 else if (node2.type === "root") Object.setPrototypeOf(node2, Root$6.prototype);
11856 node2[my$1] = true;
11857 if (node2.nodes) node2.nodes.forEach(function(child) {
11858 Container$7.rebuild(child);
11859 });
11860 };
11861 var Container$6 = container;
11862 var LazyResult$4;
11863 var Processor$3;
11864 var Document$3 = /*#__PURE__*/ function(Container$6) {
11865 _inherits(Document23, Container$6);
11866 function Document23(defaults) {
11867 var _this = Container$6.call(this, _extends({ type: "document" }, defaults)) || this;
11868 if (!_this.nodes) _this.nodes = [];
11869 return _this;
11870 }
11871 var _proto = Document23.prototype;
11872 _proto.toResult = function toResult(opts) {
11873 if (opts === void 0) opts = {};
11874 return new LazyResult$4(new Processor$3(), this, opts).stringify();
11875 };
11876 return Document23;
11877 }(Container$6);
11878 Document$3.registerLazyResult = function(dependant) {
11879 LazyResult$4 = dependant;
11880 };
11881 Document$3.registerProcessor = function(dependant) {
11882 Processor$3 = dependant;
11883 };
11884 var document$1$2 = Document$3;
11885 Document$3.default = Document$3;
11886 var printed = {};
11887 var warnOnce$2 = function warnOnce2(message) {
11888 if (printed[message]) return;
11889 printed[message] = true;
11890 if (typeof console !== "undefined" && console.warn) console.warn(message);
11891 };
11892 var Warning$2 = /*#__PURE__*/ function() {
11893 function Warning2(text, opts) {
11894 if (opts === void 0) opts = {};
11895 this.type = "warning";
11896 this.text = text;
11897 if (opts.node && opts.node.source) {
11898 var range = opts.node.rangeBy(opts);
11899 this.line = range.start.line;
11900 this.column = range.start.column;
11901 this.endLine = range.end.line;
11902 this.endColumn = range.end.column;
11903 }
11904 for (var opt in opts) this[opt] = opts[opt];
11905 }
11906 var _proto = Warning2.prototype;
11907 _proto.toString = function toString() {
11908 if (this.node) return this.node.error(this.text, {
11909 index: this.index,
11910 plugin: this.plugin,
11911 word: this.word
11912 }).message;
11913 if (this.plugin) return this.plugin + ": " + this.text;
11914 return this.text;
11915 };
11916 return Warning2;
11917 }();
11918 var warning = Warning$2;
11919 Warning$2.default = Warning$2;
11920 var Warning$1 = warning;
11921 var Result$3 = /*#__PURE__*/ function() {
11922 function Result2(processor2, root2, opts) {
11923 this.processor = processor2;
11924 this.messages = [];
11925 this.root = root2;
11926 this.opts = opts;
11927 this.css = void 0;
11928 this.map = void 0;
11929 }
11930 var _proto = Result2.prototype;
11931 _proto.toString = function toString() {
11932 return this.css;
11933 };
11934 _proto.warn = function warn(text, opts) {
11935 if (opts === void 0) opts = {};
11936 if (!opts.plugin) {
11937 if (this.lastPlugin && this.lastPlugin.postcssPlugin) opts.plugin = this.lastPlugin.postcssPlugin;
11938 }
11939 var warning2 = new Warning$1(text, opts);
11940 this.messages.push(warning2);
11941 return warning2;
11942 };
11943 _proto.warnings = function warnings() {
11944 return this.messages.filter(function(i2) {
11945 return i2.type === "warning";
11946 });
11947 };
11948 _create_class(Result2, [{
11949 key: "content",
11950 get: function get() {
11951 return this.css;
11952 }
11953 }]);
11954 return Result2;
11955 }();
11956 var result = Result$3;
11957 Result$3.default = Result$3;
11958 var SINGLE_QUOTE = "'".charCodeAt(0);
11959 var DOUBLE_QUOTE = "\"".charCodeAt(0);
11960 var BACKSLASH = "\\".charCodeAt(0);
11961 var SLASH = "/".charCodeAt(0);
11962 var NEWLINE = "\n".charCodeAt(0);
11963 var SPACE = " ".charCodeAt(0);
11964 var FEED = "\f".charCodeAt(0);
11965 var TAB = " ".charCodeAt(0);
11966 var CR = "\r".charCodeAt(0);
11967 var OPEN_SQUARE = "[".charCodeAt(0);
11968 var CLOSE_SQUARE = "]".charCodeAt(0);
11969 var OPEN_PARENTHESES = "(".charCodeAt(0);
11970 var CLOSE_PARENTHESES = ")".charCodeAt(0);
11971 var OPEN_CURLY = "{".charCodeAt(0);
11972 var CLOSE_CURLY = "}".charCodeAt(0);
11973 var SEMICOLON = ";".charCodeAt(0);
11974 var ASTERISK = "*".charCodeAt(0);
11975 var COLON = ":".charCodeAt(0);
11976 var AT = "@".charCodeAt(0);
11977 var RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
11978 var RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
11979 var RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
11980 var RE_HEX_ESCAPE = /[\da-f]/i;
11981 var tokenize = function tokenizer2(input2, options) {
11982 if (options === void 0) options = {};
11983 var css = input2.css.valueOf();
11984 var ignore = options.ignoreErrors;
11985 var code;
11986 var next;
11987 var quote;
11988 var content;
11989 var escape;
11990 var escaped;
11991 var escapePos;
11992 var prev;
11993 var n2;
11994 var currentToken;
11995 var length = css.length;
11996 var pos = 0;
11997 var buffer = [];
11998 var returned = [];
11999 function position() {
12000 return pos;
12001 }
12002 function unclosed(what) {
12003 throw input2.error("Unclosed " + what, pos);
12004 }
12005 function endOfFile() {
12006 return returned.length === 0 && pos >= length;
12007 }
12008 function nextToken(opts) {
12009 if (returned.length) return returned.pop();
12010 if (pos >= length) return;
12011 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
12012 code = css.charCodeAt(pos);
12013 switch (code) {
12014 case NEWLINE:
12015 case SPACE:
12016 case TAB:
12017 case CR:
12018 case FEED:
12019 next = pos;
12020 do {
12021 next += 1;
12022 code = css.charCodeAt(next);
12023 } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
12024 currentToken = ["space", css.slice(pos, next)];
12025 pos = next - 1;
12026 break;
12027 case OPEN_SQUARE:
12028 case CLOSE_SQUARE:
12029 case OPEN_CURLY:
12030 case CLOSE_CURLY:
12031 case COLON:
12032 case SEMICOLON:
12033 case CLOSE_PARENTHESES:
12034 var controlChar = String.fromCharCode(code);
12035 currentToken = [
12036 controlChar,
12037 controlChar,
12038 pos
12039 ];
12040 break;
12041 case OPEN_PARENTHESES:
12042 prev = buffer.length ? buffer.pop()[1] : "";
12043 n2 = css.charCodeAt(pos + 1);
12044 if (prev === "url" && n2 !== SINGLE_QUOTE && n2 !== DOUBLE_QUOTE && n2 !== SPACE && n2 !== NEWLINE && n2 !== TAB && n2 !== FEED && n2 !== CR) {
12045 next = pos;
12046 do {
12047 escaped = false;
12048 next = css.indexOf(")", next + 1);
12049 if (next === -1) if (ignore || ignoreUnclosed) {
12050 next = pos;
12051 break;
12052 } else unclosed("bracket");
12053 escapePos = next;
12054 while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
12055 escapePos -= 1;
12056 escaped = !escaped;
12057 }
12058 } while (escaped);
12059 currentToken = [
12060 "brackets",
12061 css.slice(pos, next + 1),
12062 pos,
12063 next
12064 ];
12065 pos = next;
12066 } else {
12067 next = css.indexOf(")", pos + 1);
12068 content = css.slice(pos, next + 1);
12069 if (next === -1 || RE_BAD_BRACKET.test(content)) currentToken = [
12070 "(",
12071 "(",
12072 pos
12073 ];
12074 else {
12075 currentToken = [
12076 "brackets",
12077 content,
12078 pos,
12079 next
12080 ];
12081 pos = next;
12082 }
12083 }
12084 break;
12085 case SINGLE_QUOTE:
12086 case DOUBLE_QUOTE:
12087 quote = code === SINGLE_QUOTE ? "'" : "\"";
12088 next = pos;
12089 do {
12090 escaped = false;
12091 next = css.indexOf(quote, next + 1);
12092 if (next === -1) if (ignore || ignoreUnclosed) {
12093 next = pos + 1;
12094 break;
12095 } else unclosed("string");
12096 escapePos = next;
12097 while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
12098 escapePos -= 1;
12099 escaped = !escaped;
12100 }
12101 } while (escaped);
12102 currentToken = [
12103 "string",
12104 css.slice(pos, next + 1),
12105 pos,
12106 next
12107 ];
12108 pos = next;
12109 break;
12110 case AT:
12111 RE_AT_END.lastIndex = pos + 1;
12112 RE_AT_END.test(css);
12113 if (RE_AT_END.lastIndex === 0) next = css.length - 1;
12114 else next = RE_AT_END.lastIndex - 2;
12115 currentToken = [
12116 "at-word",
12117 css.slice(pos, next + 1),
12118 pos,
12119 next
12120 ];
12121 pos = next;
12122 break;
12123 case BACKSLASH:
12124 next = pos;
12125 escape = true;
12126 while (css.charCodeAt(next + 1) === BACKSLASH) {
12127 next += 1;
12128 escape = !escape;
12129 }
12130 code = css.charCodeAt(next + 1);
12131 if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
12132 next += 1;
12133 if (RE_HEX_ESCAPE.test(css.charAt(next))) {
12134 while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) next += 1;
12135 if (css.charCodeAt(next + 1) === SPACE) next += 1;
12136 }
12137 }
12138 currentToken = [
12139 "word",
12140 css.slice(pos, next + 1),
12141 pos,
12142 next
12143 ];
12144 pos = next;
12145 break;
12146 default:
12147 if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
12148 next = css.indexOf("*/", pos + 2) + 1;
12149 if (next === 0) if (ignore || ignoreUnclosed) next = css.length;
12150 else unclosed("comment");
12151 currentToken = [
12152 "comment",
12153 css.slice(pos, next + 1),
12154 pos,
12155 next
12156 ];
12157 pos = next;
12158 } else {
12159 RE_WORD_END.lastIndex = pos + 1;
12160 RE_WORD_END.test(css);
12161 if (RE_WORD_END.lastIndex === 0) next = css.length - 1;
12162 else next = RE_WORD_END.lastIndex - 2;
12163 currentToken = [
12164 "word",
12165 css.slice(pos, next + 1),
12166 pos,
12167 next
12168 ];
12169 buffer.push(currentToken);
12170 pos = next;
12171 }
12172 break;
12173 }
12174 pos++;
12175 return currentToken;
12176 }
12177 function back(token) {
12178 returned.push(token);
12179 }
12180 return {
12181 back,
12182 endOfFile,
12183 nextToken,
12184 position
12185 };
12186 };
12187 var Container$5 = container;
12188 var AtRule$3 = /*#__PURE__*/ function(Container$5) {
12189 _inherits(AtRule2, Container$5);
12190 function AtRule2(defaults) {
12191 var _this = Container$5.call(this, defaults) || this;
12192 _this.type = "atrule";
12193 return _this;
12194 }
12195 var _proto = AtRule2.prototype;
12196 _proto.append = function append() {
12197 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
12198 var _Container$5_prototype_append;
12199 if (!this.proxyOf.nodes) this.nodes = [];
12200 return (_Container$5_prototype_append = Container$5.prototype.append).call.apply(_Container$5_prototype_append, [].concat([this], children));
12201 };
12202 _proto.prepend = function prepend() {
12203 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
12204 var _Container$5_prototype_prepend;
12205 if (!this.proxyOf.nodes) this.nodes = [];
12206 return (_Container$5_prototype_prepend = Container$5.prototype.prepend).call.apply(_Container$5_prototype_prepend, [].concat([this], children));
12207 };
12208 return AtRule2;
12209 }(Container$5);
12210 var atRule = AtRule$3;
12211 AtRule$3.default = AtRule$3;
12212 Container$5.registerAtRule(AtRule$3);
12213 var Container$4 = container;
12214 var LazyResult$3;
12215 var Processor$2;
12216 var Root$5 = /*#__PURE__*/ function(Container$4) {
12217 _inherits(Root2, Container$4);
12218 function Root2(defaults) {
12219 var _this = Container$4.call(this, defaults) || this;
12220 _this.type = "root";
12221 if (!_this.nodes) _this.nodes = [];
12222 return _this;
12223 }
12224 var _proto = Root2.prototype;
12225 _proto.normalize = function normalize(child, sample, type) {
12226 var nodes = Container$4.prototype.normalize.call(this, child);
12227 if (sample) {
12228 if (type === "prepend") if (this.nodes.length > 1) sample.raws.before = this.nodes[1].raws.before;
12229 else delete sample.raws.before;
12230 else if (this.first !== sample) for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
12231 var node2 = _step.value;
12232 node2.raws.before = sample.raws.before;
12233 }
12234 }
12235 return nodes;
12236 };
12237 _proto.removeChild = function removeChild(child, ignore) {
12238 var index2 = this.index(child);
12239 if (!ignore && index2 === 0 && this.nodes.length > 1) this.nodes[1].raws.before = this.nodes[index2].raws.before;
12240 return Container$4.prototype.removeChild.call(this, child);
12241 };
12242 _proto.toResult = function toResult(opts) {
12243 if (opts === void 0) opts = {};
12244 return new LazyResult$3(new Processor$2(), this, opts).stringify();
12245 };
12246 return Root2;
12247 }(Container$4);
12248 Root$5.registerLazyResult = function(dependant) {
12249 LazyResult$3 = dependant;
12250 };
12251 Root$5.registerProcessor = function(dependant) {
12252 Processor$2 = dependant;
12253 };
12254 var root = Root$5;
12255 Root$5.default = Root$5;
12256 Container$4.registerRoot(Root$5);
12257 var list$2 = {
12258 comma: function comma(string) {
12259 return list$2.split(string, [","], true);
12260 },
12261 space: function space(string) {
12262 return list$2.split(string, [
12263 " ",
12264 "\n",
12265 " "
12266 ]);
12267 },
12268 split: function split(string, separators, last) {
12269 var array = [];
12270 var current = "";
12271 var split = false;
12272 var func = 0;
12273 var inQuote = false;
12274 var prevQuote = "";
12275 var escape = false;
12276 for (var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;) {
12277 var letter = _step.value;
12278 if (escape) escape = false;
12279 else if (letter === "\\") escape = true;
12280 else if (inQuote) {
12281 if (letter === prevQuote) inQuote = false;
12282 } else if (letter === "\"" || letter === "'") {
12283 inQuote = true;
12284 prevQuote = letter;
12285 } else if (letter === "(") func += 1;
12286 else if (letter === ")") {
12287 if (func > 0) func -= 1;
12288 } else if (func === 0) {
12289 if (separators.includes(letter)) split = true;
12290 }
12291 if (split) {
12292 if (current !== "") array.push(current.trim());
12293 current = "";
12294 split = false;
12295 } else current += letter;
12296 }
12297 if (last || current !== "") array.push(current.trim());
12298 return array;
12299 }
12300 };
12301 var list_1 = list$2;
12302 list$2.default = list$2;
12303 var Container$3 = container;
12304 var list$1 = list_1;
12305 var Rule$3 = /*#__PURE__*/ function(Container$3) {
12306 _inherits(Rule2, Container$3);
12307 function Rule2(defaults) {
12308 var _this = Container$3.call(this, defaults) || this;
12309 _this.type = "rule";
12310 if (!_this.nodes) _this.nodes = [];
12311 return _this;
12312 }
12313 _create_class(Rule2, [{
12314 key: "selectors",
12315 get: function get() {
12316 return list$1.comma(this.selector);
12317 },
12318 set: function set(values) {
12319 var match = this.selector ? this.selector.match(/,\s*/) : null;
12320 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
12321 this.selector = values.join(sep2);
12322 }
12323 }]);
12324 return Rule2;
12325 }(Container$3);
12326 var rule = Rule$3;
12327 Rule$3.default = Rule$3;
12328 Container$3.registerRule(Rule$3);
12329 var Declaration$2 = declaration;
12330 var tokenizer22 = tokenize;
12331 var Comment$2 = comment;
12332 var AtRule$2 = atRule;
12333 var Root$4 = root;
12334 var Rule$2 = rule;
12335 var SAFE_COMMENT_NEIGHBOR = {
12336 empty: true,
12337 space: true
12338 };
12339 function findLastWithPosition(tokens) {
12340 for (var i2 = tokens.length - 1; i2 >= 0; i2--) {
12341 var token = tokens[i2];
12342 var pos = token[3] || token[2];
12343 if (pos) return pos;
12344 }
12345 }
12346 var parser = /* @__PURE__ */ function() {
12347 function Parser2(input2) {
12348 this.input = input2;
12349 this.root = new Root$4();
12350 this.current = this.root;
12351 this.spaces = "";
12352 this.semicolon = false;
12353 this.createTokenizer();
12354 this.root.source = {
12355 input: input2,
12356 start: {
12357 column: 1,
12358 line: 1,
12359 offset: 0
12360 }
12361 };
12362 }
12363 var _proto = Parser2.prototype;
12364 _proto.atrule = function atrule(token) {
12365 var node2 = new AtRule$2();
12366 node2.name = token[1].slice(1);
12367 if (node2.name === "") this.unnamedAtrule(node2, token);
12368 this.init(node2, token[2]);
12369 var type;
12370 var prev;
12371 var shift;
12372 var last = false;
12373 var open = false;
12374 var params = [];
12375 var brackets = [];
12376 while (!this.tokenizer.endOfFile()) {
12377 token = this.tokenizer.nextToken();
12378 type = token[0];
12379 if (type === "(" || type === "[") brackets.push(type === "(" ? ")" : "]");
12380 else if (type === "{" && brackets.length > 0) brackets.push("}");
12381 else if (type === brackets[brackets.length - 1]) brackets.pop();
12382 if (brackets.length === 0) if (type === ";") {
12383 node2.source.end = this.getPosition(token[2]);
12384 node2.source.end.offset++;
12385 this.semicolon = true;
12386 break;
12387 } else if (type === "{") {
12388 open = true;
12389 break;
12390 } else if (type === "}") {
12391 if (params.length > 0) {
12392 shift = params.length - 1;
12393 prev = params[shift];
12394 while (prev && prev[0] === "space") prev = params[--shift];
12395 if (prev) {
12396 node2.source.end = this.getPosition(prev[3] || prev[2]);
12397 node2.source.end.offset++;
12398 }
12399 }
12400 this.end(token);
12401 break;
12402 } else params.push(token);
12403 else params.push(token);
12404 if (this.tokenizer.endOfFile()) {
12405 last = true;
12406 break;
12407 }
12408 }
12409 node2.raws.between = this.spacesAndCommentsFromEnd(params);
12410 if (params.length) {
12411 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
12412 this.raw(node2, "params", params);
12413 if (last) {
12414 token = params[params.length - 1];
12415 node2.source.end = this.getPosition(token[3] || token[2]);
12416 node2.source.end.offset++;
12417 this.spaces = node2.raws.between;
12418 node2.raws.between = "";
12419 }
12420 } else {
12421 node2.raws.afterName = "";
12422 node2.params = "";
12423 }
12424 if (open) {
12425 node2.nodes = [];
12426 this.current = node2;
12427 }
12428 };
12429 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
12430 var colon = this.colon(tokens);
12431 if (colon === false) return;
12432 var founded = 0;
12433 var token;
12434 for (var j = colon - 1; j >= 0; j--) {
12435 token = tokens[j];
12436 if (token[0] !== "space") {
12437 founded += 1;
12438 if (founded === 2) break;
12439 }
12440 }
12441 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
12442 };
12443 _proto.colon = function colon(tokens) {
12444 var brackets = 0;
12445 var token;
12446 var type;
12447 var prev;
12448 for (var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;) {
12449 var _step_value = _step.value;
12450 var i2 = _step_value[0];
12451 token = _step_value[1];
12452 type = token[0];
12453 if (type === "(") brackets += 1;
12454 if (type === ")") brackets -= 1;
12455 if (brackets === 0 && type === ":") if (!prev) this.doubleColon(token);
12456 else if (prev[0] === "word" && prev[1] === "progid") continue;
12457 else return i2;
12458 prev = token;
12459 }
12460 return false;
12461 };
12462 _proto.comment = function comment(token) {
12463 var node2 = new Comment$2();
12464 this.init(node2, token[2]);
12465 node2.source.end = this.getPosition(token[3] || token[2]);
12466 node2.source.end.offset++;
12467 var text = token[1].slice(2, -2);
12468 if (/^\s*$/.test(text)) {
12469 node2.text = "";
12470 node2.raws.left = text;
12471 node2.raws.right = "";
12472 } else {
12473 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
12474 node2.text = match[2];
12475 node2.raws.left = match[1];
12476 node2.raws.right = match[3];
12477 }
12478 };
12479 _proto.createTokenizer = function createTokenizer() {
12480 this.tokenizer = tokenizer22(this.input);
12481 };
12482 _proto.decl = function decl(tokens, customProperty) {
12483 var node2 = new Declaration$2();
12484 this.init(node2, tokens[0][2]);
12485 var last = tokens[tokens.length - 1];
12486 if (last[0] === ";") {
12487 this.semicolon = true;
12488 tokens.pop();
12489 }
12490 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition(tokens));
12491 node2.source.end.offset++;
12492 while (tokens[0][0] !== "word") {
12493 if (tokens.length === 1) this.unknownWord(tokens);
12494 node2.raws.before += tokens.shift()[1];
12495 }
12496 node2.source.start = this.getPosition(tokens[0][2]);
12497 node2.prop = "";
12498 while (tokens.length) {
12499 var type = tokens[0][0];
12500 if (type === ":" || type === "space" || type === "comment") break;
12501 node2.prop += tokens.shift()[1];
12502 }
12503 node2.raws.between = "";
12504 var token;
12505 while (tokens.length) {
12506 token = tokens.shift();
12507 if (token[0] === ":") {
12508 node2.raws.between += token[1];
12509 break;
12510 } else {
12511 if (token[0] === "word" && /\w/.test(token[1])) this.unknownWord([token]);
12512 node2.raws.between += token[1];
12513 }
12514 }
12515 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
12516 node2.raws.before += node2.prop[0];
12517 node2.prop = node2.prop.slice(1);
12518 }
12519 var firstSpaces = [];
12520 var next;
12521 while (tokens.length) {
12522 next = tokens[0][0];
12523 if (next !== "space" && next !== "comment") break;
12524 firstSpaces.push(tokens.shift());
12525 }
12526 this.precheckMissedSemicolon(tokens);
12527 for (var i2 = tokens.length - 1; i2 >= 0; i2--) {
12528 token = tokens[i2];
12529 if (token[1].toLowerCase() === "!important") {
12530 node2.important = true;
12531 var string = this.stringFrom(tokens, i2);
12532 string = this.spacesFromEnd(tokens) + string;
12533 if (string !== " !important") node2.raws.important = string;
12534 break;
12535 } else if (token[1].toLowerCase() === "important") {
12536 var cache = tokens.slice(0);
12537 var str = "";
12538 for (var j = i2; j > 0; j--) {
12539 var type1 = cache[j][0];
12540 if (str.trim().indexOf("!") === 0 && type1 !== "space") break;
12541 str = cache.pop()[1] + str;
12542 }
12543 if (str.trim().indexOf("!") === 0) {
12544 node2.important = true;
12545 node2.raws.important = str;
12546 tokens = cache;
12547 }
12548 }
12549 if (token[0] !== "space" && token[0] !== "comment") break;
12550 }
12551 if (tokens.some(function(i2) {
12552 return i2[0] !== "space" && i2[0] !== "comment";
12553 })) {
12554 node2.raws.between += firstSpaces.map(function(i2) {
12555 return i2[1];
12556 }).join("");
12557 firstSpaces = [];
12558 }
12559 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
12560 if (node2.value.includes(":") && !customProperty) this.checkMissedSemicolon(tokens);
12561 };
12562 _proto.doubleColon = function doubleColon(token) {
12563 throw this.input.error("Double colon", { offset: token[2] }, { offset: token[2] + token[1].length });
12564 };
12565 _proto.emptyRule = function emptyRule(token) {
12566 var node2 = new Rule$2();
12567 this.init(node2, token[2]);
12568 node2.selector = "";
12569 node2.raws.between = "";
12570 this.current = node2;
12571 };
12572 _proto.end = function end(token) {
12573 if (this.current.nodes && this.current.nodes.length) this.current.raws.semicolon = this.semicolon;
12574 this.semicolon = false;
12575 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
12576 this.spaces = "";
12577 if (this.current.parent) {
12578 this.current.source.end = this.getPosition(token[2]);
12579 this.current.source.end.offset++;
12580 this.current = this.current.parent;
12581 } else this.unexpectedClose(token);
12582 };
12583 _proto.endFile = function endFile() {
12584 if (this.current.parent) this.unclosedBlock();
12585 if (this.current.nodes && this.current.nodes.length) this.current.raws.semicolon = this.semicolon;
12586 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
12587 this.root.source.end = this.getPosition(this.tokenizer.position());
12588 };
12589 _proto.freeSemicolon = function freeSemicolon(token) {
12590 this.spaces += token[1];
12591 if (this.current.nodes) {
12592 var prev = this.current.nodes[this.current.nodes.length - 1];
12593 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
12594 prev.raws.ownSemicolon = this.spaces;
12595 this.spaces = "";
12596 }
12597 }
12598 };
12599 _proto.getPosition = function getPosition(offset) {
12600 var pos = this.input.fromOffset(offset);
12601 return {
12602 column: pos.col,
12603 line: pos.line,
12604 offset
12605 };
12606 };
12607 _proto.init = function init(node2, offset) {
12608 this.current.push(node2);
12609 node2.source = {
12610 input: this.input,
12611 start: this.getPosition(offset)
12612 };
12613 node2.raws.before = this.spaces;
12614 this.spaces = "";
12615 if (node2.type !== "comment") this.semicolon = false;
12616 };
12617 _proto.other = function other(start) {
12618 var end = false;
12619 var type = null;
12620 var colon = false;
12621 var bracket = null;
12622 var brackets = [];
12623 var customProperty = start[1].startsWith("--");
12624 var tokens = [];
12625 var token = start;
12626 while (token) {
12627 type = token[0];
12628 tokens.push(token);
12629 if (type === "(" || type === "[") {
12630 if (!bracket) bracket = token;
12631 brackets.push(type === "(" ? ")" : "]");
12632 } else if (customProperty && colon && type === "{") {
12633 if (!bracket) bracket = token;
12634 brackets.push("}");
12635 } else if (brackets.length === 0) {
12636 if (type === ";") if (colon) {
12637 this.decl(tokens, customProperty);
12638 return;
12639 } else break;
12640 else if (type === "{") {
12641 this.rule(tokens);
12642 return;
12643 } else if (type === "}") {
12644 this.tokenizer.back(tokens.pop());
12645 end = true;
12646 break;
12647 } else if (type === ":") colon = true;
12648 } else if (type === brackets[brackets.length - 1]) {
12649 brackets.pop();
12650 if (brackets.length === 0) bracket = null;
12651 }
12652 token = this.tokenizer.nextToken();
12653 }
12654 if (this.tokenizer.endOfFile()) end = true;
12655 if (brackets.length > 0) this.unclosedBracket(bracket);
12656 if (end && colon) {
12657 if (!customProperty) while (tokens.length) {
12658 token = tokens[tokens.length - 1][0];
12659 if (token !== "space" && token !== "comment") break;
12660 this.tokenizer.back(tokens.pop());
12661 }
12662 this.decl(tokens, customProperty);
12663 } else this.unknownWord(tokens);
12664 };
12665 _proto.parse = function parse() {
12666 var token;
12667 while (!this.tokenizer.endOfFile()) {
12668 token = this.tokenizer.nextToken();
12669 switch (token[0]) {
12670 case "space":
12671 this.spaces += token[1];
12672 break;
12673 case ";":
12674 this.freeSemicolon(token);
12675 break;
12676 case "}":
12677 this.end(token);
12678 break;
12679 case "comment":
12680 this.comment(token);
12681 break;
12682 case "at-word":
12683 this.atrule(token);
12684 break;
12685 case "{":
12686 this.emptyRule(token);
12687 break;
12688 default:
12689 this.other(token);
12690 break;
12691 }
12692 }
12693 this.endFile();
12694 };
12695 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
12696 _proto.raw = function raw(node2, prop, tokens, customProperty) {
12697 var token;
12698 var type;
12699 var length = tokens.length;
12700 var value = "";
12701 var clean = true;
12702 var next;
12703 var prev;
12704 for (var i2 = 0; i2 < length; i2 += 1) {
12705 token = tokens[i2];
12706 type = token[0];
12707 if (type === "space" && i2 === length - 1 && !customProperty) clean = false;
12708 else if (type === "comment") {
12709 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
12710 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
12711 if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) if (value.slice(-1) === ",") clean = false;
12712 else value += token[1];
12713 else clean = false;
12714 } else value += token[1];
12715 }
12716 if (!clean) {
12717 var raw = tokens.reduce(function(all, i2) {
12718 return all + i2[1];
12719 }, "");
12720 node2.raws[prop] = {
12721 raw,
12722 value
12723 };
12724 }
12725 node2[prop] = value;
12726 };
12727 _proto.rule = function rule(tokens) {
12728 tokens.pop();
12729 var node2 = new Rule$2();
12730 this.init(node2, tokens[0][2]);
12731 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
12732 this.raw(node2, "selector", tokens);
12733 this.current = node2;
12734 };
12735 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
12736 var lastTokenType;
12737 var spaces = "";
12738 while (tokens.length) {
12739 lastTokenType = tokens[tokens.length - 1][0];
12740 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
12741 spaces = tokens.pop()[1] + spaces;
12742 }
12743 return spaces;
12744 };
12745 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
12746 var next;
12747 var spaces = "";
12748 while (tokens.length) {
12749 next = tokens[0][0];
12750 if (next !== "space" && next !== "comment") break;
12751 spaces += tokens.shift()[1];
12752 }
12753 return spaces;
12754 };
12755 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
12756 var lastTokenType;
12757 var spaces = "";
12758 while (tokens.length) {
12759 lastTokenType = tokens[tokens.length - 1][0];
12760 if (lastTokenType !== "space") break;
12761 spaces = tokens.pop()[1] + spaces;
12762 }
12763 return spaces;
12764 };
12765 _proto.stringFrom = function stringFrom(tokens, from) {
12766 var result2 = "";
12767 for (var i2 = from; i2 < tokens.length; i2++) result2 += tokens[i2][1];
12768 tokens.splice(from, tokens.length - from);
12769 return result2;
12770 };
12771 _proto.unclosedBlock = function unclosedBlock() {
12772 var pos = this.current.source.start;
12773 throw this.input.error("Unclosed block", pos.line, pos.column);
12774 };
12775 _proto.unclosedBracket = function unclosedBracket(bracket) {
12776 throw this.input.error("Unclosed bracket", { offset: bracket[2] }, { offset: bracket[2] + 1 });
12777 };
12778 _proto.unexpectedClose = function unexpectedClose(token) {
12779 throw this.input.error("Unexpected }", { offset: token[2] }, { offset: token[2] + 1 });
12780 };
12781 _proto.unknownWord = function unknownWord(tokens) {
12782 throw this.input.error("Unknown word", { offset: tokens[0][2] }, { offset: tokens[0][2] + tokens[0][1].length });
12783 };
12784 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
12785 throw this.input.error("At-rule without name", { offset: token[2] }, { offset: token[2] + token[1].length });
12786 };
12787 return Parser2;
12788 }();
12789 var Container$2 = container;
12790 var Parser22 = parser;
12791 var Input$2 = input;
12792 function parse$3(css, opts) {
12793 var parser2 = new Parser22(new Input$2(css, opts));
12794 try {
12795 parser2.parse();
12796 } catch (e2) {
12797 if (e2.name === "CssSyntaxError" && opts && opts.from) {
12798 if (/\.scss$/i.test(opts.from)) e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
12799 else if (/\.sass/i.test(opts.from)) e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
12800 else if (/\.less$/i.test(opts.from)) e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
12801 }
12802 throw e2;
12803 }
12804 return parser2.root;
12805 }
12806 var parse_1 = parse$3;
12807 parse$3.default = parse$3;
12808 Container$2.registerParse(parse$3);
12809 var isClean = symbols.isClean;
12810 var my = symbols.my;
12811 var MapGenerator$1 = mapGenerator;
12812 var stringify$2 = stringify_1;
12813 var Container$1 = container;
12814 var Document$2 = document$1$2;
12815 var warnOnce$1 = warnOnce$2;
12816 var Result$2 = result;
12817 var parse$2 = parse_1;
12818 var Root$3 = root;
12819 var TYPE_TO_CLASS_NAME = {
12820 atrule: "AtRule",
12821 comment: "Comment",
12822 decl: "Declaration",
12823 document: "Document",
12824 root: "Root",
12825 rule: "Rule"
12826 };
12827 var PLUGIN_PROPS = {
12828 AtRule: true,
12829 AtRuleExit: true,
12830 Comment: true,
12831 CommentExit: true,
12832 Declaration: true,
12833 DeclarationExit: true,
12834 Document: true,
12835 DocumentExit: true,
12836 Once: true,
12837 OnceExit: true,
12838 postcssPlugin: true,
12839 prepare: true,
12840 Root: true,
12841 RootExit: true,
12842 Rule: true,
12843 RuleExit: true
12844 };
12845 var NOT_VISITORS = {
12846 Once: true,
12847 postcssPlugin: true,
12848 prepare: true
12849 };
12850 var CHILDREN = 0;
12851 function isPromise(obj) {
12852 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
12853 }
12854 function getEvents(node2) {
12855 var key = false;
12856 var type = TYPE_TO_CLASS_NAME[node2.type];
12857 if (node2.type === "decl") key = node2.prop.toLowerCase();
12858 else if (node2.type === "atrule") key = node2.name.toLowerCase();
12859 if (key && node2.append) return [
12860 type,
12861 type + "-" + key,
12862 CHILDREN,
12863 type + "Exit",
12864 type + "Exit-" + key
12865 ];
12866 else if (key) return [
12867 type,
12868 type + "-" + key,
12869 type + "Exit",
12870 type + "Exit-" + key
12871 ];
12872 else if (node2.append) return [
12873 type,
12874 CHILDREN,
12875 type + "Exit"
12876 ];
12877 else return [type, type + "Exit"];
12878 }
12879 function toStack(node2) {
12880 var events;
12881 if (node2.type === "document") events = [
12882 "Document",
12883 CHILDREN,
12884 "DocumentExit"
12885 ];
12886 else if (node2.type === "root") events = [
12887 "Root",
12888 CHILDREN,
12889 "RootExit"
12890 ];
12891 else events = getEvents(node2);
12892 return {
12893 eventIndex: 0,
12894 events,
12895 iterator: 0,
12896 node: node2,
12897 visitorIndex: 0,
12898 visitors: []
12899 };
12900 }
12901 function cleanMarks(node2) {
12902 node2[isClean] = false;
12903 if (node2.nodes) node2.nodes.forEach(function(i2) {
12904 return cleanMarks(i2);
12905 });
12906 return node2;
12907 }
12908 var postcss$2 = {};
12909 var LazyResult$2 = /*#__PURE__*/ function() {
12910 function LazyResult2(processor2, css, opts) {
12911 var _this = this;
12912 this.stringified = false;
12913 this.processed = false;
12914 var root2;
12915 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) root2 = cleanMarks(css);
12916 else if (_instanceof(css, LazyResult2) || _instanceof(css, Result$2)) {
12917 root2 = cleanMarks(css.root);
12918 if (css.map) {
12919 if (typeof opts.map === "undefined") opts.map = {};
12920 if (!opts.map.inline) opts.map.inline = false;
12921 opts.map.prev = css.map;
12922 }
12923 } else {
12924 var parser2 = parse$2;
12925 if (opts.syntax) parser2 = opts.syntax.parse;
12926 if (opts.parser) parser2 = opts.parser;
12927 if (parser2.parse) parser2 = parser2.parse;
12928 try {
12929 root2 = parser2(css, opts);
12930 } catch (error) {
12931 this.processed = true;
12932 this.error = error;
12933 }
12934 if (root2 && !root2[my]) Container$1.rebuild(root2);
12935 }
12936 this.result = new Result$2(processor2, root2, opts);
12937 this.helpers = _extends({}, postcss$2, {
12938 postcss: postcss$2,
12939 result: this.result
12940 });
12941 this.plugins = this.processor.plugins.map(function(plugin22) {
12942 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) return _extends({}, plugin22, plugin22.prepare(_this.result));
12943 else return plugin22;
12944 });
12945 }
12946 var _proto = LazyResult2.prototype;
12947 _proto.async = function async() {
12948 if (this.error) return Promise.reject(this.error);
12949 if (this.processed) return Promise.resolve(this.result);
12950 if (!this.processing) this.processing = this.runAsync();
12951 return this.processing;
12952 };
12953 _proto.catch = function _catch(onRejected) {
12954 return this.async().catch(onRejected);
12955 };
12956 _proto.finally = function _finally(onFinally) {
12957 return this.async().then(onFinally, onFinally);
12958 };
12959 _proto.getAsyncError = function getAsyncError() {
12960 throw new Error("Use process(css).then(cb) to work with async plugins");
12961 };
12962 _proto.handleError = function handleError(error, node2) {
12963 var plugin22 = this.result.lastPlugin;
12964 try {
12965 if (node2) node2.addToError(error);
12966 this.error = error;
12967 if (error.name === "CssSyntaxError" && !error.plugin) {
12968 error.plugin = plugin22.postcssPlugin;
12969 error.setMessage();
12970 } else if (plugin22.postcssVersion) {
12971 var pluginName = plugin22.postcssPlugin;
12972 var pluginVer = plugin22.postcssVersion;
12973 var runtimeVer = this.result.processor.version;
12974 var a2 = pluginVer.split(".");
12975 var b = runtimeVer.split(".");
12976 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) console.error("Unknown error from PostCSS plugin. Your current PostCSS version is " + runtimeVer + ", but " + pluginName + " uses " + pluginVer + ". Perhaps this is the source of the error below.");
12977 }
12978 } catch (err) {
12979 if (console && console.error) console.error(err);
12980 }
12981 return error;
12982 };
12983 _proto.prepareVisitors = function prepareVisitors() {
12984 var _this = this;
12985 this.listeners = {};
12986 var add = function(plugin22, type, cb) {
12987 if (!_this.listeners[type]) _this.listeners[type] = [];
12988 _this.listeners[type].push([plugin22, cb]);
12989 };
12990 for (var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;) {
12991 var plugin22 = _step.value;
12992 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") for (var event in plugin22) {
12993 if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
12994 if (!NOT_VISITORS[event]) {
12995 if (_type_of(plugin22[event]) === "object") for (var filter in plugin22[event]) if (filter === "*") add(plugin22, event, plugin22[event][filter]);
12996 else add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
12997 else if (typeof plugin22[event] === "function") add(plugin22, event, plugin22[event]);
12998 }
12999 }
13000 }
13001 this.hasListener = Object.keys(this.listeners).length > 0;
13002 };
13003 _proto.runAsync = function runAsync() {
13004 var _this = this;
13005 return _async_to_generator(function() {
13006 var i2;
13007 var plugin22;
13008 var promise;
13009 var error;
13010 var root2;
13011 var stack;
13012 var promise1;
13013 var e2;
13014 var node2;
13015 var _loop;
13016 var _iterator;
13017 var _step;
13018 return _ts_generator(this, function(_state) {
13019 switch (_state.label) {
13020 case 0:
13021 _this.plugin = 0;
13022 i2 = 0;
13023 _state.label = 1;
13024 case 1:
13025 if (!(i2 < _this.plugins.length)) return [3, 6];
13026 plugin22 = _this.plugins[i2];
13027 promise = _this.runOnRoot(plugin22);
13028 if (!isPromise(promise)) return [3, 5];
13029 _state.label = 2;
13030 case 2:
13031 _state.trys.push([
13032 2,
13033 4,
13034 ,
13035 5
13036 ]);
13037 return [4, promise];
13038 case 3:
13039 _state.sent();
13040 return [3, 5];
13041 case 4:
13042 error = _state.sent();
13043 throw _this.handleError(error);
13044 case 5:
13045 i2++;
13046 return [3, 1];
13047 case 6:
13048 _this.prepareVisitors();
13049 if (!_this.hasListener) return [3, 18];
13050 root2 = _this.result.root;
13051 _state.label = 7;
13052 case 7:
13053 if (!!root2[isClean]) return [3, 14];
13054 root2[isClean] = true;
13055 stack = [toStack(root2)];
13056 _state.label = 8;
13057 case 8:
13058 if (!(stack.length > 0)) return [3, 13];
13059 promise1 = _this.visitTick(stack);
13060 if (!isPromise(promise1)) return [3, 12];
13061 _state.label = 9;
13062 case 9:
13063 _state.trys.push([
13064 9,
13065 11,
13066 ,
13067 12
13068 ]);
13069 return [4, promise1];
13070 case 10:
13071 _state.sent();
13072 return [3, 12];
13073 case 11:
13074 e2 = _state.sent();
13075 node2 = stack[stack.length - 1].node;
13076 throw _this.handleError(e2, node2);
13077 case 12: return [3, 8];
13078 case 13: return [3, 7];
13079 case 14:
13080 if (!_this.listeners.OnceExit) return [3, 18];
13081 _loop = function() {
13082 var _step_value;
13083 var plugin22;
13084 var visitor;
13085 var roots;
13086 var e2;
13087 return _ts_generator(this, function(_state) {
13088 switch (_state.label) {
13089 case 0:
13090 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
13091 _this.result.lastPlugin = plugin22;
13092 _state.label = 1;
13093 case 1:
13094 _state.trys.push([
13095 1,
13096 6,
13097 ,
13098 7
13099 ]);
13100 if (!(root2.type === "document")) return [3, 3];
13101 roots = root2.nodes.map(function(subRoot) {
13102 return visitor(subRoot, _this.helpers);
13103 });
13104 return [4, Promise.all(roots)];
13105 case 2:
13106 _state.sent();
13107 return [3, 5];
13108 case 3: return [4, visitor(root2, _this.helpers)];
13109 case 4:
13110 _state.sent();
13111 _state.label = 5;
13112 case 5: return [3, 7];
13113 case 6:
13114 e2 = _state.sent();
13115 throw _this.handleError(e2);
13116 case 7: return [2];
13117 }
13118 });
13119 };
13120 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
13121 _state.label = 15;
13122 case 15:
13123 if (!!(_step = _iterator()).done) return [3, 18];
13124 return [5, _ts_values(_loop())];
13125 case 16:
13126 _state.sent();
13127 _state.label = 17;
13128 case 17: return [3, 15];
13129 case 18:
13130 _this.processed = true;
13131 return [2, _this.stringify()];
13132 }
13133 });
13134 })();
13135 };
13136 _proto.runOnRoot = function runOnRoot(plugin22) {
13137 var _this = this;
13138 this.result.lastPlugin = plugin22;
13139 try {
13140 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
13141 if (this.result.root.type === "document") {
13142 var roots = this.result.root.nodes.map(function(root2) {
13143 return plugin22.Once(root2, _this.helpers);
13144 });
13145 if (isPromise(roots[0])) return Promise.all(roots);
13146 return roots;
13147 }
13148 return plugin22.Once(this.result.root, this.helpers);
13149 } else if (typeof plugin22 === "function") return plugin22(this.result.root, this.result);
13150 } catch (error) {
13151 throw this.handleError(error);
13152 }
13153 };
13154 _proto.stringify = function stringify() {
13155 if (this.error) throw this.error;
13156 if (this.stringified) return this.result;
13157 this.stringified = true;
13158 this.sync();
13159 var opts = this.result.opts;
13160 var str = stringify$2;
13161 if (opts.syntax) str = opts.syntax.stringify;
13162 if (opts.stringifier) str = opts.stringifier;
13163 if (str.stringify) str = str.stringify;
13164 var data = new MapGenerator$1(str, this.result.root, this.result.opts).generate();
13165 this.result.css = data[0];
13166 this.result.map = data[1];
13167 return this.result;
13168 };
13169 _proto.sync = function sync() {
13170 if (this.error) throw this.error;
13171 if (this.processed) return this.result;
13172 this.processed = true;
13173 if (this.processing) throw this.getAsyncError();
13174 for (var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;) {
13175 var plugin22 = _step.value;
13176 if (isPromise(this.runOnRoot(plugin22))) throw this.getAsyncError();
13177 }
13178 this.prepareVisitors();
13179 if (this.hasListener) {
13180 var root2 = this.result.root;
13181 while (!root2[isClean]) {
13182 root2[isClean] = true;
13183 this.walkSync(root2);
13184 }
13185 if (this.listeners.OnceExit) if (root2.type === "document") for (var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;) {
13186 var subRoot = _step1.value;
13187 this.visitSync(this.listeners.OnceExit, subRoot);
13188 }
13189 else this.visitSync(this.listeners.OnceExit, root2);
13190 }
13191 return this.result;
13192 };
13193 _proto.then = function then(onFulfilled, onRejected) {
13194 if (!("from" in this.opts)) warnOnce$1("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.");
13195 return this.async().then(onFulfilled, onRejected);
13196 };
13197 _proto.toString = function toString() {
13198 return this.css;
13199 };
13200 _proto.visitSync = function visitSync(visitors, node2) {
13201 for (var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;) {
13202 var _step_value = _step.value;
13203 var plugin22 = _step_value[0];
13204 var visitor = _step_value[1];
13205 this.result.lastPlugin = plugin22;
13206 var promise = void 0;
13207 try {
13208 promise = visitor(node2, this.helpers);
13209 } catch (e2) {
13210 throw this.handleError(e2, node2.proxyOf);
13211 }
13212 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) return true;
13213 if (isPromise(promise)) throw this.getAsyncError();
13214 }
13215 };
13216 _proto.visitTick = function visitTick(stack) {
13217 var visit2 = stack[stack.length - 1];
13218 var node2 = visit2.node;
13219 var visitors = visit2.visitors;
13220 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
13221 stack.pop();
13222 return;
13223 }
13224 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
13225 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex];
13226 var plugin22 = _visitors_visit2_visitorIndex[0];
13227 var visitor = _visitors_visit2_visitorIndex[1];
13228 visit2.visitorIndex += 1;
13229 if (visit2.visitorIndex === visitors.length) {
13230 visit2.visitors = [];
13231 visit2.visitorIndex = 0;
13232 }
13233 this.result.lastPlugin = plugin22;
13234 try {
13235 return visitor(node2.toProxy(), this.helpers);
13236 } catch (e2) {
13237 throw this.handleError(e2, node2);
13238 }
13239 }
13240 if (visit2.iterator !== 0) {
13241 var iterator = visit2.iterator;
13242 var child;
13243 while (child = node2.nodes[node2.indexes[iterator]]) {
13244 node2.indexes[iterator] += 1;
13245 if (!child[isClean]) {
13246 child[isClean] = true;
13247 stack.push(toStack(child));
13248 return;
13249 }
13250 }
13251 visit2.iterator = 0;
13252 delete node2.indexes[iterator];
13253 }
13254 var events = visit2.events;
13255 while (visit2.eventIndex < events.length) {
13256 var event = events[visit2.eventIndex];
13257 visit2.eventIndex += 1;
13258 if (event === CHILDREN) {
13259 if (node2.nodes && node2.nodes.length) {
13260 node2[isClean] = true;
13261 visit2.iterator = node2.getIterator();
13262 }
13263 return;
13264 } else if (this.listeners[event]) {
13265 visit2.visitors = this.listeners[event];
13266 return;
13267 }
13268 }
13269 stack.pop();
13270 };
13271 _proto.walkSync = function walkSync(node2) {
13272 var _this = this;
13273 node2[isClean] = true;
13274 for (var _iterator = _create_for_of_iterator_helper_loose(getEvents(node2)), _step; !(_step = _iterator()).done;) {
13275 var event = _step.value;
13276 if (event === CHILDREN) {
13277 if (node2.nodes) node2.each(function(child) {
13278 if (!child[isClean]) _this.walkSync(child);
13279 });
13280 } else {
13281 var visitors = this.listeners[event];
13282 if (visitors) {
13283 if (this.visitSync(visitors, node2.toProxy())) return;
13284 }
13285 }
13286 }
13287 };
13288 _proto.warnings = function warnings() {
13289 return this.sync().warnings();
13290 };
13291 _create_class(LazyResult2, [
13292 {
13293 key: "content",
13294 get: function get() {
13295 return this.stringify().content;
13296 }
13297 },
13298 {
13299 key: "css",
13300 get: function get() {
13301 return this.stringify().css;
13302 }
13303 },
13304 {
13305 key: "map",
13306 get: function get() {
13307 return this.stringify().map;
13308 }
13309 },
13310 {
13311 key: "messages",
13312 get: function get() {
13313 return this.sync().messages;
13314 }
13315 },
13316 {
13317 key: "opts",
13318 get: function get() {
13319 return this.result.opts;
13320 }
13321 },
13322 {
13323 key: "processor",
13324 get: function get() {
13325 return this.result.processor;
13326 }
13327 },
13328 {
13329 key: "root",
13330 get: function get() {
13331 return this.sync().root;
13332 }
13333 },
13334 {
13335 key: Symbol.toStringTag,
13336 get: function get() {
13337 return "LazyResult";
13338 }
13339 }
13340 ]);
13341 return LazyResult2;
13342 }();
13343 LazyResult$2.registerPostcss = function(dependant) {
13344 postcss$2 = dependant;
13345 };
13346 var lazyResult = LazyResult$2;
13347 LazyResult$2.default = LazyResult$2;
13348 Root$3.registerLazyResult(LazyResult$2);
13349 Document$2.registerLazyResult(LazyResult$2);
13350 var MapGenerator22 = mapGenerator;
13351 var stringify$1 = stringify_1;
13352 var warnOnce22 = warnOnce$2;
13353 var parse$1 = parse_1;
13354 var Result$1 = result;
13355 var NoWorkResult$1 = /*#__PURE__*/ function() {
13356 function NoWorkResult2(processor2, css, opts) {
13357 css = css.toString();
13358 this.stringified = false;
13359 this._processor = processor2;
13360 this._css = css;
13361 this._opts = opts;
13362 this._map = void 0;
13363 var root2;
13364 var str = stringify$1;
13365 this.result = new Result$1(this._processor, root2, this._opts);
13366 this.result.css = css;
13367 var self = this;
13368 Object.defineProperty(this.result, "root", { get: function get() {
13369 return self.root;
13370 } });
13371 var map = new MapGenerator22(str, root2, this._opts, css);
13372 if (map.isMap()) {
13373 var _map_generate = map.generate();
13374 var generatedCSS = _map_generate[0];
13375 var generatedMap = _map_generate[1];
13376 if (generatedCSS) this.result.css = generatedCSS;
13377 if (generatedMap) this.result.map = generatedMap;
13378 } else {
13379 map.clearAnnotation();
13380 this.result.css = map.css;
13381 }
13382 }
13383 var _proto = NoWorkResult2.prototype;
13384 _proto.async = function async() {
13385 if (this.error) return Promise.reject(this.error);
13386 return Promise.resolve(this.result);
13387 };
13388 _proto.catch = function _catch(onRejected) {
13389 return this.async().catch(onRejected);
13390 };
13391 _proto.finally = function _finally(onFinally) {
13392 return this.async().then(onFinally, onFinally);
13393 };
13394 _proto.sync = function sync() {
13395 if (this.error) throw this.error;
13396 return this.result;
13397 };
13398 _proto.then = function then(onFulfilled, onRejected) {
13399 if (!("from" in this._opts)) warnOnce22("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.");
13400 return this.async().then(onFulfilled, onRejected);
13401 };
13402 _proto.toString = function toString() {
13403 return this._css;
13404 };
13405 _proto.warnings = function warnings() {
13406 return [];
13407 };
13408 _create_class(NoWorkResult2, [
13409 {
13410 key: "content",
13411 get: function get() {
13412 return this.result.css;
13413 }
13414 },
13415 {
13416 key: "css",
13417 get: function get() {
13418 return this.result.css;
13419 }
13420 },
13421 {
13422 key: "map",
13423 get: function get() {
13424 return this.result.map;
13425 }
13426 },
13427 {
13428 key: "messages",
13429 get: function get() {
13430 return [];
13431 }
13432 },
13433 {
13434 key: "opts",
13435 get: function get() {
13436 return this.result.opts;
13437 }
13438 },
13439 {
13440 key: "processor",
13441 get: function get() {
13442 return this.result.processor;
13443 }
13444 },
13445 {
13446 key: "root",
13447 get: function get() {
13448 if (this._root) return this._root;
13449 var root2;
13450 var parser2 = parse$1;
13451 try {
13452 root2 = parser2(this._css, this._opts);
13453 } catch (error) {
13454 this.error = error;
13455 }
13456 if (this.error) throw this.error;
13457 else {
13458 this._root = root2;
13459 return root2;
13460 }
13461 }
13462 },
13463 {
13464 key: Symbol.toStringTag,
13465 get: function get() {
13466 return "NoWorkResult";
13467 }
13468 }
13469 ]);
13470 return NoWorkResult2;
13471 }();
13472 var noWorkResult = NoWorkResult$1;
13473 NoWorkResult$1.default = NoWorkResult$1;
13474 var NoWorkResult22 = noWorkResult;
13475 var LazyResult$1 = lazyResult;
13476 var Document$1 = document$1$2;
13477 var Root$2 = root;
13478 var Processor$1 = /*#__PURE__*/ function() {
13479 function Processor2(plugins) {
13480 if (plugins === void 0) plugins = [];
13481 this.version = "8.4.38";
13482 this.plugins = this.normalize(plugins);
13483 }
13484 var _proto = Processor2.prototype;
13485 _proto.normalize = function normalize(plugins) {
13486 var normalized = [];
13487 for (var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;) {
13488 var i2 = _step.value;
13489 if (i2.postcss === true) i2 = i2();
13490 else if (i2.postcss) i2 = i2.postcss;
13491 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) normalized = normalized.concat(i2.plugins);
13492 else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) normalized.push(i2);
13493 else if (typeof i2 === "function") normalized.push(i2);
13494 else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.");
13495 else throw new Error(i2 + " is not a PostCSS plugin");
13496 }
13497 return normalized;
13498 };
13499 _proto.process = function process1(css, opts) {
13500 if (opts === void 0) opts = {};
13501 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) return new NoWorkResult22(this, css, opts);
13502 else return new LazyResult$1(this, css, opts);
13503 };
13504 _proto.use = function use(plugin22) {
13505 this.plugins = this.plugins.concat(this.normalize([plugin22]));
13506 return this;
13507 };
13508 return Processor2;
13509 }();
13510 var processor = Processor$1;
13511 Processor$1.default = Processor$1;
13512 Root$2.registerProcessor(Processor$1);
13513 Document$1.registerProcessor(Processor$1);
13514 var Declaration$1 = declaration;
13515 var PreviousMap22 = previousMap;
13516 var Comment$1 = comment;
13517 var AtRule$1 = atRule;
13518 var Input$1 = input;
13519 var Root$1 = root;
13520 var Rule$1 = rule;
13521 function fromJSON$1(json, inputs) {
13522 if (Array.isArray(json)) return json.map(function(n2) {
13523 return fromJSON$1(n2);
13524 });
13525 var ownInputs = json.inputs;
13526 var defaults = _object_without_properties_loose(json, ["inputs"]);
13527 if (ownInputs) {
13528 inputs = [];
13529 for (var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;) {
13530 var input2 = _step.value;
13531 var inputHydrated = _extends({}, input2, { __proto__: Input$1.prototype });
13532 if (inputHydrated.map) inputHydrated.map = _extends({}, inputHydrated.map, { __proto__: PreviousMap22.prototype });
13533 inputs.push(inputHydrated);
13534 }
13535 }
13536 if (defaults.nodes) defaults.nodes = json.nodes.map(function(n2) {
13537 return fromJSON$1(n2, inputs);
13538 });
13539 if (defaults.source) {
13540 var _defaults_source = defaults.source;
13541 var inputId = _defaults_source.inputId;
13542 defaults.source = _object_without_properties_loose(_defaults_source, ["inputId"]);
13543 if (inputId != null) defaults.source.input = inputs[inputId];
13544 }
13545 if (defaults.type === "root") return new Root$1(defaults);
13546 else if (defaults.type === "decl") return new Declaration$1(defaults);
13547 else if (defaults.type === "rule") return new Rule$1(defaults);
13548 else if (defaults.type === "comment") return new Comment$1(defaults);
13549 else if (defaults.type === "atrule") return new AtRule$1(defaults);
13550 else throw new Error("Unknown node type: " + json.type);
13551 }
13552 var fromJSON_1 = fromJSON$1;
13553 fromJSON$1.default = fromJSON$1;
13554 var CssSyntaxError22 = cssSyntaxError;
13555 var Declaration22 = declaration;
13556 var LazyResult22 = lazyResult;
13557 var Container22 = container;
13558 var Processor22 = processor;
13559 var stringify = stringify_1;
13560 var fromJSON = fromJSON_1;
13561 var Document222 = document$1$2;
13562 var Warning22 = warning;
13563 var Comment22 = comment;
13564 var AtRule22 = atRule;
13565 var Result22 = result;
13566 var Input22 = input;
13567 var parse = parse_1;
13568 var list = list_1;
13569 var Rule22 = rule;
13570 var Root22 = root;
13571 var Node22 = node;
13572 function postcss() {
13573 for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) plugins[_key] = arguments[_key];
13574 if (plugins.length === 1 && Array.isArray(plugins[0])) plugins = plugins[0];
13575 return new Processor22(plugins);
13576 }
13577 postcss.plugin = function plugin2(name, initializer) {
13578 var warningPrinted = false;
13579 function creator() {
13580 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
13581 if (console && console.warn && !warningPrinted) {
13582 warningPrinted = true;
13583 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
13584 if ({}.LANG && {}.LANG.startsWith("cn")) console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
13585 }
13586 var transformer = initializer.apply(void 0, [].concat(args));
13587 transformer.postcssPlugin = name;
13588 transformer.postcssVersion = new Processor22().version;
13589 return transformer;
13590 }
13591 var cache;
13592 Object.defineProperty(creator, "postcss", { get: function get() {
13593 if (!cache) cache = creator();
13594 return cache;
13595 } });
13596 creator.process = function(css, processOpts, pluginOpts) {
13597 return postcss([creator(pluginOpts)]).process(css, processOpts);
13598 };
13599 return creator;
13600 };
13601 postcss.stringify = stringify;
13602 postcss.parse = parse;
13603 postcss.fromJSON = fromJSON;
13604 postcss.list = list;
13605 postcss.comment = function(defaults) {
13606 return new Comment22(defaults);
13607 };
13608 postcss.atRule = function(defaults) {
13609 return new AtRule22(defaults);
13610 };
13611 postcss.decl = function(defaults) {
13612 return new Declaration22(defaults);
13613 };
13614 postcss.rule = function(defaults) {
13615 return new Rule22(defaults);
13616 };
13617 postcss.root = function(defaults) {
13618 return new Root22(defaults);
13619 };
13620 postcss.document = function(defaults) {
13621 return new Document222(defaults);
13622 };
13623 postcss.CssSyntaxError = CssSyntaxError22;
13624 postcss.Declaration = Declaration22;
13625 postcss.Container = Container22;
13626 postcss.Processor = Processor22;
13627 postcss.Document = Document222;
13628 postcss.Comment = Comment22;
13629 postcss.Warning = Warning22;
13630 postcss.AtRule = AtRule22;
13631 postcss.Result = Result22;
13632 postcss.Input = Input22;
13633 postcss.Rule = Rule22;
13634 postcss.Root = Root22;
13635 postcss.Node = Node22;
13636 LazyResult22.registerPostcss(postcss);
13637 var postcss_1 = postcss;
13638 postcss.default = postcss;
13639 var postcss$1 = /* @__PURE__ */ getDefaultExportFromCjs(postcss_1);
13640 postcss$1.stringify;
13641 postcss$1.fromJSON;
13642 postcss$1.plugin;
13643 postcss$1.parse;
13644 postcss$1.list;
13645 postcss$1.document;
13646 postcss$1.comment;
13647 postcss$1.atRule;
13648 postcss$1.rule;
13649 postcss$1.decl;
13650 postcss$1.root;
13651 postcss$1.CssSyntaxError;
13652 postcss$1.Declaration;
13653 postcss$1.Container;
13654 postcss$1.Processor;
13655 postcss$1.Document;
13656 postcss$1.Comment;
13657 postcss$1.Warning;
13658 postcss$1.AtRule;
13659 postcss$1.Result;
13660 postcss$1.Input;
13661 postcss$1.Rule;
13662 postcss$1.Root;
13663 postcss$1.Node;
13664 var BaseRRNode = /*#__PURE__*/ function() {
13665 function BaseRRNode() {
13666 for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) _args[_key] = arguments[_key];
13667 __publicField2(this, "parentElement", null);
13668 __publicField2(this, "parentNode", null);
13669 __publicField2(this, "ownerDocument");
13670 __publicField2(this, "firstChild", null);
13671 __publicField2(this, "lastChild", null);
13672 __publicField2(this, "previousSibling", null);
13673 __publicField2(this, "nextSibling", null);
13674 __publicField2(this, "ELEMENT_NODE", 1);
13675 __publicField2(this, "TEXT_NODE", 3);
13676 __publicField2(this, "nodeType");
13677 __publicField2(this, "nodeName");
13678 __publicField2(this, "RRNodeType");
13679 }
13680 var _proto = BaseRRNode.prototype;
13681 _proto.contains = function contains(node2) {
13682 if (!_instanceof(node2, BaseRRNode)) return false;
13683 else if (node2.ownerDocument !== this.ownerDocument) return false;
13684 else if (node2 === this) return true;
13685 while (node2.parentNode) {
13686 if (node2.parentNode === this) return true;
13687 node2 = node2.parentNode;
13688 }
13689 return false;
13690 };
13691 _proto.appendChild = function appendChild(_newChild) {
13692 throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.");
13693 };
13694 _proto.insertBefore = function insertBefore(_newChild, _refChild) {
13695 throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.");
13696 };
13697 _proto.removeChild = function removeChild(_node) {
13698 throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.");
13699 };
13700 _proto.toString = function toString() {
13701 return "RRNode";
13702 };
13703 _create_class(BaseRRNode, [{
13704 key: "childNodes",
13705 get: function get() {
13706 var childNodes2 = [];
13707 var childIterator = this.firstChild;
13708 while (childIterator) {
13709 childNodes2.push(childIterator);
13710 childIterator = childIterator.nextSibling;
13711 }
13712 return childNodes2;
13713 }
13714 }]);
13715 return BaseRRNode;
13716 }();
13717 var testableAccessors = {
13718 Node: [
13719 "childNodes",
13720 "parentNode",
13721 "parentElement",
13722 "textContent"
13723 ],
13724 ShadowRoot: ["host", "styleSheets"],
13725 Element: [
13726 "shadowRoot",
13727 "querySelector",
13728 "querySelectorAll"
13729 ],
13730 MutationObserver: []
13731 };
13732 var testableMethods = {
13733 Node: ["contains", "getRootNode"],
13734 ShadowRoot: ["getSelection"],
13735 Element: [],
13736 MutationObserver: ["constructor"]
13737 };
13738 var untaintedBasePrototype = {};
13739 var isAngularZonePresent = function() {
13740 return !!globalThis.Zone;
13741 };
13742 function getUntaintedPrototype(key) {
13743 if (untaintedBasePrototype[key]) return untaintedBasePrototype[key];
13744 var defaultObj = globalThis[key];
13745 var defaultPrototype = defaultObj.prototype;
13746 var accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;
13747 var isUntaintedAccessors = Boolean(accessorNames && accessorNames.every(function(accessor) {
13748 var _a2;
13749 var _b;
13750 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
13751 }));
13752 var methodNames = key in testableMethods ? testableMethods[key] : void 0;
13753 var isUntaintedMethods = Boolean(methodNames && methodNames.every(function(method) {
13754 var _a2;
13755 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
13756 }));
13757 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent()) {
13758 untaintedBasePrototype[key] = defaultObj.prototype;
13759 return defaultObj.prototype;
13760 }
13761 try {
13762 var iframeEl = document.createElement("iframe");
13763 document.body.appendChild(iframeEl);
13764 var win = iframeEl.contentWindow;
13765 if (!win) return defaultObj.prototype;
13766 var untaintedObject = win[key].prototype;
13767 document.body.removeChild(iframeEl);
13768 if (!untaintedObject) return defaultPrototype;
13769 return untaintedBasePrototype[key] = untaintedObject;
13770 } catch (e) {
13771 return defaultPrototype;
13772 }
13773 }
13774 var untaintedAccessorCache = {};
13775 function getUntaintedAccessor(key, instance, accessor) {
13776 var _a2;
13777 var cacheKey = key + "." + String(accessor);
13778 if (untaintedAccessorCache[cacheKey]) return untaintedAccessorCache[cacheKey].call(instance);
13779 var untaintedPrototype = getUntaintedPrototype(key);
13780 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
13781 if (!untaintedAccessor) return instance[accessor];
13782 untaintedAccessorCache[cacheKey] = untaintedAccessor;
13783 return untaintedAccessor.call(instance);
13784 }
13785 var untaintedMethodCache = {};
13786 function getUntaintedMethod(key, instance, method) {
13787 var cacheKey = key + "." + String(method);
13788 if (untaintedMethodCache[cacheKey]) return untaintedMethodCache[cacheKey].bind(instance);
13789 var untaintedMethod = getUntaintedPrototype(key)[method];
13790 if (typeof untaintedMethod !== "function") return instance[method];
13791 untaintedMethodCache[cacheKey] = untaintedMethod;
13792 return untaintedMethod.bind(instance);
13793 }
13794 function childNodes(n2) {
13795 return getUntaintedAccessor("Node", n2, "childNodes");
13796 }
13797 function parentNode(n2) {
13798 return getUntaintedAccessor("Node", n2, "parentNode");
13799 }
13800 function parentElement(n2) {
13801 return getUntaintedAccessor("Node", n2, "parentElement");
13802 }
13803 function textContent(n2) {
13804 return getUntaintedAccessor("Node", n2, "textContent");
13805 }
13806 function contains(n2, other) {
13807 return getUntaintedMethod("Node", n2, "contains")(other);
13808 }
13809 function getRootNode(n2) {
13810 return getUntaintedMethod("Node", n2, "getRootNode")();
13811 }
13812 function host(n2) {
13813 if (!n2 || !("host" in n2)) return null;
13814 return getUntaintedAccessor("ShadowRoot", n2, "host");
13815 }
13816 function styleSheets(n2) {
13817 return n2.styleSheets;
13818 }
13819 function shadowRoot(n2) {
13820 if (!n2 || !("shadowRoot" in n2)) return null;
13821 return getUntaintedAccessor("Element", n2, "shadowRoot");
13822 }
13823 function querySelector(n2, selectors) {
13824 return getUntaintedAccessor("Element", n2, "querySelector")(selectors);
13825 }
13826 function querySelectorAll(n2, selectors) {
13827 return getUntaintedAccessor("Element", n2, "querySelectorAll")(selectors);
13828 }
13829 function mutationObserverCtor() {
13830 return getUntaintedPrototype("MutationObserver").constructor;
13831 }
13832 function patch(source, name, replacement) {
13833 try {
13834 if (!(name in source)) return function() {};
13835 var original = source[name];
13836 var wrapped = replacement(original);
13837 if (typeof wrapped === "function") {
13838 wrapped.prototype = wrapped.prototype || {};
13839 Object.defineProperties(wrapped, { __rrweb_original__: {
13840 enumerable: false,
13841 value: original
13842 } });
13843 }
13844 source[name] = wrapped;
13845 return function() {
13846 source[name] = original;
13847 };
13848 } catch (e) {
13849 return function() {};
13850 }
13851 }
13852 var index = {
13853 childNodes,
13854 parentNode,
13855 parentElement,
13856 textContent,
13857 contains,
13858 getRootNode,
13859 host,
13860 styleSheets,
13861 shadowRoot,
13862 querySelector,
13863 querySelectorAll,
13864 mutationObserver: mutationObserverCtor,
13865 patch
13866 };
13867 function on(type, fn, target) {
13868 if (target === void 0) target = document;
13869 var options = {
13870 capture: true,
13871 passive: true
13872 };
13873 target.addEventListener(type, fn, options);
13874 return function() {
13875 return target.removeEventListener(type, fn, options);
13876 };
13877 }
13878 var DEPARTED_MIRROR_ACCESS_WARNING = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";
13879 var _mirror = {
13880 map: {},
13881 getId: function getId() {
13882 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13883 return -1;
13884 },
13885 getNode: function getNode() {
13886 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13887 return null;
13888 },
13889 removeNodeFromMap: function removeNodeFromMap() {
13890 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13891 },
13892 has: function has() {
13893 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13894 return false;
13895 },
13896 reset: function reset() {
13897 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13898 }
13899 };
13900 if (typeof window !== "undefined" && window.Proxy && window.Reflect) _mirror = new Proxy(_mirror, { get: function get(target, prop, receiver) {
13901 if (prop === "map") console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13902 return Reflect.get(target, prop, receiver);
13903 } });
13904 function throttle(func, wait, options) {
13905 if (options === void 0) options = {};
13906 var timeout = null;
13907 var previous = 0;
13908 return function() {
13909 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
13910 var now = Date.now();
13911 if (!previous && options.leading === false) previous = now;
13912 var remaining = wait - (now - previous);
13913 var context = this;
13914 if (remaining <= 0 || remaining > wait) {
13915 if (timeout) {
13916 clearTimeout(timeout);
13917 timeout = null;
13918 }
13919 previous = now;
13920 func.apply(context, args);
13921 } else if (!timeout && options.trailing !== false) timeout = setTimeout(function() {
13922 previous = options.leading === false ? 0 : Date.now();
13923 timeout = null;
13924 func.apply(context, args);
13925 }, remaining);
13926 };
13927 }
13928 function hookSetter(target, key, d, isRevoked, win) {
13929 if (win === void 0) win = window;
13930 var original = win.Object.getOwnPropertyDescriptor(target, key);
13931 win.Object.defineProperty(target, key, isRevoked ? d : { set: function set(value) {
13932 var _this = this;
13933 setTimeout(function() {
13934 d.set.call(_this, value);
13935 }, 0);
13936 if (original && original.set) original.set.call(this, value);
13937 } });
13938 return function() {
13939 return hookSetter(target, key, original || {}, true);
13940 };
13941 }
13942 var nowTimestamp = Date.now;
13943 if (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) nowTimestamp = function() {
13944 return /* @__PURE__ */ (/* @__PURE__ */ new Date()).getTime();
13945 };
13946 function getWindowScroll(win) {
13947 var _a2;
13948 var _b;
13949 var _c;
13950 var _d;
13951 var doc = win.document;
13952 return {
13953 left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : doc.documentElement.scrollLeft || (doc == null ? void 0 : doc.body) && ((_a2 = index.parentElement(doc.body)) == null ? void 0 : _a2.scrollLeft) || ((_b = doc == null ? void 0 : doc.body) == null ? void 0 : _b.scrollLeft) || 0,
13954 top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : (doc == null ? void 0 : doc.documentElement.scrollTop) || (doc == null ? void 0 : doc.body) && ((_c = index.parentElement(doc.body)) == null ? void 0 : _c.scrollTop) || ((_d = doc == null ? void 0 : doc.body) == null ? void 0 : _d.scrollTop) || 0
13955 };
13956 }
13957 function getWindowHeight() {
13958 return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;
13959 }
13960 function getWindowWidth() {
13961 return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;
13962 }
13963 function closestElementOfNode(node2) {
13964 if (!node2) return null;
13965 return node2.nodeType === node2.ELEMENT_NODE ? node2 : index.parentElement(node2);
13966 }
13967 function isBlocked(node2, blockClass, blockSelector, checkAncestors) {
13968 if (!node2) return false;
13969 var el = closestElementOfNode(node2);
13970 if (!el) return false;
13971 try {
13972 if (typeof blockClass === "string") {
13973 if (el.classList.contains(blockClass)) return true;
13974 if (checkAncestors && el.closest("." + blockClass) !== null) return true;
13975 } else if (classMatchesRegex(el, blockClass, checkAncestors)) return true;
13976 } catch (e2) {}
13977 if (blockSelector) {
13978 if (el.matches(blockSelector)) return true;
13979 if (checkAncestors && el.closest(blockSelector) !== null) return true;
13980 }
13981 return false;
13982 }
13983 function isSerialized(n2, mirror2) {
13984 return mirror2.getId(n2) !== -1;
13985 }
13986 function isIgnored(n2, mirror2, slimDOMOptions) {
13987 if (n2.tagName === "TITLE" && slimDOMOptions.headTitleMutations) return true;
13988 return mirror2.getId(n2) === IGNORED_NODE;
13989 }
13990 function isAncestorRemoved(target, mirror2) {
13991 if (isShadowRoot(target)) return false;
13992 var id = mirror2.getId(target);
13993 if (!mirror2.has(id)) return true;
13994 var parent = index.parentNode(target);
13995 if (parent && parent.nodeType === target.DOCUMENT_NODE) return false;
13996 if (!parent) return true;
13997 return isAncestorRemoved(parent, mirror2);
13998 }
13999 function legacy_isTouchEvent(event) {
14000 return Boolean(event.changedTouches);
14001 }
14002 function polyfill$1(win) {
14003 if (win === void 0) win = window;
14004 if ("NodeList" in win && !win.NodeList.prototype.forEach) win.NodeList.prototype.forEach = Array.prototype.forEach;
14005 if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
14006 }
14007 function isSerializedIframe(n2, mirror2) {
14008 return Boolean(n2.nodeName === "IFRAME" && mirror2.getMeta(n2));
14009 }
14010 function isSerializedStylesheet(n2, mirror2) {
14011 return Boolean(n2.nodeName === "LINK" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute("rel") === "stylesheet" && mirror2.getMeta(n2));
14012 }
14013 function hasShadowRoot(n2) {
14014 if (!n2) return false;
14015 if (_instanceof(n2, BaseRRNode) && "shadowRoot" in n2) return Boolean(n2.shadowRoot);
14016 return Boolean(index.shadowRoot(n2));
14017 }
14018 var StyleSheetMirror = /*#__PURE__*/ function() {
14019 function StyleSheetMirror() {
14020 __publicField(this, "id", 1);
14021 __publicField(this, "styleIDMap", /* @__PURE__ */ new WeakMap());
14022 __publicField(this, "idStyleMap", /* @__PURE__ */ new Map());
14023 }
14024 var _proto = StyleSheetMirror.prototype;
14025 _proto.getId = function getId(stylesheet) {
14026 var _this_styleIDMap_get;
14027 return (_this_styleIDMap_get = this.styleIDMap.get(stylesheet)) != null ? _this_styleIDMap_get : -1;
14028 };
14029 _proto.has = function has(stylesheet) {
14030 return this.styleIDMap.has(stylesheet);
14031 };
14032 /**
14033 * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.
14034 */ _proto.add = function add(stylesheet, id) {
14035 if (this.has(stylesheet)) return this.getId(stylesheet);
14036 var newId;
14037 if (id === void 0) newId = this.id++;
14038 else newId = id;
14039 this.styleIDMap.set(stylesheet, newId);
14040 this.idStyleMap.set(newId, stylesheet);
14041 return newId;
14042 };
14043 _proto.getStyle = function getStyle(id) {
14044 return this.idStyleMap.get(id) || null;
14045 };
14046 _proto.reset = function reset() {
14047 this.styleIDMap = /* @__PURE__ */ new WeakMap();
14048 this.idStyleMap = /* @__PURE__ */ new Map();
14049 this.id = 1;
14050 };
14051 _proto.generateId = function generateId() {
14052 return this.id++;
14053 };
14054 return StyleSheetMirror;
14055 }();
14056 function getShadowHost(n2) {
14057 var _a2;
14058 var shadowHost = null;
14059 if ("getRootNode" in n2 && ((_a2 = index.getRootNode(n2)) == null ? void 0 : _a2.nodeType) === Node.DOCUMENT_FRAGMENT_NODE && index.host(index.getRootNode(n2))) shadowHost = index.host(index.getRootNode(n2));
14060 return shadowHost;
14061 }
14062 function getRootShadowHost(n2) {
14063 var rootShadowHost = n2;
14064 var shadowHost;
14065 while (shadowHost = getShadowHost(rootShadowHost)) rootShadowHost = shadowHost;
14066 return rootShadowHost;
14067 }
14068 function shadowHostInDom(n2) {
14069 var doc = n2.ownerDocument;
14070 if (!doc) return false;
14071 var shadowHost = getRootShadowHost(n2);
14072 return index.contains(doc, shadowHost);
14073 }
14074 function inDom(n2) {
14075 var doc = n2.ownerDocument;
14076 if (!doc) return false;
14077 return index.contains(doc, n2) || shadowHostInDom(n2);
14078 }
14079 var EventType = /* @__PURE__ */ function(EventType2) {
14080 EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
14081 EventType2[EventType2["Load"] = 1] = "Load";
14082 EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
14083 EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
14084 EventType2[EventType2["Meta"] = 4] = "Meta";
14085 EventType2[EventType2["Custom"] = 5] = "Custom";
14086 EventType2[EventType2["Plugin"] = 6] = "Plugin";
14087 return EventType2;
14088 }(EventType || {});
14089 var IncrementalSource = /* @__PURE__ */ function(IncrementalSource2) {
14090 IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
14091 IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
14092 IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
14093 IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
14094 IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
14095 IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
14096 IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
14097 IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
14098 IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
14099 IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
14100 IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
14101 IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
14102 IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
14103 IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
14104 IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
14105 IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
14106 IncrementalSource2[IncrementalSource2["CustomElement"] = 16] = "CustomElement";
14107 return IncrementalSource2;
14108 }(IncrementalSource || {});
14109 var MouseInteractions = /* @__PURE__ */ function(MouseInteractions2) {
14110 MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
14111 MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
14112 MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
14113 MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
14114 MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
14115 MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
14116 MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
14117 MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
14118 MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
14119 MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
14120 MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
14121 return MouseInteractions2;
14122 }(MouseInteractions || {});
14123 var PointerTypes = /* @__PURE__ */ function(PointerTypes2) {
14124 PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse";
14125 PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen";
14126 PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch";
14127 return PointerTypes2;
14128 }(PointerTypes || {});
14129 var CanvasContext = /* @__PURE__ */ function(CanvasContext2) {
14130 CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
14131 CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
14132 CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
14133 return CanvasContext2;
14134 }(CanvasContext || {});
14135 var MediaInteractions = /* @__PURE__ */ function(MediaInteractions2) {
14136 MediaInteractions2[MediaInteractions2["Play"] = 0] = "Play";
14137 MediaInteractions2[MediaInteractions2["Pause"] = 1] = "Pause";
14138 MediaInteractions2[MediaInteractions2["Seeked"] = 2] = "Seeked";
14139 MediaInteractions2[MediaInteractions2["VolumeChange"] = 3] = "VolumeChange";
14140 MediaInteractions2[MediaInteractions2["RateChange"] = 4] = "RateChange";
14141 return MediaInteractions2;
14142 }(MediaInteractions || {});
14143 var NodeType = /* @__PURE__ */ function(NodeType2) {
14144 NodeType2[NodeType2["Document"] = 0] = "Document";
14145 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
14146 NodeType2[NodeType2["Element"] = 2] = "Element";
14147 NodeType2[NodeType2["Text"] = 3] = "Text";
14148 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
14149 NodeType2[NodeType2["Comment"] = 5] = "Comment";
14150 return NodeType2;
14151 }(NodeType || {});
14152 function isNodeInLinkedList(n2) {
14153 return "__ln" in n2;
14154 }
14155 var DoubleLinkedList = /*#__PURE__*/ function() {
14156 function DoubleLinkedList() {
14157 __publicField(this, "length", 0);
14158 __publicField(this, "head", null);
14159 __publicField(this, "tail", null);
14160 }
14161 var _proto = DoubleLinkedList.prototype;
14162 _proto.get = function get(position) {
14163 if (position >= this.length) throw new Error("Position outside of list range");
14164 var current = this.head;
14165 for (var index2 = 0; index2 < position; index2++) current = (current == null ? void 0 : current.next) || null;
14166 return current;
14167 };
14168 _proto.addNode = function addNode(n2) {
14169 var node2 = {
14170 value: n2,
14171 previous: null,
14172 next: null
14173 };
14174 n2.__ln = node2;
14175 if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) {
14176 var current = n2.previousSibling.__ln.next;
14177 node2.next = current;
14178 node2.previous = n2.previousSibling.__ln;
14179 n2.previousSibling.__ln.next = node2;
14180 if (current) current.previous = node2;
14181 } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) {
14182 var current1 = n2.nextSibling.__ln.previous;
14183 node2.previous = current1;
14184 node2.next = n2.nextSibling.__ln;
14185 n2.nextSibling.__ln.previous = node2;
14186 if (current1) current1.next = node2;
14187 } else {
14188 if (this.head) this.head.previous = node2;
14189 node2.next = this.head;
14190 this.head = node2;
14191 }
14192 if (node2.next === null) this.tail = node2;
14193 this.length++;
14194 };
14195 _proto.removeNode = function removeNode(n2) {
14196 var current = n2.__ln;
14197 if (!this.head) return;
14198 if (!current.previous) {
14199 this.head = current.next;
14200 if (this.head) this.head.previous = null;
14201 else this.tail = null;
14202 } else {
14203 current.previous.next = current.next;
14204 if (current.next) current.next.previous = current.previous;
14205 else this.tail = current.previous;
14206 }
14207 if (n2.__ln) delete n2.__ln;
14208 this.length--;
14209 };
14210 return DoubleLinkedList;
14211 }();
14212 var moveKey = function(id, parentId) {
14213 return id + "@" + parentId;
14214 };
14215 var MutationBuffer = /*#__PURE__*/ function() {
14216 function MutationBuffer() {
14217 var _this = this;
14218 __publicField(this, "frozen", false);
14219 __publicField(this, "locked", false);
14220 __publicField(this, "texts", []);
14221 __publicField(this, "attributes", []);
14222 __publicField(this, "attributeMap", /* @__PURE__ */ new WeakMap());
14223 __publicField(this, "removes", []);
14224 __publicField(this, "mapRemoves", []);
14225 __publicField(this, "movedMap", {});
14226 /**
14227 * the browser MutationObserver emits multiple mutations after
14228 * a delay for performance reasons, making tracing added nodes hard
14229 * in our `processMutations` callback function.
14230 * For example, if we append an element el_1 into body, and then append
14231 * another element el_2 into el_1, these two mutations may be passed to the
14232 * callback function together when the two operations were done.
14233 * Generally we need to trace child nodes of newly added nodes, but in this
14234 * case if we count el_2 as el_1's child node in the first mutation record,
14235 * then we will count el_2 again in the second mutation record which was
14236 * duplicated.
14237 * To avoid of duplicate counting added nodes, we use a Set to store
14238 * added nodes and its child nodes during iterate mutation records. Then
14239 * collect added nodes from the Set which have no duplicate copy. But
14240 * this also causes newly added nodes will not be serialized with id ASAP,
14241 * which means all the id related calculation should be lazy too.
14242 */ __publicField(this, "addedSet", /* @__PURE__ */ new Set());
14243 __publicField(this, "movedSet", /* @__PURE__ */ new Set());
14244 __publicField(this, "droppedSet", /* @__PURE__ */ new Set());
14245 __publicField(this, "removesSubTreeCache", /* @__PURE__ */ new Set());
14246 __publicField(this, "mutationCb");
14247 __publicField(this, "blockClass");
14248 __publicField(this, "blockSelector");
14249 __publicField(this, "maskTextClass");
14250 __publicField(this, "maskTextSelector");
14251 __publicField(this, "inlineStylesheet");
14252 __publicField(this, "maskInputOptions");
14253 __publicField(this, "maskTextFn");
14254 __publicField(this, "maskInputFn");
14255 __publicField(this, "keepIframeSrcFn");
14256 __publicField(this, "recordCanvas");
14257 __publicField(this, "inlineImages");
14258 __publicField(this, "slimDOMOptions");
14259 __publicField(this, "dataURLOptions");
14260 __publicField(this, "doc");
14261 __publicField(this, "mirror");
14262 __publicField(this, "iframeManager");
14263 __publicField(this, "stylesheetManager");
14264 __publicField(this, "shadowDomManager");
14265 __publicField(this, "canvasManager");
14266 __publicField(this, "processedNodeManager");
14267 __publicField(this, "unattachedDoc");
14268 __publicField(this, "processMutations", function(mutations) {
14269 mutations.forEach(_this.processMutation);
14270 _this.emit();
14271 });
14272 __publicField(this, "emit", function() {
14273 if (_this.frozen || _this.locked) return;
14274 var adds = [];
14275 var addedIds = /* @__PURE__ */ new Set();
14276 var addList = new DoubleLinkedList();
14277 var getNextId = function(n2) {
14278 var ns = n2;
14279 var nextId = IGNORED_NODE;
14280 while (nextId === IGNORED_NODE) {
14281 ns = ns && ns.nextSibling;
14282 nextId = ns && _this.mirror.getId(ns);
14283 }
14284 return nextId;
14285 };
14286 var pushAdd = function(n2) {
14287 var parent = index.parentNode(n2);
14288 if (!parent || !inDom(n2)) return;
14289 var cssCaptured = false;
14290 if (n2.nodeType === Node.TEXT_NODE) {
14291 var parentTag = parent.tagName;
14292 if (parentTag === "TEXTAREA") return;
14293 else if (parentTag === "STYLE" && _this.addedSet.has(parent)) cssCaptured = true;
14294 }
14295 var parentId = isShadowRoot(parent) ? _this.mirror.getId(getShadowHost(n2)) : _this.mirror.getId(parent);
14296 var nextId = getNextId(n2);
14297 if (parentId === -1 || nextId === -1) return addList.addNode(n2);
14298 var sn = serializeNodeWithId(n2, {
14299 doc: _this.doc,
14300 mirror: _this.mirror,
14301 blockClass: _this.blockClass,
14302 blockSelector: _this.blockSelector,
14303 maskTextClass: _this.maskTextClass,
14304 maskTextSelector: _this.maskTextSelector,
14305 skipChild: true,
14306 newlyAddedElement: true,
14307 inlineStylesheet: _this.inlineStylesheet,
14308 maskInputOptions: _this.maskInputOptions,
14309 maskTextFn: _this.maskTextFn,
14310 maskInputFn: _this.maskInputFn,
14311 slimDOMOptions: _this.slimDOMOptions,
14312 dataURLOptions: _this.dataURLOptions,
14313 recordCanvas: _this.recordCanvas,
14314 inlineImages: _this.inlineImages,
14315 onSerialize: function(currentN) {
14316 if (isSerializedIframe(currentN, _this.mirror)) _this.iframeManager.addIframe(currentN);
14317 if (isSerializedStylesheet(currentN, _this.mirror)) _this.stylesheetManager.trackLinkElement(currentN);
14318 if (hasShadowRoot(n2)) _this.shadowDomManager.addShadowRoot(index.shadowRoot(n2), _this.doc);
14319 },
14320 onIframeLoad: function(iframe, childSn) {
14321 _this.iframeManager.attachIframe(iframe, childSn);
14322 _this.shadowDomManager.observeAttachShadow(iframe);
14323 },
14324 onStylesheetLoad: function(link, childSn) {
14325 _this.stylesheetManager.attachLinkElement(link, childSn);
14326 },
14327 cssCaptured
14328 });
14329 if (sn) {
14330 adds.push({
14331 parentId,
14332 nextId,
14333 node: sn
14334 });
14335 addedIds.add(sn.id);
14336 }
14337 };
14338 while (_this.mapRemoves.length) _this.mirror.removeNodeFromMap(_this.mapRemoves.shift());
14339 for (var _iterator = _create_for_of_iterator_helper_loose(_this.movedSet), _step; !(_step = _iterator()).done;) {
14340 var n2 = _step.value;
14341 if (isParentRemoved(_this.removesSubTreeCache, n2, _this.mirror) && !_this.movedSet.has(index.parentNode(n2))) continue;
14342 pushAdd(n2);
14343 }
14344 for (var _iterator1 = _create_for_of_iterator_helper_loose(_this.addedSet), _step1; !(_step1 = _iterator1()).done;) {
14345 var n21 = _step1.value;
14346 if (!isAncestorInSet(_this.droppedSet, n21) && !isParentRemoved(_this.removesSubTreeCache, n21, _this.mirror)) pushAdd(n21);
14347 else if (isAncestorInSet(_this.movedSet, n21)) pushAdd(n21);
14348 else _this.droppedSet.add(n21);
14349 }
14350 var candidate = null;
14351 while (addList.length) {
14352 var node2 = null;
14353 if (candidate) {
14354 var parentId = _this.mirror.getId(index.parentNode(candidate.value));
14355 var nextId = getNextId(candidate.value);
14356 if (parentId !== -1 && nextId !== -1) node2 = candidate;
14357 }
14358 if (!node2) {
14359 var tailNode = addList.tail;
14360 while (tailNode) {
14361 var _node = tailNode;
14362 tailNode = tailNode.previous;
14363 if (_node) {
14364 var parentId1 = _this.mirror.getId(index.parentNode(_node.value));
14365 if (getNextId(_node.value) === -1) continue;
14366 else if (parentId1 !== -1) {
14367 node2 = _node;
14368 break;
14369 } else {
14370 var unhandledNode = _node.value;
14371 var parent = index.parentNode(unhandledNode);
14372 if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
14373 var shadowHost = index.host(parent);
14374 if (_this.mirror.getId(shadowHost) !== -1) {
14375 node2 = _node;
14376 break;
14377 }
14378 }
14379 }
14380 }
14381 }
14382 }
14383 if (!node2) {
14384 while (addList.head) addList.removeNode(addList.head.value);
14385 break;
14386 }
14387 candidate = node2.previous;
14388 addList.removeNode(node2.value);
14389 pushAdd(node2.value);
14390 }
14391 var payload = {
14392 texts: _this.texts.map(function(text) {
14393 var n2 = text.node;
14394 var parent = index.parentNode(n2);
14395 if (parent && parent.tagName === "TEXTAREA") _this.genTextAreaValueMutation(parent);
14396 return {
14397 id: _this.mirror.getId(n2),
14398 value: text.value
14399 };
14400 }).filter(function(text) {
14401 return !addedIds.has(text.id);
14402 }).filter(function(text) {
14403 return _this.mirror.has(text.id);
14404 }),
14405 attributes: _this.attributes.map(function(attribute) {
14406 var attributes = attribute.attributes;
14407 if (typeof attributes.style === "string") {
14408 var diffAsStr = JSON.stringify(attribute.styleDiff);
14409 var unchangedAsStr = JSON.stringify(attribute._unchangedStyles);
14410 if (diffAsStr.length < attributes.style.length) {
14411 if ((diffAsStr + unchangedAsStr).split("var(").length === attributes.style.split("var(").length) attributes.style = attribute.styleDiff;
14412 }
14413 }
14414 return {
14415 id: _this.mirror.getId(attribute.node),
14416 attributes
14417 };
14418 }).filter(function(attribute) {
14419 return !addedIds.has(attribute.id);
14420 }).filter(function(attribute) {
14421 return _this.mirror.has(attribute.id);
14422 }),
14423 removes: _this.removes,
14424 adds
14425 };
14426 if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) return;
14427 _this.texts = [];
14428 _this.attributes = [];
14429 _this.attributeMap = /* @__PURE__ */ new WeakMap();
14430 _this.removes = [];
14431 _this.addedSet = /* @__PURE__ */ new Set();
14432 _this.movedSet = /* @__PURE__ */ new Set();
14433 _this.droppedSet = /* @__PURE__ */ new Set();
14434 _this.removesSubTreeCache = /* @__PURE__ */ new Set();
14435 _this.movedMap = {};
14436 _this.mutationCb(payload);
14437 });
14438 __publicField(this, "genTextAreaValueMutation", function(textarea) {
14439 var item = _this.attributeMap.get(textarea);
14440 if (!item) {
14441 item = {
14442 node: textarea,
14443 attributes: {},
14444 styleDiff: {},
14445 _unchangedStyles: {}
14446 };
14447 _this.attributes.push(item);
14448 _this.attributeMap.set(textarea, item);
14449 }
14450 var value = Array.from(index.childNodes(textarea), function(cn) {
14451 return index.textContent(cn) || "";
14452 }).join("");
14453 item.attributes.value = maskInputValue({
14454 element: textarea,
14455 maskInputOptions: _this.maskInputOptions,
14456 tagName: textarea.tagName,
14457 type: getInputType(textarea),
14458 value,
14459 maskInputFn: _this.maskInputFn
14460 });
14461 });
14462 __publicField(this, "processMutation", function(m) {
14463 if (isIgnored(m.target, _this.mirror, _this.slimDOMOptions)) return;
14464 switch (m.type) {
14465 case "characterData":
14466 var value = index.textContent(m.target);
14467 if (!isBlocked(m.target, _this.blockClass, _this.blockSelector, false) && value !== m.oldValue) _this.texts.push({
14468 value: needMaskingText(m.target, _this.maskTextClass, _this.maskTextSelector, true) && value ? _this.maskTextFn ? _this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\S]/g, "*") : value,
14469 node: m.target
14470 });
14471 break;
14472 case "attributes":
14473 var target = m.target;
14474 var attributeName = m.attributeName;
14475 var value1 = m.target.getAttribute(attributeName);
14476 if (attributeName === "value") {
14477 var type = getInputType(target);
14478 value1 = maskInputValue({
14479 element: target,
14480 maskInputOptions: _this.maskInputOptions,
14481 tagName: target.tagName,
14482 type,
14483 value: value1,
14484 maskInputFn: _this.maskInputFn
14485 });
14486 }
14487 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || value1 === m.oldValue) return;
14488 var item = _this.attributeMap.get(m.target);
14489 if (target.tagName === "IFRAME" && attributeName === "src" && !_this.keepIframeSrcFn(value1)) if (!target.contentDocument) attributeName = "rr_src";
14490 else return;
14491 if (!item) {
14492 item = {
14493 node: m.target,
14494 attributes: {},
14495 styleDiff: {},
14496 _unchangedStyles: {}
14497 };
14498 _this.attributes.push(item);
14499 _this.attributeMap.set(m.target, item);
14500 }
14501 if (attributeName === "type" && target.tagName === "INPUT" && (m.oldValue || "").toLowerCase() === "password") target.setAttribute("data-rr-is-password", "true");
14502 if (!ignoreAttribute(target.tagName, attributeName)) {
14503 item.attributes[attributeName] = transformAttribute(_this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value1);
14504 if (attributeName === "style") {
14505 if (!_this.unattachedDoc) try {
14506 _this.unattachedDoc = document.implementation.createHTMLDocument();
14507 } catch (e2) {
14508 _this.unattachedDoc = _this.doc;
14509 }
14510 var old = _this.unattachedDoc.createElement("span");
14511 if (m.oldValue) old.setAttribute("style", m.oldValue);
14512 for (var _iterator = _create_for_of_iterator_helper_loose(Array.from(target.style)), _step; !(_step = _iterator()).done;) {
14513 var pname = _step.value;
14514 var newValue = target.style.getPropertyValue(pname);
14515 var newPriority = target.style.getPropertyPriority(pname);
14516 if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) if (newPriority === "") item.styleDiff[pname] = newValue;
14517 else item.styleDiff[pname] = [newValue, newPriority];
14518 else item._unchangedStyles[pname] = [newValue, newPriority];
14519 }
14520 for (var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(old.style)), _step1; !(_step1 = _iterator1()).done;) {
14521 var pname1 = _step1.value;
14522 if (target.style.getPropertyValue(pname1) === "") item.styleDiff[pname1] = false;
14523 }
14524 } else if (attributeName === "open" && target.tagName === "DIALOG") if (target.matches("dialog:modal")) item.attributes["rr_open_mode"] = "modal";
14525 else item.attributes["rr_open_mode"] = "non-modal";
14526 }
14527 break;
14528 case "childList":
14529 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, true)) return;
14530 if (m.target.tagName === "TEXTAREA") {
14531 _this.genTextAreaValueMutation(m.target);
14532 return;
14533 }
14534 m.addedNodes.forEach(function(n2) {
14535 return _this.genAdds(n2, m.target);
14536 });
14537 m.removedNodes.forEach(function(n2) {
14538 var nodeId = _this.mirror.getId(n2);
14539 var parentId = isShadowRoot(m.target) ? _this.mirror.getId(index.host(m.target)) : _this.mirror.getId(m.target);
14540 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || isIgnored(n2, _this.mirror, _this.slimDOMOptions) || !isSerialized(n2, _this.mirror)) return;
14541 if (_this.addedSet.has(n2)) {
14542 deepDelete(_this.addedSet, n2);
14543 _this.droppedSet.add(n2);
14544 } else if (_this.addedSet.has(m.target) && nodeId === -1);
14545 else if (isAncestorRemoved(m.target, _this.mirror));
14546 else if (_this.movedSet.has(n2) && _this.movedMap[moveKey(nodeId, parentId)]) deepDelete(_this.movedSet, n2);
14547 else {
14548 _this.removes.push({
14549 parentId,
14550 id: nodeId,
14551 isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0
14552 });
14553 processRemoves(n2, _this.removesSubTreeCache);
14554 }
14555 _this.mapRemoves.push(n2);
14556 });
14557 break;
14558 }
14559 });
14560 /**
14561 * Make sure you check if `n`'s parent is blocked before calling this function
14562 * */ __publicField(this, "genAdds", function(n2, target) {
14563 if (_this.processedNodeManager.inOtherBuffer(n2, _this)) return;
14564 if (_this.addedSet.has(n2) || _this.movedSet.has(n2)) return;
14565 if (_this.mirror.hasNode(n2)) {
14566 if (isIgnored(n2, _this.mirror, _this.slimDOMOptions)) return;
14567 _this.movedSet.add(n2);
14568 var targetId = null;
14569 if (target && _this.mirror.hasNode(target)) targetId = _this.mirror.getId(target);
14570 if (targetId && targetId !== -1) _this.movedMap[moveKey(_this.mirror.getId(n2), targetId)] = true;
14571 } else {
14572 _this.addedSet.add(n2);
14573 _this.droppedSet.delete(n2);
14574 }
14575 if (!isBlocked(n2, _this.blockClass, _this.blockSelector, false)) {
14576 index.childNodes(n2).forEach(function(childN) {
14577 return _this.genAdds(childN);
14578 });
14579 if (hasShadowRoot(n2)) index.childNodes(index.shadowRoot(n2)).forEach(function(childN) {
14580 _this.processedNodeManager.add(childN, _this);
14581 _this.genAdds(childN, n2);
14582 });
14583 }
14584 });
14585 }
14586 var _proto = MutationBuffer.prototype;
14587 _proto.init = function init(options) {
14588 var _this = this;
14589 [
14590 "mutationCb",
14591 "blockClass",
14592 "blockSelector",
14593 "maskTextClass",
14594 "maskTextSelector",
14595 "inlineStylesheet",
14596 "maskInputOptions",
14597 "maskTextFn",
14598 "maskInputFn",
14599 "keepIframeSrcFn",
14600 "recordCanvas",
14601 "inlineImages",
14602 "slimDOMOptions",
14603 "dataURLOptions",
14604 "doc",
14605 "mirror",
14606 "iframeManager",
14607 "stylesheetManager",
14608 "shadowDomManager",
14609 "canvasManager",
14610 "processedNodeManager"
14611 ].forEach(function(key) {
14612 _this[key] = options[key];
14613 });
14614 };
14615 _proto.freeze = function freeze() {
14616 this.frozen = true;
14617 this.canvasManager.freeze();
14618 };
14619 _proto.unfreeze = function unfreeze() {
14620 this.frozen = false;
14621 this.canvasManager.unfreeze();
14622 this.emit();
14623 };
14624 _proto.isFrozen = function isFrozen() {
14625 return this.frozen;
14626 };
14627 _proto.lock = function lock() {
14628 this.locked = true;
14629 this.canvasManager.lock();
14630 };
14631 _proto.unlock = function unlock() {
14632 this.locked = false;
14633 this.canvasManager.unlock();
14634 this.emit();
14635 };
14636 _proto.reset = function reset() {
14637 this.shadowDomManager.reset();
14638 this.canvasManager.reset();
14639 };
14640 return MutationBuffer;
14641 }();
14642 function deepDelete(addsSet, n2) {
14643 addsSet.delete(n2);
14644 index.childNodes(n2).forEach(function(childN) {
14645 return deepDelete(addsSet, childN);
14646 });
14647 }
14648 function processRemoves(n2, cache) {
14649 var queue = [n2];
14650 while (queue.length) {
14651 var next = queue.pop();
14652 if (cache.has(next)) continue;
14653 cache.add(next);
14654 index.childNodes(next).forEach(function(n22) {
14655 return queue.push(n22);
14656 });
14657 }
14658 }
14659 function isParentRemoved(removes, n2, mirror2) {
14660 if (removes.size === 0) return false;
14661 return _isParentRemoved(removes, n2);
14662 }
14663 function _isParentRemoved(removes, n2, _mirror2) {
14664 var node2 = index.parentNode(n2);
14665 if (!node2) return false;
14666 return removes.has(node2);
14667 }
14668 function isAncestorInSet(set, n2) {
14669 if (set.size === 0) return false;
14670 return _isAncestorInSet(set, n2);
14671 }
14672 function _isAncestorInSet(set, n2) {
14673 var parent = index.parentNode(n2);
14674 if (!parent) return false;
14675 if (set.has(parent)) return true;
14676 return _isAncestorInSet(set, parent);
14677 }
14678 var errorHandler;
14679 function registerErrorHandler(handler) {
14680 errorHandler = handler;
14681 }
14682 function unregisterErrorHandler() {
14683 errorHandler = void 0;
14684 }
14685 var callbackWrapper = function(cb) {
14686 if (!errorHandler) return cb;
14687 var rrwebWrapped = function() {
14688 for (var _len = arguments.length, rest = new Array(_len), _key = 0; _key < _len; _key++) rest[_key] = arguments[_key];
14689 try {
14690 return cb.apply(void 0, [].concat(rest));
14691 } catch (error) {
14692 if (errorHandler && errorHandler(error) === true) return;
14693 throw error;
14694 }
14695 };
14696 return rrwebWrapped;
14697 };
14698 var mutationBuffers = [];
14699 function getEventTarget(event) {
14700 try {
14701 if ("composedPath" in event) {
14702 var path = event.composedPath();
14703 if (path.length) return path[0];
14704 } else if ("path" in event && event.path.length) return event.path[0];
14705 } catch (e) {}
14706 return event && event.target;
14707 }
14708 function initMutationObserver(options, rootEl) {
14709 var mutationBuffer = new MutationBuffer();
14710 mutationBuffers.push(mutationBuffer);
14711 mutationBuffer.init(options);
14712 var observer = new (mutationObserverCtor())(callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)));
14713 observer.observe(rootEl, {
14714 attributes: true,
14715 attributeOldValue: true,
14716 characterData: true,
14717 characterDataOldValue: true,
14718 childList: true,
14719 subtree: true
14720 });
14721 return observer;
14722 }
14723 function initMoveObserver(param) {
14724 var mousemoveCb = param.mousemoveCb;
14725 var sampling = param.sampling;
14726 var doc = param.doc;
14727 var mirror2 = param.mirror;
14728 if (sampling.mousemove === false) return function() {};
14729 var threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50;
14730 var callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500;
14731 var positions = [];
14732 var timeBaseline;
14733 var wrappedCb = throttle(callbackWrapper(function(source) {
14734 var totalOffset = Date.now() - timeBaseline;
14735 mousemoveCb(positions.map(function(p) {
14736 p.timeOffset -= totalOffset;
14737 return p;
14738 }), source);
14739 positions = [];
14740 timeBaseline = null;
14741 }), callbackThreshold);
14742 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
14743 var target = getEventTarget(evt);
14744 var _ref = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;
14745 var clientX = _ref.clientX;
14746 var clientY = _ref.clientY;
14747 if (!timeBaseline) timeBaseline = nowTimestamp();
14748 positions.push({
14749 x: clientX,
14750 y: clientY,
14751 id: mirror2.getId(target),
14752 timeOffset: nowTimestamp() - timeBaseline
14753 });
14754 wrappedCb(typeof DragEvent !== "undefined" && _instanceof(evt, DragEvent) ? IncrementalSource.Drag : _instanceof(evt, MouseEvent) ? IncrementalSource.MouseMove : IncrementalSource.TouchMove);
14755 }), threshold, { trailing: false }));
14756 var handlers = [
14757 on("mousemove", updatePosition, doc),
14758 on("touchmove", updatePosition, doc),
14759 on("drag", updatePosition, doc)
14760 ];
14761 return callbackWrapper(function() {
14762 handlers.forEach(function(h) {
14763 return h();
14764 });
14765 });
14766 }
14767 function initMouseInteractionObserver(param) {
14768 var mouseInteractionCb = param.mouseInteractionCb;
14769 var doc = param.doc;
14770 var mirror2 = param.mirror;
14771 var blockClass = param.blockClass;
14772 var blockSelector = param.blockSelector;
14773 var sampling = param.sampling;
14774 if (sampling.mouseInteraction === false) return function() {};
14775 var disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;
14776 var handlers = [];
14777 var currentPointerType = null;
14778 var getHandler = function(eventKey) {
14779 return function(event) {
14780 var target = getEventTarget(event);
14781 if (isBlocked(target, blockClass, blockSelector, true)) return;
14782 var pointerType = null;
14783 var thisEventKey = eventKey;
14784 if ("pointerType" in event) {
14785 switch (event.pointerType) {
14786 case "mouse":
14787 pointerType = PointerTypes.Mouse;
14788 break;
14789 case "touch":
14790 pointerType = PointerTypes.Touch;
14791 break;
14792 case "pen":
14793 pointerType = PointerTypes.Pen;
14794 break;
14795 }
14796 if (pointerType === PointerTypes.Touch) {
14797 if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) thisEventKey = "TouchStart";
14798 else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) thisEventKey = "TouchEnd";
14799 } else if (pointerType === PointerTypes.Pen);
14800 } else if (legacy_isTouchEvent(event)) pointerType = PointerTypes.Touch;
14801 if (pointerType !== null) {
14802 currentPointerType = pointerType;
14803 if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) pointerType = null;
14804 } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {
14805 pointerType = currentPointerType;
14806 currentPointerType = null;
14807 }
14808 var e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;
14809 if (!e2) return;
14810 var id = mirror2.getId(target);
14811 var clientX = e2.clientX;
14812 var clientY = e2.clientY;
14813 callbackWrapper(mouseInteractionCb)(_extends({
14814 type: MouseInteractions[thisEventKey],
14815 id,
14816 x: clientX,
14817 y: clientY
14818 }, pointerType !== null && { pointerType }));
14819 };
14820 };
14821 Object.keys(MouseInteractions).filter(function(key) {
14822 return Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false;
14823 }).forEach(function(eventKey) {
14824 var eventName = toLowerCase(eventKey);
14825 var handler = getHandler(eventKey);
14826 if (window.PointerEvent) switch (MouseInteractions[eventKey]) {
14827 case MouseInteractions.MouseDown:
14828 case MouseInteractions.MouseUp:
14829 eventName = eventName.replace("mouse", "pointer");
14830 break;
14831 case MouseInteractions.TouchStart:
14832 case MouseInteractions.TouchEnd: return;
14833 }
14834 handlers.push(on(eventName, handler, doc));
14835 });
14836 return callbackWrapper(function() {
14837 handlers.forEach(function(h) {
14838 return h();
14839 });
14840 });
14841 }
14842 function initScrollObserver(param) {
14843 var scrollCb = param.scrollCb;
14844 var doc = param.doc;
14845 var mirror2 = param.mirror;
14846 var blockClass = param.blockClass;
14847 var blockSelector = param.blockSelector;
14848 var sampling = param.sampling;
14849 return on("scroll", callbackWrapper(throttle(callbackWrapper(function(evt) {
14850 var target = getEventTarget(evt);
14851 if (!target || isBlocked(target, blockClass, blockSelector, true)) return;
14852 var id = mirror2.getId(target);
14853 if (target === doc && doc.defaultView) {
14854 var scrollLeftTop = getWindowScroll(doc.defaultView);
14855 scrollCb({
14856 id,
14857 x: scrollLeftTop.left,
14858 y: scrollLeftTop.top
14859 });
14860 } else scrollCb({
14861 id,
14862 x: target.scrollLeft,
14863 y: target.scrollTop
14864 });
14865 }), sampling.scroll || 100)), doc);
14866 }
14867 function initViewportResizeObserver(param, param1) {
14868 var viewportResizeCb = param.viewportResizeCb;
14869 var win = param1.win;
14870 var lastH = -1;
14871 var lastW = -1;
14872 return on("resize", callbackWrapper(throttle(callbackWrapper(function() {
14873 var height = getWindowHeight();
14874 var width = getWindowWidth();
14875 if (lastH !== height || lastW !== width) {
14876 viewportResizeCb({
14877 width: Number(width),
14878 height: Number(height)
14879 });
14880 lastH = height;
14881 lastW = width;
14882 }
14883 }), 200)), win);
14884 }
14885 var INPUT_TAGS = [
14886 "INPUT",
14887 "TEXTAREA",
14888 "SELECT"
14889 ];
14890 var lastInputValueMap = /* @__PURE__ */ new WeakMap();
14891 function initInputObserver(param) {
14892 var inputCb = param.inputCb;
14893 var doc = param.doc;
14894 var mirror2 = param.mirror;
14895 var blockClass = param.blockClass;
14896 var blockSelector = param.blockSelector;
14897 var ignoreClass = param.ignoreClass;
14898 var ignoreSelector = param.ignoreSelector;
14899 var maskInputOptions = param.maskInputOptions;
14900 var maskInputFn = param.maskInputFn;
14901 var sampling = param.sampling;
14902 var userTriggeredOnInput = param.userTriggeredOnInput;
14903 function eventHandler(event) {
14904 var target = getEventTarget(event);
14905 var userTriggered = event.isTrusted;
14906 var tagName = target && target.tagName;
14907 if (target && tagName === "OPTION") target = index.parentElement(target);
14908 if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) return;
14909 if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) return;
14910 var text = target.value;
14911 var isChecked = false;
14912 var type = getInputType(target) || "";
14913 if (type === "radio" || type === "checkbox") isChecked = target.checked;
14914 else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) text = maskInputValue({
14915 element: target,
14916 maskInputOptions,
14917 tagName,
14918 type,
14919 value: text,
14920 maskInputFn
14921 });
14922 cbWithDedup(target, userTriggeredOnInput ? {
14923 text,
14924 isChecked,
14925 userTriggered
14926 } : {
14927 text,
14928 isChecked
14929 });
14930 var name = target.name;
14931 if (type === "radio" && name && isChecked) doc.querySelectorAll("input[type=\"radio\"][name=\"" + name + "\"]").forEach(function(el) {
14932 if (el !== target) {
14933 var text2 = el.value;
14934 cbWithDedup(el, userTriggeredOnInput ? {
14935 text: text2,
14936 isChecked: !isChecked,
14937 userTriggered: false
14938 } : {
14939 text: text2,
14940 isChecked: !isChecked
14941 });
14942 }
14943 });
14944 }
14945 function cbWithDedup(target, v2) {
14946 var lastInputValue = lastInputValueMap.get(target);
14947 if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) {
14948 lastInputValueMap.set(target, v2);
14949 var id = mirror2.getId(target);
14950 callbackWrapper(inputCb)(_extends({}, v2, { id }));
14951 }
14952 }
14953 var handlers = (sampling.input === "last" ? ["change"] : ["input", "change"]).map(function(eventName) {
14954 return on(eventName, callbackWrapper(eventHandler), doc);
14955 });
14956 var currentWindow = doc.defaultView;
14957 if (!currentWindow) return function() {
14958 handlers.forEach(function(h) {
14959 return h();
14960 });
14961 };
14962 var propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value");
14963 var hookProperties = [
14964 [currentWindow.HTMLInputElement.prototype, "value"],
14965 [currentWindow.HTMLInputElement.prototype, "checked"],
14966 [currentWindow.HTMLSelectElement.prototype, "value"],
14967 [currentWindow.HTMLTextAreaElement.prototype, "value"],
14968 [currentWindow.HTMLSelectElement.prototype, "selectedIndex"],
14969 [currentWindow.HTMLOptionElement.prototype, "selected"]
14970 ];
14971 if (propertyDescriptor && propertyDescriptor.set) {
14972 var _handlers;
14973 (_handlers = handlers).push.apply(_handlers, [].concat(hookProperties.map(function(p) {
14974 return hookSetter(p[0], p[1], { set: function set() {
14975 callbackWrapper(eventHandler)({
14976 target: this,
14977 isTrusted: false
14978 });
14979 } }, false, currentWindow);
14980 })));
14981 }
14982 return callbackWrapper(function() {
14983 handlers.forEach(function(h) {
14984 return h();
14985 });
14986 });
14987 }
14988 function getNestedCSSRulePositions(rule2) {
14989 var positions = [];
14990 function recurse(childRule, pos) {
14991 if (hasNestedCSSRule("CSSGroupingRule") && _instanceof(childRule.parentRule, CSSGroupingRule) || hasNestedCSSRule("CSSMediaRule") && _instanceof(childRule.parentRule, CSSMediaRule) || hasNestedCSSRule("CSSSupportsRule") && _instanceof(childRule.parentRule, CSSSupportsRule) || hasNestedCSSRule("CSSConditionRule") && _instanceof(childRule.parentRule, CSSConditionRule)) {
14992 var index2 = Array.from(childRule.parentRule.cssRules).indexOf(childRule);
14993 pos.unshift(index2);
14994 } else if (childRule.parentStyleSheet) {
14995 var index21 = Array.from(childRule.parentStyleSheet.cssRules).indexOf(childRule);
14996 pos.unshift(index21);
14997 }
14998 return pos;
14999 }
15000 return recurse(rule2, positions);
15001 }
15002 function getIdAndStyleId(sheet, mirror2, styleMirror) {
15003 var id;
15004 var styleId;
15005 if (!sheet) return {};
15006 if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);
15007 else styleId = styleMirror.getId(sheet);
15008 return {
15009 styleId,
15010 id
15011 };
15012 }
15013 function initStyleSheetObserver(param, param1) {
15014 var styleSheetRuleCb = param.styleSheetRuleCb;
15015 var mirror2 = param.mirror;
15016 var stylesheetManager = param.stylesheetManager;
15017 var win = param1.win;
15018 if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) return function() {};
15019 var insertRule = win.CSSStyleSheet.prototype.insertRule;
15020 win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15021 var rule2 = argumentsList[0];
15022 var index2 = argumentsList[1];
15023 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
15024 var id = _getIdAndStyleId.id;
15025 var styleId = _getIdAndStyleId.styleId;
15026 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
15027 id,
15028 styleId,
15029 adds: [{
15030 rule: rule2,
15031 index: index2
15032 }]
15033 });
15034 return target.apply(thisArg, argumentsList);
15035 }) });
15036 win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2) {
15037 if (index2 === void 0) index2 = this.cssRules.length;
15038 var rule2 = selector + " { " + styleBlock + " }";
15039 return win.CSSStyleSheet.prototype.insertRule.apply(this, [rule2, index2]);
15040 };
15041 var deleteRule = win.CSSStyleSheet.prototype.deleteRule;
15042 win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15043 var index2 = argumentsList[0];
15044 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
15045 var id = _getIdAndStyleId.id;
15046 var styleId = _getIdAndStyleId.styleId;
15047 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
15048 id,
15049 styleId,
15050 removes: [{ index: index2 }]
15051 });
15052 return target.apply(thisArg, argumentsList);
15053 }) });
15054 win.CSSStyleSheet.prototype.removeRule = function(index2) {
15055 return win.CSSStyleSheet.prototype.deleteRule.apply(this, [index2]);
15056 };
15057 var replace;
15058 if (win.CSSStyleSheet.prototype.replace) {
15059 replace = win.CSSStyleSheet.prototype.replace;
15060 win.CSSStyleSheet.prototype.replace = new Proxy(replace, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15061 var text = argumentsList[0];
15062 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
15063 var id = _getIdAndStyleId.id;
15064 var styleId = _getIdAndStyleId.styleId;
15065 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
15066 id,
15067 styleId,
15068 replace: text
15069 });
15070 return target.apply(thisArg, argumentsList);
15071 }) });
15072 }
15073 var replaceSync;
15074 if (win.CSSStyleSheet.prototype.replaceSync) {
15075 replaceSync = win.CSSStyleSheet.prototype.replaceSync;
15076 win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15077 var text = argumentsList[0];
15078 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
15079 var id = _getIdAndStyleId.id;
15080 var styleId = _getIdAndStyleId.styleId;
15081 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
15082 id,
15083 styleId,
15084 replaceSync: text
15085 });
15086 return target.apply(thisArg, argumentsList);
15087 }) });
15088 }
15089 var supportedNestedCSSRuleTypes = {};
15090 if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
15091 else {
15092 if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
15093 if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
15094 if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
15095 }
15096 var unmodifiedFunctions = {};
15097 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
15098 var typeKey = param[0];
15099 var type = param[1];
15100 unmodifiedFunctions[typeKey] = {
15101 insertRule: type.prototype.insertRule,
15102 deleteRule: type.prototype.deleteRule
15103 };
15104 type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15105 var rule2 = argumentsList[0];
15106 var index2 = argumentsList[1];
15107 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
15108 var id = _getIdAndStyleId.id;
15109 var styleId = _getIdAndStyleId.styleId;
15110 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
15111 id,
15112 styleId,
15113 adds: [{
15114 rule: rule2,
15115 index: [].concat(getNestedCSSRulePositions(thisArg), [index2 || 0])
15116 }]
15117 });
15118 return target.apply(thisArg, argumentsList);
15119 }) });
15120 type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15121 var index2 = argumentsList[0];
15122 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
15123 var id = _getIdAndStyleId.id;
15124 var styleId = _getIdAndStyleId.styleId;
15125 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
15126 id,
15127 styleId,
15128 removes: [{ index: [].concat(getNestedCSSRulePositions(thisArg), [index2]) }]
15129 });
15130 return target.apply(thisArg, argumentsList);
15131 }) });
15132 });
15133 return callbackWrapper(function() {
15134 win.CSSStyleSheet.prototype.insertRule = insertRule;
15135 win.CSSStyleSheet.prototype.deleteRule = deleteRule;
15136 replace && (win.CSSStyleSheet.prototype.replace = replace);
15137 replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
15138 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
15139 var typeKey = param[0];
15140 var type = param[1];
15141 type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
15142 type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
15143 });
15144 });
15145 }
15146 function initAdoptedStyleSheetObserver(param, host2) {
15147 var mirror2 = param.mirror;
15148 var stylesheetManager = param.stylesheetManager;
15149 var _a2;
15150 var _b;
15151 var _c;
15152 var hostId = null;
15153 if (host2.nodeName === "#document") hostId = mirror2.getId(host2);
15154 else hostId = mirror2.getId(index.host(host2));
15155 var patchTarget = host2.nodeName === "#document" ? (_a2 = host2.defaultView) == null ? void 0 : _a2.Document : (_c = (_b = host2.ownerDocument) == null ? void 0 : _b.defaultView) == null ? void 0 : _c.ShadowRoot;
15156 var originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(patchTarget == null ? void 0 : patchTarget.prototype, "adoptedStyleSheets") : void 0;
15157 if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor) return function() {};
15158 Object.defineProperty(host2, "adoptedStyleSheets", {
15159 configurable: originalPropertyDescriptor.configurable,
15160 enumerable: originalPropertyDescriptor.enumerable,
15161 get: function get() {
15162 var _a3;
15163 return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);
15164 },
15165 set: function set(sheets) {
15166 var _a3;
15167 var result2 = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);
15168 if (hostId !== null && hostId !== -1) try {
15169 stylesheetManager.adoptStyleSheets(sheets, hostId);
15170 } catch (e2) {}
15171 return result2;
15172 }
15173 });
15174 return callbackWrapper(function() {
15175 Object.defineProperty(host2, "adoptedStyleSheets", {
15176 configurable: originalPropertyDescriptor.configurable,
15177 enumerable: originalPropertyDescriptor.enumerable,
15178 get: originalPropertyDescriptor.get,
15179 set: originalPropertyDescriptor.set
15180 });
15181 });
15182 }
15183 function initStyleDeclarationObserver(param, param1) {
15184 var styleDeclarationCb = param.styleDeclarationCb;
15185 var mirror2 = param.mirror;
15186 var ignoreCSSAttributes = param.ignoreCSSAttributes;
15187 var stylesheetManager = param.stylesheetManager;
15188 var win = param1.win;
15189 var setProperty = win.CSSStyleDeclaration.prototype.setProperty;
15190 win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15191 var _a2;
15192 var property = argumentsList[0];
15193 var value = argumentsList[1];
15194 var priority = argumentsList[2];
15195 if (ignoreCSSAttributes.has(property)) return setProperty.apply(thisArg, [
15196 property,
15197 value,
15198 priority
15199 ]);
15200 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
15201 var id = _getIdAndStyleId.id;
15202 var styleId = _getIdAndStyleId.styleId;
15203 if (id && id !== -1 || styleId && styleId !== -1) styleDeclarationCb({
15204 id,
15205 styleId,
15206 set: {
15207 property,
15208 value,
15209 priority
15210 },
15211 index: getNestedCSSRulePositions(thisArg.parentRule)
15212 });
15213 return target.apply(thisArg, argumentsList);
15214 }) });
15215 var removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
15216 win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15217 var _a2;
15218 var property = argumentsList[0];
15219 if (ignoreCSSAttributes.has(property)) return removeProperty.apply(thisArg, [property]);
15220 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
15221 var id = _getIdAndStyleId.id;
15222 var styleId = _getIdAndStyleId.styleId;
15223 if (id && id !== -1 || styleId && styleId !== -1) styleDeclarationCb({
15224 id,
15225 styleId,
15226 remove: { property },
15227 index: getNestedCSSRulePositions(thisArg.parentRule)
15228 });
15229 return target.apply(thisArg, argumentsList);
15230 }) });
15231 return callbackWrapper(function() {
15232 win.CSSStyleDeclaration.prototype.setProperty = setProperty;
15233 win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
15234 });
15235 }
15236 function initMediaInteractionObserver(param) {
15237 var mediaInteractionCb = param.mediaInteractionCb;
15238 var blockClass = param.blockClass;
15239 var blockSelector = param.blockSelector;
15240 var mirror2 = param.mirror;
15241 var sampling = param.sampling;
15242 var doc = param.doc;
15243 var handler = callbackWrapper(function(type) {
15244 return throttle(callbackWrapper(function(event) {
15245 var target = getEventTarget(event);
15246 if (!target || isBlocked(target, blockClass, blockSelector, true)) return;
15247 var currentTime = target.currentTime;
15248 var volume = target.volume;
15249 var muted = target.muted;
15250 var playbackRate = target.playbackRate;
15251 var loop = target.loop;
15252 mediaInteractionCb({
15253 type,
15254 id: mirror2.getId(target),
15255 currentTime,
15256 volume,
15257 muted,
15258 playbackRate,
15259 loop
15260 });
15261 }), sampling.media || 500);
15262 });
15263 var handlers = [
15264 on("play", handler(MediaInteractions.Play), doc),
15265 on("pause", handler(MediaInteractions.Pause), doc),
15266 on("seeked", handler(MediaInteractions.Seeked), doc),
15267 on("volumechange", handler(MediaInteractions.VolumeChange), doc),
15268 on("ratechange", handler(MediaInteractions.RateChange), doc)
15269 ];
15270 return callbackWrapper(function() {
15271 handlers.forEach(function(h) {
15272 return h();
15273 });
15274 });
15275 }
15276 function initFontObserver(param) {
15277 var fontCb = param.fontCb;
15278 var doc = param.doc;
15279 var win = doc.defaultView;
15280 if (!win) return function() {};
15281 var handlers = [];
15282 var fontMap = /* @__PURE__ */ new WeakMap();
15283 var originalFontFace = win.FontFace;
15284 win.FontFace = function FontFace2(family, source, descriptors) {
15285 var fontFace = new originalFontFace(family, source, descriptors);
15286 fontMap.set(fontFace, {
15287 family,
15288 buffer: typeof source !== "string",
15289 descriptors,
15290 fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source)))
15291 });
15292 return fontFace;
15293 };
15294 var restoreHandler = patch(doc.fonts, "add", function(original) {
15295 return function(fontFace) {
15296 setTimeout(callbackWrapper(function() {
15297 var p = fontMap.get(fontFace);
15298 if (p) {
15299 fontCb(p);
15300 fontMap.delete(fontFace);
15301 }
15302 }), 0);
15303 return original.apply(this, [fontFace]);
15304 };
15305 });
15306 handlers.push(function() {
15307 win.FontFace = originalFontFace;
15308 });
15309 handlers.push(restoreHandler);
15310 return callbackWrapper(function() {
15311 handlers.forEach(function(h) {
15312 return h();
15313 });
15314 });
15315 }
15316 function initSelectionObserver(param) {
15317 var doc = param.doc;
15318 var mirror2 = param.mirror;
15319 var blockClass = param.blockClass;
15320 var blockSelector = param.blockSelector;
15321 var selectionCb = param.selectionCb;
15322 var collapsed = true;
15323 var updateSelection = callbackWrapper(function() {
15324 var selection = doc.getSelection();
15325 if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;
15326 collapsed = selection.isCollapsed || false;
15327 var ranges = [];
15328 var count = selection.rangeCount || 0;
15329 for (var i2 = 0; i2 < count; i2++) {
15330 var range = selection.getRangeAt(i2);
15331 var startContainer = range.startContainer;
15332 var startOffset = range.startOffset;
15333 var endContainer = range.endContainer;
15334 var endOffset = range.endOffset;
15335 if (isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true)) continue;
15336 ranges.push({
15337 start: mirror2.getId(startContainer),
15338 startOffset,
15339 end: mirror2.getId(endContainer),
15340 endOffset
15341 });
15342 }
15343 selectionCb({ ranges });
15344 });
15345 updateSelection();
15346 return on("selectionchange", updateSelection);
15347 }
15348 function initCustomElementObserver(param) {
15349 var doc = param.doc;
15350 var customElementCb = param.customElementCb;
15351 var win = doc.defaultView;
15352 if (!win || !win.customElements) return function() {};
15353 return patch(win.customElements, "define", function(original) {
15354 return function(name, constructor, options) {
15355 try {
15356 customElementCb({ define: { name } });
15357 } catch (e2) {
15358 console.warn("Custom element callback failed for " + name);
15359 }
15360 return original.apply(this, [
15361 name,
15362 constructor,
15363 options
15364 ]);
15365 };
15366 });
15367 }
15368 function mergeHooks(o2, hooks) {
15369 var mutationCb = o2.mutationCb;
15370 var mousemoveCb = o2.mousemoveCb;
15371 var mouseInteractionCb = o2.mouseInteractionCb;
15372 var scrollCb = o2.scrollCb;
15373 var viewportResizeCb = o2.viewportResizeCb;
15374 var inputCb = o2.inputCb;
15375 var mediaInteractionCb = o2.mediaInteractionCb;
15376 var styleSheetRuleCb = o2.styleSheetRuleCb;
15377 var styleDeclarationCb = o2.styleDeclarationCb;
15378 var canvasMutationCb = o2.canvasMutationCb;
15379 var fontCb = o2.fontCb;
15380 var selectionCb = o2.selectionCb;
15381 var customElementCb = o2.customElementCb;
15382 o2.mutationCb = function() {
15383 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15384 if (hooks.mutation) {
15385 var _hooks;
15386 (_hooks = hooks).mutation.apply(_hooks, [].concat(p));
15387 }
15388 mutationCb.apply(void 0, [].concat(p));
15389 };
15390 o2.mousemoveCb = function() {
15391 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15392 if (hooks.mousemove) {
15393 var _hooks;
15394 (_hooks = hooks).mousemove.apply(_hooks, [].concat(p));
15395 }
15396 mousemoveCb.apply(void 0, [].concat(p));
15397 };
15398 o2.mouseInteractionCb = function() {
15399 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15400 if (hooks.mouseInteraction) {
15401 var _hooks;
15402 (_hooks = hooks).mouseInteraction.apply(_hooks, [].concat(p));
15403 }
15404 mouseInteractionCb.apply(void 0, [].concat(p));
15405 };
15406 o2.scrollCb = function() {
15407 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15408 if (hooks.scroll) {
15409 var _hooks;
15410 (_hooks = hooks).scroll.apply(_hooks, [].concat(p));
15411 }
15412 scrollCb.apply(void 0, [].concat(p));
15413 };
15414 o2.viewportResizeCb = function() {
15415 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15416 if (hooks.viewportResize) {
15417 var _hooks;
15418 (_hooks = hooks).viewportResize.apply(_hooks, [].concat(p));
15419 }
15420 viewportResizeCb.apply(void 0, [].concat(p));
15421 };
15422 o2.inputCb = function() {
15423 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15424 if (hooks.input) {
15425 var _hooks;
15426 (_hooks = hooks).input.apply(_hooks, [].concat(p));
15427 }
15428 inputCb.apply(void 0, [].concat(p));
15429 };
15430 o2.mediaInteractionCb = function() {
15431 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15432 if (hooks.mediaInteaction) {
15433 var _hooks;
15434 (_hooks = hooks).mediaInteaction.apply(_hooks, [].concat(p));
15435 }
15436 mediaInteractionCb.apply(void 0, [].concat(p));
15437 };
15438 o2.styleSheetRuleCb = function() {
15439 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15440 if (hooks.styleSheetRule) {
15441 var _hooks;
15442 (_hooks = hooks).styleSheetRule.apply(_hooks, [].concat(p));
15443 }
15444 styleSheetRuleCb.apply(void 0, [].concat(p));
15445 };
15446 o2.styleDeclarationCb = function() {
15447 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15448 if (hooks.styleDeclaration) {
15449 var _hooks;
15450 (_hooks = hooks).styleDeclaration.apply(_hooks, [].concat(p));
15451 }
15452 styleDeclarationCb.apply(void 0, [].concat(p));
15453 };
15454 o2.canvasMutationCb = function() {
15455 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15456 if (hooks.canvasMutation) {
15457 var _hooks;
15458 (_hooks = hooks).canvasMutation.apply(_hooks, [].concat(p));
15459 }
15460 canvasMutationCb.apply(void 0, [].concat(p));
15461 };
15462 o2.fontCb = function() {
15463 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15464 if (hooks.font) {
15465 var _hooks;
15466 (_hooks = hooks).font.apply(_hooks, [].concat(p));
15467 }
15468 fontCb.apply(void 0, [].concat(p));
15469 };
15470 o2.selectionCb = function() {
15471 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15472 if (hooks.selection) {
15473 var _hooks;
15474 (_hooks = hooks).selection.apply(_hooks, [].concat(p));
15475 }
15476 selectionCb.apply(void 0, [].concat(p));
15477 };
15478 o2.customElementCb = function() {
15479 for (var _len = arguments.length, c2 = new Array(_len), _key = 0; _key < _len; _key++) c2[_key] = arguments[_key];
15480 if (hooks.customElement) {
15481 var _hooks;
15482 (_hooks = hooks).customElement.apply(_hooks, [].concat(c2));
15483 }
15484 customElementCb.apply(void 0, [].concat(c2));
15485 };
15486 }
15487 function initObservers(o2, hooks) {
15488 if (hooks === void 0) hooks = {};
15489 var currentWindow = o2.doc.defaultView;
15490 if (!currentWindow) return function() {};
15491 mergeHooks(o2, hooks);
15492 var mutationObserver;
15493 if (o2.recordDOM) mutationObserver = initMutationObserver(o2, o2.doc);
15494 var mousemoveHandler = initMoveObserver(o2);
15495 var mouseInteractionHandler = initMouseInteractionObserver(o2);
15496 var scrollHandler = initScrollObserver(o2);
15497 var viewportResizeHandler = initViewportResizeObserver(o2, { win: currentWindow });
15498 var inputHandler = initInputObserver(o2);
15499 var mediaInteractionHandler = initMediaInteractionObserver(o2);
15500 var styleSheetObserver = function() {};
15501 var adoptedStyleSheetObserver = function() {};
15502 var styleDeclarationObserver = function() {};
15503 var fontObserver = function() {};
15504 if (o2.recordDOM) {
15505 styleSheetObserver = initStyleSheetObserver(o2, { win: currentWindow });
15506 adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc);
15507 styleDeclarationObserver = initStyleDeclarationObserver(o2, { win: currentWindow });
15508 if (o2.collectFonts) fontObserver = initFontObserver(o2);
15509 }
15510 var selectionObserver = initSelectionObserver(o2);
15511 var customElementObserver = initCustomElementObserver(o2);
15512 var pluginHandlers = [];
15513 for (var _iterator = _create_for_of_iterator_helper_loose(o2.plugins), _step; !(_step = _iterator()).done;) {
15514 var plugin3 = _step.value;
15515 pluginHandlers.push(plugin3.observer(plugin3.callback, currentWindow, plugin3.options));
15516 }
15517 return callbackWrapper(function() {
15518 mutationBuffers.forEach(function(b) {
15519 return b.reset();
15520 });
15521 mutationObserver == null || mutationObserver.disconnect();
15522 mousemoveHandler();
15523 mouseInteractionHandler();
15524 scrollHandler();
15525 viewportResizeHandler();
15526 inputHandler();
15527 mediaInteractionHandler();
15528 styleSheetObserver();
15529 adoptedStyleSheetObserver();
15530 styleDeclarationObserver();
15531 fontObserver();
15532 selectionObserver();
15533 customElementObserver();
15534 pluginHandlers.forEach(function(h) {
15535 return h();
15536 });
15537 });
15538 }
15539 function hasNestedCSSRule(prop) {
15540 return typeof window[prop] !== "undefined";
15541 }
15542 function canMonkeyPatchNestedCSSRule(prop) {
15543 return Boolean(typeof window[prop] !== "undefined" && window[prop].prototype && "insertRule" in window[prop].prototype && "deleteRule" in window[prop].prototype);
15544 }
15545 var CrossOriginIframeMirror = /*#__PURE__*/ function() {
15546 function CrossOriginIframeMirror(generateIdFn) {
15547 __publicField(this, "iframeIdToRemoteIdMap", /* @__PURE__ */ new WeakMap());
15548 __publicField(this, "iframeRemoteIdToIdMap", /* @__PURE__ */ new WeakMap());
15549 this.generateIdFn = generateIdFn;
15550 }
15551 var _proto = CrossOriginIframeMirror.prototype;
15552 _proto.getId = function getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
15553 var idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
15554 var remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
15555 var id = idToRemoteIdMap.get(remoteId);
15556 if (!id) {
15557 id = this.generateIdFn();
15558 idToRemoteIdMap.set(remoteId, id);
15559 remoteIdToIdMap.set(id, remoteId);
15560 }
15561 return id;
15562 };
15563 _proto.getIds = function getIds(iframe, remoteId) {
15564 var _this = this;
15565 var idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
15566 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
15567 return remoteId.map(function(id) {
15568 return _this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap);
15569 });
15570 };
15571 _proto.getRemoteId = function getRemoteId(iframe, id, map) {
15572 var remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
15573 if (typeof id !== "number") return id;
15574 var remoteId = remoteIdToIdMap.get(id);
15575 if (!remoteId) return -1;
15576 return remoteId;
15577 };
15578 _proto.getRemoteIds = function getRemoteIds(iframe, ids) {
15579 var _this = this;
15580 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
15581 return ids.map(function(id) {
15582 return _this.getRemoteId(iframe, id, remoteIdToIdMap);
15583 });
15584 };
15585 _proto.reset = function reset(iframe) {
15586 if (!iframe) {
15587 this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
15588 this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
15589 return;
15590 }
15591 this.iframeIdToRemoteIdMap.delete(iframe);
15592 this.iframeRemoteIdToIdMap.delete(iframe);
15593 };
15594 _proto.getIdToRemoteIdMap = function getIdToRemoteIdMap(iframe) {
15595 var idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
15596 if (!idToRemoteIdMap) {
15597 idToRemoteIdMap = /* @__PURE__ */ new Map();
15598 this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
15599 }
15600 return idToRemoteIdMap;
15601 };
15602 _proto.getRemoteIdToIdMap = function getRemoteIdToIdMap(iframe) {
15603 var remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
15604 if (!remoteIdToIdMap) {
15605 remoteIdToIdMap = /* @__PURE__ */ new Map();
15606 this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
15607 }
15608 return remoteIdToIdMap;
15609 };
15610 return CrossOriginIframeMirror;
15611 }();
15612 var IframeManager = /*#__PURE__*/ function() {
15613 function IframeManager(options) {
15614 __publicField(this, "iframes", /* @__PURE__ */ new WeakMap());
15615 __publicField(this, "crossOriginIframeMap", /* @__PURE__ */ new WeakMap());
15616 __publicField(this, "crossOriginIframeMirror", new CrossOriginIframeMirror(genId));
15617 __publicField(this, "crossOriginIframeStyleMirror");
15618 __publicField(this, "crossOriginIframeRootIdMap", /* @__PURE__ */ new WeakMap());
15619 __publicField(this, "mirror");
15620 __publicField(this, "mutationCb");
15621 __publicField(this, "wrappedEmit");
15622 __publicField(this, "loadListener");
15623 __publicField(this, "stylesheetManager");
15624 __publicField(this, "recordCrossOriginIframes");
15625 this.mutationCb = options.mutationCb;
15626 this.wrappedEmit = options.wrappedEmit;
15627 this.stylesheetManager = options.stylesheetManager;
15628 this.recordCrossOriginIframes = options.recordCrossOriginIframes;
15629 this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
15630 this.mirror = options.mirror;
15631 if (this.recordCrossOriginIframes) window.addEventListener("message", this.handleMessage.bind(this));
15632 }
15633 var _proto = IframeManager.prototype;
15634 _proto.addIframe = function addIframe(iframeEl) {
15635 this.iframes.set(iframeEl, true);
15636 if (iframeEl.contentWindow) this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
15637 };
15638 _proto.addLoadListener = function addLoadListener(cb) {
15639 this.loadListener = cb;
15640 };
15641 _proto.attachIframe = function attachIframe(iframeEl, childSn) {
15642 var _a2;
15643 var _b;
15644 this.mutationCb({
15645 adds: [{
15646 parentId: this.mirror.getId(iframeEl),
15647 nextId: null,
15648 node: childSn
15649 }],
15650 removes: [],
15651 texts: [],
15652 attributes: [],
15653 isAttachIframe: true
15654 });
15655 if (this.recordCrossOriginIframes) (_a2 = iframeEl.contentWindow) == null || _a2.addEventListener("message", this.handleMessage.bind(this));
15656 (_b = this.loadListener) == null || _b.call(this, iframeEl);
15657 if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0) this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
15658 };
15659 _proto.handleMessage = function handleMessage(message) {
15660 var crossOriginMessageEvent = message;
15661 if (crossOriginMessageEvent.data.type !== "rrweb" || crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin) return;
15662 if (!message.source) return;
15663 var iframeEl = this.crossOriginIframeMap.get(message.source);
15664 if (!iframeEl) return;
15665 var transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);
15666 if (transformedEvent) this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);
15667 };
15668 _proto.transformCrossOriginEvent = function transformCrossOriginEvent(iframeEl, e2) {
15669 var _this = this;
15670 var _a2;
15671 switch (e2.type) {
15672 case EventType.FullSnapshot:
15673 this.crossOriginIframeMirror.reset(iframeEl);
15674 this.crossOriginIframeStyleMirror.reset(iframeEl);
15675 this.replaceIdOnNode(e2.data.node, iframeEl);
15676 var rootId = e2.data.node.id;
15677 this.crossOriginIframeRootIdMap.set(iframeEl, rootId);
15678 this.patchRootIdOnNode(e2.data.node, rootId);
15679 return {
15680 timestamp: e2.timestamp,
15681 type: EventType.IncrementalSnapshot,
15682 data: {
15683 source: IncrementalSource.Mutation,
15684 adds: [{
15685 parentId: this.mirror.getId(iframeEl),
15686 nextId: null,
15687 node: e2.data.node
15688 }],
15689 removes: [],
15690 texts: [],
15691 attributes: [],
15692 isAttachIframe: true
15693 }
15694 };
15695 case EventType.Meta:
15696 case EventType.Load:
15697 case EventType.DomContentLoaded: return false;
15698 case EventType.Plugin: return e2;
15699 case EventType.Custom:
15700 this.replaceIds(e2.data.payload, iframeEl, [
15701 "id",
15702 "parentId",
15703 "previousId",
15704 "nextId"
15705 ]);
15706 return e2;
15707 case EventType.IncrementalSnapshot: switch (e2.data.source) {
15708 case IncrementalSource.Mutation:
15709 e2.data.adds.forEach(function(n2) {
15710 _this.replaceIds(n2, iframeEl, [
15711 "parentId",
15712 "nextId",
15713 "previousId"
15714 ]);
15715 _this.replaceIdOnNode(n2.node, iframeEl);
15716 var rootId = _this.crossOriginIframeRootIdMap.get(iframeEl);
15717 rootId && _this.patchRootIdOnNode(n2.node, rootId);
15718 });
15719 e2.data.removes.forEach(function(n2) {
15720 _this.replaceIds(n2, iframeEl, ["parentId", "id"]);
15721 });
15722 e2.data.attributes.forEach(function(n2) {
15723 _this.replaceIds(n2, iframeEl, ["id"]);
15724 });
15725 e2.data.texts.forEach(function(n2) {
15726 _this.replaceIds(n2, iframeEl, ["id"]);
15727 });
15728 return e2;
15729 case IncrementalSource.Drag:
15730 case IncrementalSource.TouchMove:
15731 case IncrementalSource.MouseMove:
15732 e2.data.positions.forEach(function(p) {
15733 _this.replaceIds(p, iframeEl, ["id"]);
15734 });
15735 return e2;
15736 case IncrementalSource.ViewportResize: return false;
15737 case IncrementalSource.MediaInteraction:
15738 case IncrementalSource.MouseInteraction:
15739 case IncrementalSource.Scroll:
15740 case IncrementalSource.CanvasMutation:
15741 case IncrementalSource.Input:
15742 this.replaceIds(e2.data, iframeEl, ["id"]);
15743 return e2;
15744 case IncrementalSource.StyleSheetRule:
15745 case IncrementalSource.StyleDeclaration:
15746 this.replaceIds(e2.data, iframeEl, ["id"]);
15747 this.replaceStyleIds(e2.data, iframeEl, ["styleId"]);
15748 return e2;
15749 case IncrementalSource.Font: return e2;
15750 case IncrementalSource.Selection:
15751 e2.data.ranges.forEach(function(range) {
15752 _this.replaceIds(range, iframeEl, ["start", "end"]);
15753 });
15754 return e2;
15755 case IncrementalSource.AdoptedStyleSheet:
15756 this.replaceIds(e2.data, iframeEl, ["id"]);
15757 this.replaceStyleIds(e2.data, iframeEl, ["styleIds"]);
15758 (_a2 = e2.data.styles) == null || _a2.forEach(function(style) {
15759 _this.replaceStyleIds(style, iframeEl, ["styleId"]);
15760 });
15761 return e2;
15762 }
15763 }
15764 return false;
15765 };
15766 _proto.replace = function replace(iframeMirror, obj, iframeEl, keys) {
15767 for (var _iterator = _create_for_of_iterator_helper_loose(keys), _step; !(_step = _iterator()).done;) {
15768 var key = _step.value;
15769 if (!Array.isArray(obj[key]) && typeof obj[key] !== "number") continue;
15770 if (Array.isArray(obj[key])) obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
15771 else obj[key] = iframeMirror.getId(iframeEl, obj[key]);
15772 }
15773 return obj;
15774 };
15775 _proto.replaceIds = function replaceIds(obj, iframeEl, keys) {
15776 return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
15777 };
15778 _proto.replaceStyleIds = function replaceStyleIds(obj, iframeEl, keys) {
15779 return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
15780 };
15781 _proto.replaceIdOnNode = function replaceIdOnNode(node2, iframeEl) {
15782 var _this = this;
15783 this.replaceIds(node2, iframeEl, ["id", "rootId"]);
15784 if ("childNodes" in node2) node2.childNodes.forEach(function(child) {
15785 _this.replaceIdOnNode(child, iframeEl);
15786 });
15787 };
15788 _proto.patchRootIdOnNode = function patchRootIdOnNode(node2, rootId) {
15789 var _this = this;
15790 if (node2.type !== NodeType.Document && !node2.rootId) node2.rootId = rootId;
15791 if ("childNodes" in node2) node2.childNodes.forEach(function(child) {
15792 _this.patchRootIdOnNode(child, rootId);
15793 });
15794 };
15795 return IframeManager;
15796 }();
15797 var ShadowDomManager = /*#__PURE__*/ function() {
15798 function ShadowDomManager(options) {
15799 __publicField(this, "shadowDoms", /* @__PURE__ */ new WeakSet());
15800 __publicField(this, "mutationCb");
15801 __publicField(this, "scrollCb");
15802 __publicField(this, "bypassOptions");
15803 __publicField(this, "mirror");
15804 __publicField(this, "restoreHandlers", []);
15805 this.mutationCb = options.mutationCb;
15806 this.scrollCb = options.scrollCb;
15807 this.bypassOptions = options.bypassOptions;
15808 this.mirror = options.mirror;
15809 this.init();
15810 }
15811 var _proto = ShadowDomManager.prototype;
15812 _proto.init = function init() {
15813 this.reset();
15814 this.patchAttachShadow(Element, document);
15815 };
15816 _proto.addShadowRoot = function addShadowRoot(shadowRoot2, doc) {
15817 var _this = this;
15818 if (!isNativeShadowDom(shadowRoot2)) return;
15819 if (this.shadowDoms.has(shadowRoot2)) return;
15820 this.shadowDoms.add(shadowRoot2);
15821 var observer = initMutationObserver(_extends({}, this.bypassOptions, {
15822 doc,
15823 mutationCb: this.mutationCb,
15824 mirror: this.mirror,
15825 shadowDomManager: this
15826 }), shadowRoot2);
15827 this.restoreHandlers.push(function() {
15828 return observer.disconnect();
15829 });
15830 this.restoreHandlers.push(initScrollObserver(_extends({}, this.bypassOptions, {
15831 scrollCb: this.scrollCb,
15832 doc: shadowRoot2,
15833 mirror: this.mirror
15834 })));
15835 setTimeout(function() {
15836 if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0) _this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot2.adoptedStyleSheets, _this.mirror.getId(index.host(shadowRoot2)));
15837 _this.restoreHandlers.push(initAdoptedStyleSheetObserver({
15838 mirror: _this.mirror,
15839 stylesheetManager: _this.bypassOptions.stylesheetManager
15840 }, shadowRoot2));
15841 }, 0);
15842 };
15843 /**
15844 * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.
15845 */ _proto.observeAttachShadow = function observeAttachShadow(iframeElement) {
15846 if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;
15847 this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);
15848 };
15849 /**
15850 * Patch 'attachShadow' to observe newly added shadow doms.
15851 */ _proto.patchAttachShadow = function patchAttachShadow(element, doc) {
15852 var manager = this;
15853 this.restoreHandlers.push(patch(element.prototype, "attachShadow", function(original) {
15854 return function(option) {
15855 var sRoot = original.call(this, option);
15856 var shadowRootEl = index.shadowRoot(this);
15857 if (shadowRootEl && inDom(this)) manager.addShadowRoot(shadowRootEl, doc);
15858 return sRoot;
15859 };
15860 }));
15861 };
15862 _proto.reset = function reset() {
15863 this.restoreHandlers.forEach(function(handler) {
15864 try {
15865 handler();
15866 } catch (e2) {}
15867 });
15868 this.restoreHandlers = [];
15869 this.shadowDoms = /* @__PURE__ */ new WeakSet();
15870 };
15871 return ShadowDomManager;
15872 }();
15873 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
15874 var lookup = typeof Uint8Array === "undefined" ? [] : /* @__PURE__ */ new Uint8Array(256);
15875 for (var i$1 = 0; i$1 < chars.length; i$1++) lookup[chars.charCodeAt(i$1)] = i$1;
15876 var encode = function encode(arraybuffer) {
15877 var bytes = new Uint8Array(arraybuffer);
15878 var i2;
15879 var len = bytes.length;
15880 var base64 = "";
15881 for (i2 = 0; i2 < len; i2 += 3) {
15882 base64 += chars[bytes[i2] >> 2];
15883 base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
15884 base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
15885 base64 += chars[bytes[i2 + 2] & 63];
15886 }
15887 if (len % 3 === 2) base64 = base64.substring(0, base64.length - 1) + "=";
15888 else if (len % 3 === 1) base64 = base64.substring(0, base64.length - 2) + "==";
15889 return base64;
15890 };
15891 var canvasVarMap = /* @__PURE__ */ new Map();
15892 function variableListFor$1(ctx, ctor) {
15893 var contextMap = canvasVarMap.get(ctx);
15894 if (!contextMap) {
15895 contextMap = /* @__PURE__ */ new Map();
15896 canvasVarMap.set(ctx, contextMap);
15897 }
15898 if (!contextMap.has(ctor)) contextMap.set(ctor, []);
15899 return contextMap.get(ctor);
15900 }
15901 var saveWebGLVar = function(value, win, ctx) {
15902 if (!value || !(isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object")) return;
15903 var name = value.constructor.name;
15904 var list2 = variableListFor$1(ctx, name);
15905 var index2 = list2.indexOf(value);
15906 if (index2 === -1) {
15907 index2 = list2.length;
15908 list2.push(value);
15909 }
15910 return index2;
15911 };
15912 function serializeArg(value, win, ctx) {
15913 if (_instanceof(value, Array)) return value.map(function(arg) {
15914 return serializeArg(arg, win, ctx);
15915 });
15916 else if (value === null) return value;
15917 else if (_instanceof(value, Float32Array) || _instanceof(value, Float64Array) || _instanceof(value, Int32Array) || _instanceof(value, Uint32Array) || _instanceof(value, Uint8Array) || _instanceof(value, Uint16Array) || _instanceof(value, Int16Array) || _instanceof(value, Int8Array) || _instanceof(value, Uint8ClampedArray)) return {
15918 rr_type: value.constructor.name,
15919 args: [Object.values(value)]
15920 };
15921 else if (_instanceof(value, ArrayBuffer)) return {
15922 rr_type: value.constructor.name,
15923 base64: encode(value)
15924 };
15925 else if (_instanceof(value, DataView)) return {
15926 rr_type: value.constructor.name,
15927 args: [
15928 serializeArg(value.buffer, win, ctx),
15929 value.byteOffset,
15930 value.byteLength
15931 ]
15932 };
15933 else if (_instanceof(value, HTMLImageElement)) return {
15934 rr_type: value.constructor.name,
15935 src: value.src
15936 };
15937 else if (_instanceof(value, HTMLCanvasElement)) return {
15938 rr_type: "HTMLImageElement",
15939 src: value.toDataURL()
15940 };
15941 else if (_instanceof(value, ImageData)) return {
15942 rr_type: value.constructor.name,
15943 args: [
15944 serializeArg(value.data, win, ctx),
15945 value.width,
15946 value.height
15947 ]
15948 };
15949 else if (isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") return {
15950 rr_type: value.constructor.name,
15951 index: saveWebGLVar(value, win, ctx)
15952 };
15953 return value;
15954 }
15955 var serializeArgs = function(args, win, ctx) {
15956 return args.map(function(arg) {
15957 return serializeArg(arg, win, ctx);
15958 });
15959 };
15960 var isInstanceOfWebGLObject = function(value, win) {
15961 var supportedWebGLConstructorNames = [
15962 "WebGLActiveInfo",
15963 "WebGLBuffer",
15964 "WebGLFramebuffer",
15965 "WebGLProgram",
15966 "WebGLRenderbuffer",
15967 "WebGLShader",
15968 "WebGLShaderPrecisionFormat",
15969 "WebGLTexture",
15970 "WebGLUniformLocation",
15971 "WebGLVertexArrayObject",
15972 "WebGLVertexArrayObjectOES"
15973 ].filter(function(name) {
15974 return typeof win[name] === "function";
15975 });
15976 return Boolean(supportedWebGLConstructorNames.find(function(name) {
15977 return _instanceof(value, win[name]);
15978 }));
15979 };
15980 function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
15981 var _loop = function() {
15982 var prop = _step.value;
15983 try {
15984 if (typeof win.CanvasRenderingContext2D.prototype[prop] !== "function") return "continue";
15985 var restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function(original) {
15986 return function() {
15987 var _this = this;
15988 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
15989 if (!isBlocked(this.canvas, blockClass, blockSelector, true)) setTimeout(function() {
15990 var recordArgs = serializeArgs(args, win, _this);
15991 cb(_this.canvas, {
15992 type: CanvasContext["2D"],
15993 property: prop,
15994 args: recordArgs
15995 });
15996 }, 0);
15997 return original.apply(this, args);
15998 };
15999 });
16000 handlers.push(restoreHandler);
16001 } catch (e) {
16002 var hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, { set: function set(v2) {
16003 cb(this.canvas, {
16004 type: CanvasContext["2D"],
16005 property: prop,
16006 args: [v2],
16007 setter: true
16008 });
16009 } });
16010 handlers.push(hookHandler);
16011 }
16012 };
16013 var handlers = [];
16014 for (var _iterator = _create_for_of_iterator_helper_loose(Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype)), _step; !(_step = _iterator()).done;) _loop();
16015 return function() {
16016 handlers.forEach(function(h) {
16017 return h();
16018 });
16019 };
16020 }
16021 function getNormalizedContextName(contextType) {
16022 return contextType === "experimental-webgl" ? "webgl" : contextType;
16023 }
16024 function initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {
16025 var handlers = [];
16026 try {
16027 var restoreHandler = patch(win.HTMLCanvasElement.prototype, "getContext", function(original) {
16028 return function(contextType) {
16029 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) args[_key - 1] = arguments[_key];
16030 if (!isBlocked(this, blockClass, blockSelector, true)) {
16031 var ctxName = getNormalizedContextName(contextType);
16032 if (!("__context" in this)) this.__context = ctxName;
16033 if (setPreserveDrawingBufferToTrue && ["webgl", "webgl2"].includes(ctxName)) if (args[0] && _type_of(args[0]) === "object") {
16034 var contextAttributes = args[0];
16035 if (!contextAttributes.preserveDrawingBuffer) contextAttributes.preserveDrawingBuffer = true;
16036 } else args.splice(0, 1, { preserveDrawingBuffer: true });
16037 }
16038 return original.apply(this, [].concat([contextType], args));
16039 };
16040 });
16041 handlers.push(restoreHandler);
16042 } catch (e) {
16043 console.error("failed to patch HTMLCanvasElement.prototype.getContext");
16044 }
16045 return function() {
16046 handlers.forEach(function(h) {
16047 return h();
16048 });
16049 };
16050 }
16051 function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win) {
16052 var _loop = function() {
16053 var prop = _step.value;
16054 if ([
16055 "isContextLost",
16056 "canvas",
16057 "drawingBufferWidth",
16058 "drawingBufferHeight"
16059 ].includes(prop)) return "continue";
16060 try {
16061 if (typeof prototype[prop] !== "function") return "continue";
16062 var restoreHandler = patch(prototype, prop, function(original) {
16063 return function() {
16064 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
16065 var result2 = original.apply(this, args);
16066 saveWebGLVar(result2, win, this);
16067 if ("tagName" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {
16068 var mutation = {
16069 type,
16070 property: prop,
16071 args: serializeArgs(args, win, this)
16072 };
16073 cb(this.canvas, mutation);
16074 }
16075 return result2;
16076 };
16077 });
16078 handlers.push(restoreHandler);
16079 } catch (e) {
16080 var hookHandler = hookSetter(prototype, prop, { set: function set(v2) {
16081 cb(this.canvas, {
16082 type,
16083 property: prop,
16084 args: [v2],
16085 setter: true
16086 });
16087 } });
16088 handlers.push(hookHandler);
16089 }
16090 };
16091 var handlers = [];
16092 for (var _iterator = _create_for_of_iterator_helper_loose(Object.getOwnPropertyNames(prototype)), _step; !(_step = _iterator()).done;) _loop();
16093 return handlers;
16094 }
16095 function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector) {
16096 var _handlers;
16097 var handlers = [];
16098 (_handlers = handlers).push.apply(_handlers, [].concat(patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, win)));
16099 if (typeof win.WebGL2RenderingContext !== "undefined") {
16100 var _handlers1;
16101 (_handlers1 = handlers).push.apply(_handlers1, [].concat(patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, win)));
16102 }
16103 return function() {
16104 handlers.forEach(function(h) {
16105 return h();
16106 });
16107 };
16108 }
16109 var encodedJs = "KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=";
16110 var decodeBase64 = function(base64) {
16111 return Uint8Array.from(atob(base64), function(c2) {
16112 return c2.charCodeAt(0);
16113 });
16114 };
16115 var blob = typeof window !== "undefined" && window.Blob && new Blob([decodeBase64(encodedJs)], { type: "text/javascript;charset=utf-8" });
16116 function WorkerWrapper(options) {
16117 var objURL;
16118 try {
16119 objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
16120 if (!objURL) throw "";
16121 var worker = new Worker(objURL, { name: options == null ? void 0 : options.name });
16122 worker.addEventListener("error", function() {
16123 (window.URL || window.webkitURL).revokeObjectURL(objURL);
16124 });
16125 return worker;
16126 } catch (e2) {
16127 return new Worker("data:text/javascript;base64," + encodedJs, { name: options == null ? void 0 : options.name });
16128 } finally {
16129 objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
16130 }
16131 }
16132 var CanvasManager = /*#__PURE__*/ function() {
16133 function CanvasManager(options) {
16134 var _this = this;
16135 __publicField(this, "pendingCanvasMutations", /* @__PURE__ */ new Map());
16136 __publicField(this, "rafStamps", {
16137 latestId: 0,
16138 invokeId: null
16139 });
16140 __publicField(this, "mirror");
16141 __publicField(this, "mutationCb");
16142 __publicField(this, "resetObservers");
16143 __publicField(this, "frozen", false);
16144 __publicField(this, "locked", false);
16145 __publicField(this, "processMutation", function(target, mutation) {
16146 if (_this.rafStamps.invokeId && _this.rafStamps.latestId !== _this.rafStamps.invokeId || !_this.rafStamps.invokeId) _this.rafStamps.invokeId = _this.rafStamps.latestId;
16147 if (!_this.pendingCanvasMutations.has(target)) _this.pendingCanvasMutations.set(target, []);
16148 _this.pendingCanvasMutations.get(target).push(mutation);
16149 });
16150 var _options_sampling = options.sampling;
16151 var sampling = _options_sampling === void 0 ? "all" : _options_sampling;
16152 var win = options.win;
16153 var blockClass = options.blockClass;
16154 var blockSelector = options.blockSelector;
16155 var recordCanvas = options.recordCanvas;
16156 var dataURLOptions = options.dataURLOptions;
16157 this.mutationCb = options.mutationCb;
16158 this.mirror = options.mirror;
16159 if (recordCanvas && sampling === "all") this.initCanvasMutationObserver(win, blockClass, blockSelector);
16160 if (recordCanvas && typeof sampling === "number") this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, { dataURLOptions });
16161 }
16162 var _proto = CanvasManager.prototype;
16163 _proto.reset = function reset() {
16164 this.pendingCanvasMutations.clear();
16165 this.resetObservers && this.resetObservers();
16166 };
16167 _proto.freeze = function freeze() {
16168 this.frozen = true;
16169 };
16170 _proto.unfreeze = function unfreeze() {
16171 this.frozen = false;
16172 };
16173 _proto.lock = function lock() {
16174 this.locked = true;
16175 };
16176 _proto.unlock = function unlock() {
16177 this.locked = false;
16178 };
16179 _proto.initCanvasFPSObserver = function initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
16180 var _this = this;
16181 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, true);
16182 var snapshotInProgressMap = /* @__PURE__ */ new Map();
16183 var worker = new WorkerWrapper();
16184 worker.onmessage = function(e2) {
16185 var id = e2.data.id;
16186 snapshotInProgressMap.set(id, false);
16187 if (!("base64" in e2.data)) return;
16188 var _e2_data = e2.data;
16189 var base64 = _e2_data.base64;
16190 var type = _e2_data.type;
16191 var width = _e2_data.width;
16192 var height = _e2_data.height;
16193 _this.mutationCb({
16194 id,
16195 type: CanvasContext["2D"],
16196 commands: [{
16197 property: "clearRect",
16198 args: [
16199 0,
16200 0,
16201 width,
16202 height
16203 ]
16204 }, {
16205 property: "drawImage",
16206 args: [
16207 {
16208 rr_type: "ImageBitmap",
16209 args: [{
16210 rr_type: "Blob",
16211 data: [{
16212 rr_type: "ArrayBuffer",
16213 base64
16214 }],
16215 type
16216 }]
16217 },
16218 0,
16219 0
16220 ]
16221 }]
16222 });
16223 };
16224 var timeBetweenSnapshots = 1e3 / fps;
16225 var lastSnapshotTime = 0;
16226 var rafId;
16227 var getCanvas = function() {
16228 var matchedCanvas = [];
16229 win.document.querySelectorAll("canvas").forEach(function(canvas) {
16230 if (!isBlocked(canvas, blockClass, blockSelector, true)) matchedCanvas.push(canvas);
16231 });
16232 return matchedCanvas;
16233 };
16234 var takeCanvasSnapshots = function(timestamp) {
16235 if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {
16236 rafId = requestAnimationFrame(takeCanvasSnapshots);
16237 return;
16238 }
16239 lastSnapshotTime = timestamp;
16240 var _this1 = _this;
16241 getCanvas().forEach(/*#__PURE__*/ _async_to_generator(function(canvas) {
16242 var _a2;
16243 var id;
16244 var context;
16245 var bitmap;
16246 return _ts_generator(this, function(_state) {
16247 switch (_state.label) {
16248 case 0:
16249 id = _this1.mirror.getId(canvas);
16250 if (snapshotInProgressMap.get(id)) return [2];
16251 if (canvas.width === 0 || canvas.height === 0) return [2];
16252 snapshotInProgressMap.set(id, true);
16253 if (["webgl", "webgl2"].includes(canvas.__context)) {
16254 context = canvas.getContext(canvas.__context);
16255 if (((_a2 = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _a2.preserveDrawingBuffer) === false) context.clear(context.COLOR_BUFFER_BIT);
16256 }
16257 return [4, createImageBitmap(canvas)];
16258 case 1:
16259 bitmap = _state.sent();
16260 worker.postMessage({
16261 id,
16262 bitmap,
16263 width: canvas.width,
16264 height: canvas.height,
16265 dataURLOptions: options.dataURLOptions
16266 }, [bitmap]);
16267 return [2];
16268 }
16269 });
16270 }));
16271 rafId = requestAnimationFrame(takeCanvasSnapshots);
16272 };
16273 rafId = requestAnimationFrame(takeCanvasSnapshots);
16274 this.resetObservers = function() {
16275 canvasContextReset();
16276 cancelAnimationFrame(rafId);
16277 };
16278 };
16279 _proto.initCanvasMutationObserver = function initCanvasMutationObserver(win, blockClass, blockSelector) {
16280 this.startRAFTimestamping();
16281 this.startPendingCanvasMutationFlusher();
16282 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, false);
16283 var canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
16284 var canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
16285 this.resetObservers = function() {
16286 canvasContextReset();
16287 canvas2DReset();
16288 canvasWebGL1and2Reset();
16289 };
16290 };
16291 _proto.startPendingCanvasMutationFlusher = function startPendingCanvasMutationFlusher() {
16292 var _this = this;
16293 requestAnimationFrame(function() {
16294 return _this.flushPendingCanvasMutations();
16295 });
16296 };
16297 _proto.startRAFTimestamping = function startRAFTimestamping() {
16298 var _this = this;
16299 var setLatestRAFTimestamp = function(timestamp) {
16300 _this.rafStamps.latestId = timestamp;
16301 requestAnimationFrame(setLatestRAFTimestamp);
16302 };
16303 requestAnimationFrame(setLatestRAFTimestamp);
16304 };
16305 _proto.flushPendingCanvasMutations = function flushPendingCanvasMutations() {
16306 var _this = this;
16307 this.pendingCanvasMutations.forEach(function(_values, canvas) {
16308 var id = _this.mirror.getId(canvas);
16309 _this.flushPendingCanvasMutationFor(canvas, id);
16310 });
16311 requestAnimationFrame(function() {
16312 return _this.flushPendingCanvasMutations();
16313 });
16314 };
16315 _proto.flushPendingCanvasMutationFor = function flushPendingCanvasMutationFor(canvas, id) {
16316 if (this.frozen || this.locked) return;
16317 var valuesWithType = this.pendingCanvasMutations.get(canvas);
16318 if (!valuesWithType || id === -1) return;
16319 var values = valuesWithType.map(function(value) {
16320 value.type;
16321 return _object_without_properties_loose(value, ["type"]);
16322 });
16323 var type = valuesWithType[0].type;
16324 this.mutationCb({
16325 id,
16326 type,
16327 commands: values
16328 });
16329 this.pendingCanvasMutations.delete(canvas);
16330 };
16331 return CanvasManager;
16332 }();
16333 var StylesheetManager = /*#__PURE__*/ function() {
16334 function StylesheetManager(options) {
16335 __publicField(this, "trackedLinkElements", /* @__PURE__ */ new WeakSet());
16336 __publicField(this, "mutationCb");
16337 __publicField(this, "adoptedStyleSheetCb");
16338 __publicField(this, "styleMirror", new StyleSheetMirror());
16339 this.mutationCb = options.mutationCb;
16340 this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
16341 }
16342 var _proto = StylesheetManager.prototype;
16343 _proto.attachLinkElement = function attachLinkElement(linkEl, childSn) {
16344 if ("_cssText" in childSn.attributes) this.mutationCb({
16345 adds: [],
16346 removes: [],
16347 texts: [],
16348 attributes: [{
16349 id: childSn.id,
16350 attributes: childSn.attributes
16351 }]
16352 });
16353 this.trackLinkElement(linkEl);
16354 };
16355 _proto.trackLinkElement = function trackLinkElement(linkEl) {
16356 if (this.trackedLinkElements.has(linkEl)) return;
16357 this.trackedLinkElements.add(linkEl);
16358 this.trackStylesheetInLinkElement(linkEl);
16359 };
16360 _proto.adoptStyleSheets = function adoptStyleSheets(sheets, hostId) {
16361 var _this;
16362 var _loop = function() {
16363 var sheet = _step.value;
16364 var styleId = void 0;
16365 if (!_this.styleMirror.has(sheet)) {
16366 styleId = _this.styleMirror.add(sheet);
16367 styles.push({
16368 styleId,
16369 rules: Array.from(sheet.rules || CSSRule, function(r2, index2) {
16370 return {
16371 rule: stringifyRule(r2, sheet.href),
16372 index: index2
16373 };
16374 })
16375 });
16376 } else styleId = _this.styleMirror.getId(sheet);
16377 adoptedStyleSheetData.styleIds.push(styleId);
16378 };
16379 if (sheets.length === 0) return;
16380 var adoptedStyleSheetData = {
16381 id: hostId,
16382 styleIds: []
16383 };
16384 var styles = [];
16385 for (var _iterator = _create_for_of_iterator_helper_loose(sheets), _step; !(_step = _iterator()).done;) _this = this, _loop();
16386 if (styles.length > 0) adoptedStyleSheetData.styles = styles;
16387 this.adoptedStyleSheetCb(adoptedStyleSheetData);
16388 };
16389 _proto.reset = function reset() {
16390 this.styleMirror.reset();
16391 this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
16392 };
16393 _proto.trackStylesheetInLinkElement = function trackStylesheetInLinkElement(_linkEl) {};
16394 return StylesheetManager;
16395 }();
16396 var ProcessedNodeManager = /*#__PURE__*/ function() {
16397 function ProcessedNodeManager() {
16398 __publicField(this, "nodeMap", /* @__PURE__ */ new WeakMap());
16399 __publicField(this, "active", false);
16400 }
16401 var _proto = ProcessedNodeManager.prototype;
16402 _proto.inOtherBuffer = function inOtherBuffer(node2, thisBuffer) {
16403 var buffers = this.nodeMap.get(node2);
16404 return buffers && Array.from(buffers).some(function(buffer) {
16405 return buffer !== thisBuffer;
16406 });
16407 };
16408 _proto.add = function add(node2, buffer) {
16409 var _this = this;
16410 if (!this.active) {
16411 this.active = true;
16412 requestAnimationFrame(function() {
16413 _this.nodeMap = /* @__PURE__ */ new WeakMap();
16414 _this.active = false;
16415 });
16416 }
16417 this.nodeMap.set(node2, (this.nodeMap.get(node2) || /* @__PURE__ */ new Set()).add(buffer));
16418 };
16419 _proto.destroy = function destroy() {};
16420 return ProcessedNodeManager;
16421 }();
16422 var wrappedEmit;
16423 var takeFullSnapshot$1;
16424 var canvasManager;
16425 var recording = false;
16426 try {
16427 if (Array.from([1], function(x2) {
16428 return x2 * 2;
16429 })[0] !== 2) {
16430 var cleanFrame = document.createElement("iframe");
16431 document.body.appendChild(cleanFrame);
16432 Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;
16433 document.body.removeChild(cleanFrame);
16434 }
16435 } catch (err) {
16436 console.debug("Unable to override Array.from", err);
16437 }
16438 var mirror = createMirror$2();
16439 function record(options) {
16440 if (options === void 0) options = {};
16441 var emit = options.emit;
16442 var checkoutEveryNms = options.checkoutEveryNms;
16443 var checkoutEveryNth = options.checkoutEveryNth;
16444 var _options_blockClass = options.blockClass;
16445 var blockClass = _options_blockClass === void 0 ? "rr-block" : _options_blockClass;
16446 var _options_blockSelector = options.blockSelector;
16447 var blockSelector = _options_blockSelector === void 0 ? null : _options_blockSelector;
16448 var _options_ignoreClass = options.ignoreClass;
16449 var ignoreClass = _options_ignoreClass === void 0 ? "rr-ignore" : _options_ignoreClass;
16450 var _options_ignoreSelector = options.ignoreSelector;
16451 var ignoreSelector = _options_ignoreSelector === void 0 ? null : _options_ignoreSelector;
16452 var _options_maskTextClass = options.maskTextClass;
16453 var maskTextClass = _options_maskTextClass === void 0 ? "rr-mask" : _options_maskTextClass;
16454 var _options_maskTextSelector = options.maskTextSelector;
16455 var maskTextSelector = _options_maskTextSelector === void 0 ? null : _options_maskTextSelector;
16456 var _options_inlineStylesheet = options.inlineStylesheet;
16457 var inlineStylesheet = _options_inlineStylesheet === void 0 ? true : _options_inlineStylesheet;
16458 var maskAllInputs = options.maskAllInputs;
16459 var _maskInputOptions = options.maskInputOptions;
16460 var _slimDOMOptions = options.slimDOMOptions;
16461 var maskInputFn = options.maskInputFn;
16462 var maskTextFn = options.maskTextFn;
16463 var hooks = options.hooks;
16464 var packFn = options.packFn;
16465 var _options_sampling = options.sampling;
16466 var sampling = _options_sampling === void 0 ? {} : _options_sampling;
16467 var _options_dataURLOptions = options.dataURLOptions;
16468 var dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions;
16469 var mousemoveWait = options.mousemoveWait;
16470 var _options_recordDOM = options.recordDOM;
16471 var recordDOM = _options_recordDOM === void 0 ? true : _options_recordDOM;
16472 var _options_recordCanvas = options.recordCanvas;
16473 var recordCanvas = _options_recordCanvas === void 0 ? false : _options_recordCanvas;
16474 var _options_recordCrossOriginIframes = options.recordCrossOriginIframes;
16475 var recordCrossOriginIframes = _options_recordCrossOriginIframes === void 0 ? false : _options_recordCrossOriginIframes;
16476 var _options_recordAfter = options.recordAfter;
16477 var recordAfter = _options_recordAfter === void 0 ? options.recordAfter === "DOMContentLoaded" ? options.recordAfter : "load" : _options_recordAfter;
16478 var _options_userTriggeredOnInput = options.userTriggeredOnInput;
16479 var userTriggeredOnInput = _options_userTriggeredOnInput === void 0 ? false : _options_userTriggeredOnInput;
16480 var _options_collectFonts = options.collectFonts;
16481 var collectFonts = _options_collectFonts === void 0 ? false : _options_collectFonts;
16482 var _options_inlineImages = options.inlineImages;
16483 var inlineImages = _options_inlineImages === void 0 ? false : _options_inlineImages;
16484 var plugins = options.plugins;
16485 var _options_keepIframeSrcFn = options.keepIframeSrcFn;
16486 var keepIframeSrcFn = _options_keepIframeSrcFn === void 0 ? function() {
16487 return false;
16488 } : _options_keepIframeSrcFn;
16489 var _options_ignoreCSSAttributes = options.ignoreCSSAttributes;
16490 var ignoreCSSAttributes = _options_ignoreCSSAttributes === void 0 ? /* @__PURE__ */ new Set([]) : _options_ignoreCSSAttributes;
16491 var errorHandler2 = options.errorHandler;
16492 registerErrorHandler(errorHandler2);
16493 var inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;
16494 var passEmitsToParent = false;
16495 if (!inEmittingFrame) try {
16496 if (window.parent.document) passEmitsToParent = false;
16497 } catch (e2) {
16498 passEmitsToParent = true;
16499 }
16500 if (inEmittingFrame && !emit) throw new Error("emit function is required");
16501 if (!inEmittingFrame && !passEmitsToParent) return function() {};
16502 if (mousemoveWait !== void 0 && sampling.mousemove === void 0) sampling.mousemove = mousemoveWait;
16503 mirror.reset();
16504 var maskInputOptions = maskAllInputs === true ? {
16505 color: true,
16506 date: true,
16507 "datetime-local": true,
16508 email: true,
16509 month: true,
16510 number: true,
16511 range: true,
16512 search: true,
16513 tel: true,
16514 text: true,
16515 time: true,
16516 url: true,
16517 week: true,
16518 textarea: true,
16519 select: true,
16520 password: true,
16521 hidden: true
16522 } : _maskInputOptions !== void 0 ? _maskInputOptions : { password: true };
16523 var slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? {
16524 script: true,
16525 comment: true,
16526 headFavicon: true,
16527 headWhitespace: true,
16528 headMetaSocial: true,
16529 headMetaRobots: true,
16530 headMetaHttpEquiv: true,
16531 headMetaVerification: true,
16532 headMetaAuthorship: _slimDOMOptions === "all",
16533 headMetaDescKeywords: _slimDOMOptions === "all",
16534 headTitleMutations: _slimDOMOptions === "all"
16535 } : _slimDOMOptions ? _slimDOMOptions : {};
16536 polyfill$1();
16537 var lastFullSnapshotEvent;
16538 var incrementalSnapshotCount = 0;
16539 var eventProcessor = function(e2) {
16540 for (var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;) {
16541 var plugin3 = _step.value;
16542 if (plugin3.eventProcessor) e2 = plugin3.eventProcessor(e2);
16543 }
16544 if (packFn && !passEmitsToParent) e2 = packFn(e2);
16545 return e2;
16546 };
16547 wrappedEmit = function(r2, isCheckout) {
16548 var _a2;
16549 var e2 = r2;
16550 e2.timestamp = nowTimestamp();
16551 if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) mutationBuffers.forEach(function(buf) {
16552 return buf.unfreeze();
16553 });
16554 if (inEmittingFrame) emit == null || emit(eventProcessor(e2), isCheckout);
16555 else if (passEmitsToParent) {
16556 var message = {
16557 type: "rrweb",
16558 event: eventProcessor(e2),
16559 origin: window.location.origin,
16560 isCheckout
16561 };
16562 window.parent.postMessage(message, "*");
16563 }
16564 if (e2.type === EventType.FullSnapshot) {
16565 lastFullSnapshotEvent = e2;
16566 incrementalSnapshotCount = 0;
16567 } else if (e2.type === EventType.IncrementalSnapshot) {
16568 if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) return;
16569 incrementalSnapshotCount++;
16570 var exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
16571 var exceedTime = checkoutEveryNms && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
16572 if (exceedCount || exceedTime) takeFullSnapshot$1(true);
16573 }
16574 };
16575 var wrappedMutationEmit = function(m) {
16576 wrappedEmit({
16577 type: EventType.IncrementalSnapshot,
16578 data: _extends({ source: IncrementalSource.Mutation }, m)
16579 });
16580 };
16581 var wrappedScrollEmit = function(p) {
16582 return wrappedEmit({
16583 type: EventType.IncrementalSnapshot,
16584 data: _extends({ source: IncrementalSource.Scroll }, p)
16585 });
16586 };
16587 var wrappedCanvasMutationEmit = function(p) {
16588 return wrappedEmit({
16589 type: EventType.IncrementalSnapshot,
16590 data: _extends({ source: IncrementalSource.CanvasMutation }, p)
16591 });
16592 };
16593 var wrappedAdoptedStyleSheetEmit = function(a2) {
16594 return wrappedEmit({
16595 type: EventType.IncrementalSnapshot,
16596 data: _extends({ source: IncrementalSource.AdoptedStyleSheet }, a2)
16597 });
16598 };
16599 var stylesheetManager = new StylesheetManager({
16600 mutationCb: wrappedMutationEmit,
16601 adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit
16602 });
16603 var iframeManager = new IframeManager({
16604 mirror,
16605 mutationCb: wrappedMutationEmit,
16606 stylesheetManager,
16607 recordCrossOriginIframes,
16608 wrappedEmit
16609 });
16610 for (var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;) {
16611 var plugin3 = _step.value;
16612 if (plugin3.getMirror) plugin3.getMirror({
16613 nodeMirror: mirror,
16614 crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
16615 crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror
16616 });
16617 }
16618 var processedNodeManager = new ProcessedNodeManager();
16619 canvasManager = new CanvasManager({
16620 recordCanvas,
16621 mutationCb: wrappedCanvasMutationEmit,
16622 win: window,
16623 blockClass,
16624 blockSelector,
16625 mirror,
16626 sampling: sampling.canvas,
16627 dataURLOptions
16628 });
16629 var shadowDomManager = new ShadowDomManager({
16630 mutationCb: wrappedMutationEmit,
16631 scrollCb: wrappedScrollEmit,
16632 bypassOptions: {
16633 blockClass,
16634 blockSelector,
16635 maskTextClass,
16636 maskTextSelector,
16637 inlineStylesheet,
16638 maskInputOptions,
16639 dataURLOptions,
16640 maskTextFn,
16641 maskInputFn,
16642 recordCanvas,
16643 inlineImages,
16644 sampling,
16645 slimDOMOptions,
16646 iframeManager,
16647 stylesheetManager,
16648 canvasManager,
16649 keepIframeSrcFn,
16650 processedNodeManager
16651 },
16652 mirror
16653 });
16654 takeFullSnapshot$1 = function(isCheckout) {
16655 if (isCheckout === void 0) isCheckout = false;
16656 if (!recordDOM) return;
16657 wrappedEmit({
16658 type: EventType.Meta,
16659 data: {
16660 href: window.location.href,
16661 width: getWindowWidth(),
16662 height: getWindowHeight()
16663 }
16664 }, isCheckout);
16665 stylesheetManager.reset();
16666 shadowDomManager.init();
16667 mutationBuffers.forEach(function(buf) {
16668 return buf.lock();
16669 });
16670 var node2 = snapshot(document, {
16671 mirror,
16672 blockClass,
16673 blockSelector,
16674 maskTextClass,
16675 maskTextSelector,
16676 inlineStylesheet,
16677 maskAllInputs: maskInputOptions,
16678 maskTextFn,
16679 maskInputFn,
16680 slimDOM: slimDOMOptions,
16681 dataURLOptions,
16682 recordCanvas,
16683 inlineImages,
16684 onSerialize: function(n2) {
16685 if (isSerializedIframe(n2, mirror)) iframeManager.addIframe(n2);
16686 if (isSerializedStylesheet(n2, mirror)) stylesheetManager.trackLinkElement(n2);
16687 if (hasShadowRoot(n2)) shadowDomManager.addShadowRoot(index.shadowRoot(n2), document);
16688 },
16689 onIframeLoad: function(iframe, childSn) {
16690 iframeManager.attachIframe(iframe, childSn);
16691 shadowDomManager.observeAttachShadow(iframe);
16692 },
16693 onStylesheetLoad: function(linkEl, childSn) {
16694 stylesheetManager.attachLinkElement(linkEl, childSn);
16695 },
16696 keepIframeSrcFn
16697 });
16698 if (!node2) return console.warn("Failed to snapshot the document");
16699 wrappedEmit({
16700 type: EventType.FullSnapshot,
16701 data: {
16702 node: node2,
16703 initialOffset: getWindowScroll(window)
16704 }
16705 }, isCheckout);
16706 mutationBuffers.forEach(function(buf) {
16707 return buf.unlock();
16708 });
16709 if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0) stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
16710 };
16711 try {
16712 var handlers = [];
16713 var observe = function(doc) {
16714 var _a2;
16715 return callbackWrapper(initObservers)({
16716 mutationCb: wrappedMutationEmit,
16717 mousemoveCb: function(positions, source) {
16718 return wrappedEmit({
16719 type: EventType.IncrementalSnapshot,
16720 data: {
16721 source,
16722 positions
16723 }
16724 });
16725 },
16726 mouseInteractionCb: function(d) {
16727 return wrappedEmit({
16728 type: EventType.IncrementalSnapshot,
16729 data: _extends({ source: IncrementalSource.MouseInteraction }, d)
16730 });
16731 },
16732 scrollCb: wrappedScrollEmit,
16733 viewportResizeCb: function(d) {
16734 return wrappedEmit({
16735 type: EventType.IncrementalSnapshot,
16736 data: _extends({ source: IncrementalSource.ViewportResize }, d)
16737 });
16738 },
16739 inputCb: function(v2) {
16740 return wrappedEmit({
16741 type: EventType.IncrementalSnapshot,
16742 data: _extends({ source: IncrementalSource.Input }, v2)
16743 });
16744 },
16745 mediaInteractionCb: function(p) {
16746 return wrappedEmit({
16747 type: EventType.IncrementalSnapshot,
16748 data: _extends({ source: IncrementalSource.MediaInteraction }, p)
16749 });
16750 },
16751 styleSheetRuleCb: function(r2) {
16752 return wrappedEmit({
16753 type: EventType.IncrementalSnapshot,
16754 data: _extends({ source: IncrementalSource.StyleSheetRule }, r2)
16755 });
16756 },
16757 styleDeclarationCb: function(r2) {
16758 return wrappedEmit({
16759 type: EventType.IncrementalSnapshot,
16760 data: _extends({ source: IncrementalSource.StyleDeclaration }, r2)
16761 });
16762 },
16763 canvasMutationCb: wrappedCanvasMutationEmit,
16764 fontCb: function(p) {
16765 return wrappedEmit({
16766 type: EventType.IncrementalSnapshot,
16767 data: _extends({ source: IncrementalSource.Font }, p)
16768 });
16769 },
16770 selectionCb: function(p) {
16771 wrappedEmit({
16772 type: EventType.IncrementalSnapshot,
16773 data: _extends({ source: IncrementalSource.Selection }, p)
16774 });
16775 },
16776 customElementCb: function(c2) {
16777 wrappedEmit({
16778 type: EventType.IncrementalSnapshot,
16779 data: _extends({ source: IncrementalSource.CustomElement }, c2)
16780 });
16781 },
16782 blockClass,
16783 ignoreClass,
16784 ignoreSelector,
16785 maskTextClass,
16786 maskTextSelector,
16787 maskInputOptions,
16788 inlineStylesheet,
16789 sampling,
16790 recordDOM,
16791 recordCanvas,
16792 inlineImages,
16793 userTriggeredOnInput,
16794 collectFonts,
16795 doc,
16796 maskInputFn,
16797 maskTextFn,
16798 keepIframeSrcFn,
16799 blockSelector,
16800 slimDOMOptions,
16801 dataURLOptions,
16802 mirror,
16803 iframeManager,
16804 stylesheetManager,
16805 shadowDomManager,
16806 processedNodeManager,
16807 canvasManager,
16808 ignoreCSSAttributes,
16809 plugins: ((_a2 = plugins == null ? void 0 : plugins.filter(function(p) {
16810 return p.observer;
16811 })) == null ? void 0 : _a2.map(function(p) {
16812 return {
16813 observer: p.observer,
16814 options: p.options,
16815 callback: function(payload) {
16816 return wrappedEmit({
16817 type: EventType.Plugin,
16818 data: {
16819 plugin: p.name,
16820 payload
16821 }
16822 });
16823 }
16824 };
16825 })) || []
16826 }, hooks);
16827 };
16828 iframeManager.addLoadListener(function(iframeEl) {
16829 try {
16830 handlers.push(observe(iframeEl.contentDocument));
16831 } catch (error) {
16832 console.warn(error);
16833 }
16834 });
16835 var init = function() {
16836 takeFullSnapshot$1();
16837 handlers.push(observe(document));
16838 recording = true;
16839 };
16840 if (document.readyState === "interactive" || document.readyState === "complete") init();
16841 else {
16842 handlers.push(on("DOMContentLoaded", function() {
16843 wrappedEmit({
16844 type: EventType.DomContentLoaded,
16845 data: {}
16846 });
16847 if (recordAfter === "DOMContentLoaded") init();
16848 }));
16849 handlers.push(on("load", function() {
16850 wrappedEmit({
16851 type: EventType.Load,
16852 data: {}
16853 });
16854 if (recordAfter === "load") init();
16855 }, window));
16856 }
16857 return function() {
16858 handlers.forEach(function(handler) {
16859 try {
16860 handler();
16861 } catch (error) {
16862 if (!String(error).toLowerCase().includes("cross-origin")) console.warn(error);
16863 }
16864 });
16865 processedNodeManager.destroy();
16866 recording = false;
16867 unregisterErrorHandler();
16868 };
16869 } catch (error) {
16870 console.warn(error);
16871 }
16872 }
16873 record.addCustomEvent = function(tag, payload) {
16874 if (!recording) throw new Error("please add custom event after start recording");
16875 wrappedEmit({
16876 type: EventType.Custom,
16877 data: {
16878 tag,
16879 payload
16880 }
16881 });
16882 };
16883 record.freezePage = function() {
16884 mutationBuffers.forEach(function(buf) {
16885 return buf.freeze();
16886 });
16887 };
16888 record.takeFullSnapshot = function(isCheckout) {
16889 if (!recording) throw new Error("please take full snapshot after start recording");
16890 takeFullSnapshot$1(isCheckout);
16891 };
16892 record.mirror = mirror;
16893 var n;
16894 (function(t2) {
16895 t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped";
16896 })(n || (n = {}));
16897 record.addCustomEvent;
16898 record.freezePage;
16899 record.takeFullSnapshot;
16900 var setImmediate = win["setImmediate"];
16901 var builtInProp;
16902 var cycle;
16903 var schedulingQueue;
16904 var ToString = Object.prototype.toString;
16905 var timer = typeof setImmediate !== "undefined" ? function timer(fn) {
16906 return setImmediate(fn);
16907 } : setTimeout;
16908 try {
16909 Object.defineProperty({}, "x", {});
16910 builtInProp = function builtInProp(obj, name, val, config) {
16911 return Object.defineProperty(obj, name, {
16912 value: val,
16913 writable: true,
16914 configurable: config !== false
16915 });
16916 };
16917 } catch (err) {
16918 builtInProp = function builtInProp(obj, name, val) {
16919 obj[name] = val;
16920 return obj;
16921 };
16922 }
16923 schedulingQueue = (function Queue() {
16924 var first;
16925 var last;
16926 var item;
16927 function Item(fn, self) {
16928 this.fn = fn;
16929 this.self = self;
16930 this.next = void 0;
16931 }
16932 return {
16933 add: function add(fn, self) {
16934 item = new Item(fn, self);
16935 if (last) last.next = item;
16936 else first = item;
16937 last = item;
16938 item = void 0;
16939 },
16940 drain: function drain() {
16941 var f = first;
16942 first = last = cycle = void 0;
16943 while (f) {
16944 f.fn.call(f.self);
16945 f = f.next;
16946 }
16947 }
16948 };
16949 })();
16950 function schedule(fn, self) {
16951 schedulingQueue.add(fn, self);
16952 if (!cycle) cycle = timer(schedulingQueue.drain);
16953 }
16954 function isThenable(o) {
16955 var _then;
16956 var oType = typeof o;
16957 if (o !== null && (oType === "object" || oType === "function")) _then = o.then;
16958 return typeof _then === "function" ? _then : false;
16959 }
16960 function notify() {
16961 for (var i = 0; i < this.chain.length; i++) notifyIsolated(this, this.state === 1 ? this.chain[i].success : this.chain[i].failure, this.chain[i]);
16962 this.chain.length = 0;
16963 }
16964 function notifyIsolated(self, cb, chain) {
16965 var ret;
16966 var _then;
16967 try {
16968 if (cb === false) chain.reject(self.msg);
16969 else {
16970 if (cb === true) ret = self.msg;
16971 else ret = cb.call(void 0, self.msg);
16972 if (ret === chain.promise) chain.reject(TypeError("Promise-chain cycle"));
16973 else if (_then = isThenable(ret)) _then.call(ret, chain.resolve, chain.reject);
16974 else chain.resolve(ret);
16975 }
16976 } catch (err) {
16977 chain.reject(err);
16978 }
16979 }
16980 function resolve(msg) {
16981 var _then;
16982 var self = this;
16983 if (self.triggered) return;
16984 self.triggered = true;
16985 if (self.def) self = self.def;
16986 try {
16987 if (_then = isThenable(msg)) schedule(function() {
16988 var defWrapper = new MakeDefWrapper(self);
16989 try {
16990 _then.call(msg, function $resolve$() {
16991 resolve.apply(defWrapper, arguments);
16992 }, function $reject$() {
16993 reject.apply(defWrapper, arguments);
16994 });
16995 } catch (err) {
16996 reject.call(defWrapper, err);
16997 }
16998 });
16999 else {
17000 self.msg = msg;
17001 self.state = 1;
17002 if (self.chain.length > 0) schedule(notify, self);
17003 }
17004 } catch (err) {
17005 reject.call(new MakeDefWrapper(self), err);
17006 }
17007 }
17008 function reject(msg) {
17009 var self = this;
17010 if (self.triggered) return;
17011 self.triggered = true;
17012 if (self.def) self = self.def;
17013 self.msg = msg;
17014 self.state = 2;
17015 if (self.chain.length > 0) schedule(notify, self);
17016 }
17017 function iteratePromises(Constructor, arr, resolver, rejecter) {
17018 for (var idx = 0; idx < arr.length; idx++) (function IIFE(idx) {
17019 Constructor.resolve(arr[idx]).then(function $resolver$(msg) {
17020 resolver(idx, msg);
17021 }, rejecter);
17022 })(idx);
17023 }
17024 function MakeDefWrapper(self) {
17025 this.def = self;
17026 this.triggered = false;
17027 }
17028 function MakeDef(self) {
17029 this.promise = self;
17030 this.state = 0;
17031 this.triggered = false;
17032 this.chain = [];
17033 this.msg = void 0;
17034 }
17035 function NpoPromise(executor) {
17036 if (typeof executor !== "function") throw TypeError("Not a function");
17037 if (this["__NPO__"] !== 0) throw TypeError("Not a promise");
17038 this["__NPO__"] = 1;
17039 var def = new MakeDef(this);
17040 this["then"] = function then(success, failure) {
17041 var o = {
17042 success: typeof success === "function" ? success : true,
17043 failure: typeof failure === "function" ? failure : false
17044 };
17045 o.promise = new this.constructor(function extractChain(resolve, reject) {
17046 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
17047 o.resolve = resolve;
17048 o.reject = reject;
17049 });
17050 def.chain.push(o);
17051 if (def.state !== 0) schedule(notify, def);
17052 return o.promise;
17053 };
17054 this["catch"] = function $catch$(failure) {
17055 return this.then(void 0, failure);
17056 };
17057 try {
17058 executor.call(void 0, function publicResolve(msg) {
17059 resolve.call(def, msg);
17060 }, function publicReject(msg) {
17061 reject.call(def, msg);
17062 });
17063 } catch (err) {
17064 reject.call(def, err);
17065 }
17066 }
17067 var PromisePrototype = builtInProp({}, "constructor", NpoPromise, false);
17068 NpoPromise.prototype = PromisePrototype;
17069 builtInProp(PromisePrototype, "__NPO__", 0, false);
17070 builtInProp(NpoPromise, "resolve", function Promise$resolve(msg) {
17071 var Constructor = this;
17072 if (msg && typeof msg === "object" && msg["__NPO__"] === 1) return msg;
17073 return new Constructor(function executor(resolve, reject) {
17074 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
17075 resolve(msg);
17076 });
17077 });
17078 builtInProp(NpoPromise, "reject", function Promise$reject(msg) {
17079 return new this(function executor(resolve, reject) {
17080 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
17081 reject(msg);
17082 });
17083 });
17084 builtInProp(NpoPromise, "all", function Promise$all(arr) {
17085 var Constructor = this;
17086 if (ToString.call(arr) !== "[object Array]") return Constructor.reject(TypeError("Not an array"));
17087 if (arr.length === 0) return Constructor.resolve([]);
17088 return new Constructor(function executor(resolve, reject) {
17089 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
17090 var len = arr.length;
17091 var msgs = Array(len);
17092 var count = 0;
17093 iteratePromises(Constructor, arr, function resolver(idx, msg) {
17094 msgs[idx] = msg;
17095 if (++count === len) resolve(msgs);
17096 }, reject);
17097 });
17098 });
17099 builtInProp(NpoPromise, "race", function Promise$race(arr) {
17100 var Constructor = this;
17101 if (ToString.call(arr) !== "[object Array]") return Constructor.reject(TypeError("Not an array"));
17102 return new Constructor(function executor(resolve, reject) {
17103 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
17104 iteratePromises(Constructor, arr, function resolver(idx, msg) {
17105 resolve(msg);
17106 }, reject);
17107 });
17108 });
17109 var PromisePolyfill;
17110 if (typeof Promise !== "undefined" && Promise.toString().indexOf("[native code]") !== -1) PromisePolyfill = Promise;
17111 else PromisePolyfill = NpoPromise;
17112 var Config = {
17113 DEBUG: false,
17114 LIB_VERSION: "2.71.1"
17115 };
17116 var MAX_RECORDING_MS = 1440 * 60 * 1e3;
17117 var MAX_VALUE_FOR_MIN_RECORDING_MS = 8 * 1e3;
17118 var ArrayProto = Array.prototype;
17119 var FuncProto = Function.prototype;
17120 var ObjProto = Object.prototype;
17121 var slice = ArrayProto.slice;
17122 var toString = ObjProto.toString;
17123 var hasOwnProperty = ObjProto.hasOwnProperty;
17124 var windowConsole = win.console;
17125 var navigator = win.navigator;
17126 var document$1 = win.document;
17127 var windowOpera = win.opera;
17128 var screen = win.screen;
17129 var userAgent = navigator.userAgent;
17130 var nativeBind = FuncProto.bind;
17131 var nativeForEach = ArrayProto.forEach;
17132 var nativeIndexOf = ArrayProto.indexOf;
17133 var nativeMap = ArrayProto.map;
17134 var nativeIsArray = Array.isArray;
17135 var breaker = {};
17136 var _$1 = { trim: function(str) {
17137 return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
17138 } };
17139 var console$1 = {
17140 /** @type {function(...*)} */
17141 log: function() {
17142 if (Config.DEBUG && !_$1.isUndefined(windowConsole) && windowConsole) try {
17143 windowConsole.log.apply(windowConsole, arguments);
17144 } catch (err) {
17145 _$1.each(arguments, function(arg) {
17146 windowConsole.log(arg);
17147 });
17148 }
17149 },
17150 /** @type {function(...*)} */
17151 warn: function() {
17152 if (Config.DEBUG && !_$1.isUndefined(windowConsole) && windowConsole) {
17153 var args = ["Mixpanel warning:"].concat(_$1.toArray(arguments));
17154 try {
17155 windowConsole.warn.apply(windowConsole, args);
17156 } catch (err) {
17157 _$1.each(args, function(arg) {
17158 windowConsole.warn(arg);
17159 });
17160 }
17161 }
17162 },
17163 /** @type {function(...*)} */
17164 error: function() {
17165 if (Config.DEBUG && !_$1.isUndefined(windowConsole) && windowConsole) {
17166 var args = ["Mixpanel error:"].concat(_$1.toArray(arguments));
17167 try {
17168 windowConsole.error.apply(windowConsole, args);
17169 } catch (err) {
17170 _$1.each(args, function(arg) {
17171 windowConsole.error(arg);
17172 });
17173 }
17174 }
17175 },
17176 /** @type {function(...*)} */
17177 critical: function() {
17178 if (!_$1.isUndefined(windowConsole) && windowConsole) {
17179 var args = ["Mixpanel error:"].concat(_$1.toArray(arguments));
17180 try {
17181 windowConsole.error.apply(windowConsole, args);
17182 } catch (err) {
17183 _$1.each(args, function(arg) {
17184 windowConsole.error(arg);
17185 });
17186 }
17187 }
17188 }
17189 };
17190 var log_func_with_prefix = function(func, prefix) {
17191 return function() {
17192 arguments[0] = "[" + prefix + "] " + arguments[0];
17193 return func.apply(console$1, arguments);
17194 };
17195 };
17196 var console_with_prefix = function(prefix) {
17197 return {
17198 log: log_func_with_prefix(console$1.log, prefix),
17199 error: log_func_with_prefix(console$1.error, prefix),
17200 critical: log_func_with_prefix(console$1.critical, prefix)
17201 };
17202 };
17203 var safewrap = function(f) {
17204 return function() {
17205 try {
17206 return f.apply(this, arguments);
17207 } catch (e) {
17208 console$1.critical("Implementation error. Please turn on debug and contact [email protected].");
17209 if (Config.DEBUG) console$1.critical(e);
17210 }
17211 };
17212 };
17213 var safewrapClass = function(klass) {
17214 var proto = klass.prototype;
17215 for (var func in proto) if (typeof proto[func] === "function") proto[func] = safewrap(proto[func]);
17216 };
17217 _$1.bind = function(func, context) {
17218 var args;
17219 var bound;
17220 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
17221 if (!_$1.isFunction(func)) throw new TypeError();
17222 args = slice.call(arguments, 2);
17223 bound = function() {
17224 if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
17225 var ctor = {};
17226 ctor.prototype = func.prototype;
17227 var self = new ctor();
17228 ctor.prototype = null;
17229 var result = func.apply(self, args.concat(slice.call(arguments)));
17230 if (Object(result) === result) return result;
17231 return self;
17232 };
17233 return bound;
17234 };
17235 /**
17236 * @param {*=} obj
17237 * @param {function(...*)=} iterator
17238 * @param {Object=} context
17239 */
17240 _$1.each = function(obj, iterator, context) {
17241 if (obj === null || obj === void 0) return;
17242 if (nativeForEach && obj.forEach === nativeForEach) obj.forEach(iterator, context);
17243 else if (obj.length === +obj.length) {
17244 for (var i = 0, l = obj.length; i < l; i++) if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
17245 } else for (var key in obj) if (hasOwnProperty.call(obj, key)) {
17246 if (iterator.call(context, obj[key], key, obj) === breaker) return;
17247 }
17248 };
17249 _$1.extend = function(obj) {
17250 _$1.each(slice.call(arguments, 1), function(source) {
17251 for (var prop in source) if (source[prop] !== void 0) obj[prop] = source[prop];
17252 });
17253 return obj;
17254 };
17255 _$1.isArray = nativeIsArray || function(obj) {
17256 return toString.call(obj) === "[object Array]";
17257 };
17258 _$1.isFunction = function(f) {
17259 try {
17260 return /^\s*\bfunction\b/.test(f);
17261 } catch (x) {
17262 return false;
17263 }
17264 };
17265 _$1.isArguments = function(obj) {
17266 return !!(obj && hasOwnProperty.call(obj, "callee"));
17267 };
17268 _$1.toArray = function(iterable) {
17269 if (!iterable) return [];
17270 if (iterable.toArray) return iterable.toArray();
17271 if (_$1.isArray(iterable)) return slice.call(iterable);
17272 if (_$1.isArguments(iterable)) return slice.call(iterable);
17273 return _$1.values(iterable);
17274 };
17275 _$1.map = function(arr, callback, context) {
17276 if (nativeMap && arr.map === nativeMap) return arr.map(callback, context);
17277 else {
17278 var results = [];
17279 _$1.each(arr, function(item) {
17280 results.push(callback.call(context, item));
17281 });
17282 return results;
17283 }
17284 };
17285 _$1.keys = function(obj) {
17286 var results = [];
17287 if (obj === null) return results;
17288 _$1.each(obj, function(value, key) {
17289 results[results.length] = key;
17290 });
17291 return results;
17292 };
17293 _$1.values = function(obj) {
17294 var results = [];
17295 if (obj === null) return results;
17296 _$1.each(obj, function(value) {
17297 results[results.length] = value;
17298 });
17299 return results;
17300 };
17301 _$1.include = function(obj, target) {
17302 var found = false;
17303 if (obj === null) return found;
17304 if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
17305 _$1.each(obj, function(value) {
17306 if (found || (found = value === target)) return breaker;
17307 });
17308 return found;
17309 };
17310 _$1.includes = function(str, needle) {
17311 return str.indexOf(needle) !== -1;
17312 };
17313 _$1.inherit = function(subclass, superclass) {
17314 subclass.prototype = new superclass();
17315 subclass.prototype.constructor = subclass;
17316 subclass.superclass = superclass.prototype;
17317 return subclass;
17318 };
17319 _$1.isObject = function(obj) {
17320 return obj === Object(obj) && !_$1.isArray(obj);
17321 };
17322 _$1.isEmptyObject = function(obj) {
17323 if (_$1.isObject(obj)) {
17324 for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
17325 return true;
17326 }
17327 return false;
17328 };
17329 _$1.isUndefined = function(obj) {
17330 return obj === void 0;
17331 };
17332 _$1.isString = function(obj) {
17333 return toString.call(obj) == "[object String]";
17334 };
17335 _$1.isDate = function(obj) {
17336 return toString.call(obj) == "[object Date]";
17337 };
17338 _$1.isNumber = function(obj) {
17339 return toString.call(obj) == "[object Number]";
17340 };
17341 _$1.isElement = function(obj) {
17342 return !!(obj && obj.nodeType === 1);
17343 };
17344 _$1.encodeDates = function(obj) {
17345 _$1.each(obj, function(v, k) {
17346 if (_$1.isDate(v)) obj[k] = _$1.formatDate(v);
17347 else if (_$1.isObject(v)) obj[k] = _$1.encodeDates(v);
17348 });
17349 return obj;
17350 };
17351 _$1.timestamp = function() {
17352 Date.now = Date.now || function() {
17353 return +/* @__PURE__ */ new Date();
17354 };
17355 return Date.now();
17356 };
17357 _$1.formatDate = function(d) {
17358 function pad(n) {
17359 return n < 10 ? "0" + n : n;
17360 }
17361 return d.getUTCFullYear() + "-" + pad(d.getUTCMonth() + 1) + "-" + pad(d.getUTCDate()) + "T" + pad(d.getUTCHours()) + ":" + pad(d.getUTCMinutes()) + ":" + pad(d.getUTCSeconds());
17362 };
17363 _$1.strip_empty_properties = function(p) {
17364 var ret = {};
17365 _$1.each(p, function(v, k) {
17366 if (_$1.isString(v) && v.length > 0) ret[k] = v;
17367 });
17368 return ret;
17369 };
17370 _$1.truncate = function(obj, length) {
17371 var ret;
17372 if (typeof obj === "string") ret = obj.slice(0, length);
17373 else if (_$1.isArray(obj)) {
17374 ret = [];
17375 _$1.each(obj, function(val) {
17376 ret.push(_$1.truncate(val, length));
17377 });
17378 } else if (_$1.isObject(obj)) {
17379 ret = {};
17380 _$1.each(obj, function(val, key) {
17381 ret[key] = _$1.truncate(val, length);
17382 });
17383 } else ret = obj;
17384 return ret;
17385 };
17386 _$1.JSONEncode = (function() {
17387 return function(mixed_val) {
17388 var value = mixed_val;
17389 var quote = function(string) {
17390 var escapable = /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
17391 var meta = {
17392 "\b": "\\b",
17393 " ": "\\t",
17394 "\n": "\\n",
17395 "\f": "\\f",
17396 "\r": "\\r",
17397 "\"": "\\\"",
17398 "\\": "\\\\"
17399 };
17400 escapable.lastIndex = 0;
17401 return escapable.test(string) ? "\"" + string.replace(escapable, function(a) {
17402 var c = meta[a];
17403 return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
17404 }) + "\"" : "\"" + string + "\"";
17405 };
17406 var str = function(key, holder) {
17407 var gap = "";
17408 var indent = " ";
17409 var i = 0;
17410 var k = "";
17411 var v = "";
17412 var length = 0;
17413 var mind = gap;
17414 var partial = [];
17415 var value = holder[key];
17416 if (value && typeof value === "object" && typeof value.toJSON === "function") value = value.toJSON(key);
17417 switch (typeof value) {
17418 case "string": return quote(value);
17419 case "number": return isFinite(value) ? String(value) : "null";
17420 case "boolean":
17421 case "null": return String(value);
17422 case "object":
17423 if (!value) return "null";
17424 gap += indent;
17425 partial = [];
17426 if (toString.apply(value) === "[object Array]") {
17427 length = value.length;
17428 for (i = 0; i < length; i += 1) partial[i] = str(i, value) || "null";
17429 v = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]";
17430 gap = mind;
17431 return v;
17432 }
17433 for (k in value) if (hasOwnProperty.call(value, k)) {
17434 v = str(k, value);
17435 if (v) partial.push(quote(k) + (gap ? ": " : ":") + v);
17436 }
17437 v = partial.length === 0 ? "{}" : gap ? "{" + partial.join(",") + mind + "}" : "{" + partial.join(",") + "}";
17438 gap = mind;
17439 return v;
17440 }
17441 };
17442 return str("", { "": value });
17443 };
17444 })();
17445 /**
17446 * From https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
17447 * Slightly modified to throw a real Error rather than a POJO
17448 */
17449 _$1.JSONDecode = (function() {
17450 var at;
17451 var ch;
17452 var escapee = {
17453 "\"": "\"",
17454 "\\": "\\",
17455 "/": "/",
17456 "b": "\b",
17457 "f": "\f",
17458 "n": "\n",
17459 "r": "\r",
17460 "t": " "
17461 };
17462 var text;
17463 var error = function(m) {
17464 var e = new SyntaxError(m);
17465 e.at = at;
17466 e.text = text;
17467 throw e;
17468 };
17469 var next = function(c) {
17470 if (c && c !== ch) error("Expected '" + c + "' instead of '" + ch + "'");
17471 ch = text.charAt(at);
17472 at += 1;
17473 return ch;
17474 };
17475 var number = function() {
17476 var number;
17477 var string = "";
17478 if (ch === "-") {
17479 string = "-";
17480 next("-");
17481 }
17482 while (ch >= "0" && ch <= "9") {
17483 string += ch;
17484 next();
17485 }
17486 if (ch === ".") {
17487 string += ".";
17488 while (next() && ch >= "0" && ch <= "9") string += ch;
17489 }
17490 if (ch === "e" || ch === "E") {
17491 string += ch;
17492 next();
17493 if (ch === "-" || ch === "+") {
17494 string += ch;
17495 next();
17496 }
17497 while (ch >= "0" && ch <= "9") {
17498 string += ch;
17499 next();
17500 }
17501 }
17502 number = +string;
17503 if (!isFinite(number)) error("Bad number");
17504 else return number;
17505 };
17506 var string = function() {
17507 var hex;
17508 var i;
17509 var string = "";
17510 var uffff;
17511 if (ch === "\"") while (next()) {
17512 if (ch === "\"") {
17513 next();
17514 return string;
17515 }
17516 if (ch === "\\") {
17517 next();
17518 if (ch === "u") {
17519 uffff = 0;
17520 for (i = 0; i < 4; i += 1) {
17521 hex = parseInt(next(), 16);
17522 if (!isFinite(hex)) break;
17523 uffff = uffff * 16 + hex;
17524 }
17525 string += String.fromCharCode(uffff);
17526 } else if (typeof escapee[ch] === "string") string += escapee[ch];
17527 else break;
17528 } else string += ch;
17529 }
17530 error("Bad string");
17531 };
17532 var white = function() {
17533 while (ch && ch <= " ") next();
17534 };
17535 var word = function() {
17536 switch (ch) {
17537 case "t":
17538 next("t");
17539 next("r");
17540 next("u");
17541 next("e");
17542 return true;
17543 case "f":
17544 next("f");
17545 next("a");
17546 next("l");
17547 next("s");
17548 next("e");
17549 return false;
17550 case "n":
17551 next("n");
17552 next("u");
17553 next("l");
17554 next("l");
17555 return null;
17556 }
17557 error("Unexpected \"" + ch + "\"");
17558 };
17559 var value;
17560 var array = function() {
17561 var array = [];
17562 if (ch === "[") {
17563 next("[");
17564 white();
17565 if (ch === "]") {
17566 next("]");
17567 return array;
17568 }
17569 while (ch) {
17570 array.push(value());
17571 white();
17572 if (ch === "]") {
17573 next("]");
17574 return array;
17575 }
17576 next(",");
17577 white();
17578 }
17579 }
17580 error("Bad array");
17581 };
17582 var object = function() {
17583 var key;
17584 var object = {};
17585 if (ch === "{") {
17586 next("{");
17587 white();
17588 if (ch === "}") {
17589 next("}");
17590 return object;
17591 }
17592 while (ch) {
17593 key = string();
17594 white();
17595 next(":");
17596 if (Object.hasOwnProperty.call(object, key)) error("Duplicate key \"" + key + "\"");
17597 object[key] = value();
17598 white();
17599 if (ch === "}") {
17600 next("}");
17601 return object;
17602 }
17603 next(",");
17604 white();
17605 }
17606 }
17607 error("Bad object");
17608 };
17609 value = function() {
17610 white();
17611 switch (ch) {
17612 case "{": return object();
17613 case "[": return array();
17614 case "\"": return string();
17615 case "-": return number();
17616 default: return ch >= "0" && ch <= "9" ? number() : word();
17617 }
17618 };
17619 return function(source) {
17620 var result;
17621 text = source;
17622 at = 0;
17623 ch = " ";
17624 result = value();
17625 white();
17626 if (ch) error("Syntax error");
17627 return result;
17628 };
17629 })();
17630 _$1.base64Encode = function(data) {
17631 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17632 var o1;
17633 var o2;
17634 var o3;
17635 var h1;
17636 var h2;
17637 var h3;
17638 var h4;
17639 var bits;
17640 var i = 0;
17641 var ac = 0;
17642 var enc = "";
17643 var tmp_arr = [];
17644 if (!data) return data;
17645 data = _$1.utf8Encode(data);
17646 do {
17647 o1 = data.charCodeAt(i++);
17648 o2 = data.charCodeAt(i++);
17649 o3 = data.charCodeAt(i++);
17650 bits = o1 << 16 | o2 << 8 | o3;
17651 h1 = bits >> 18 & 63;
17652 h2 = bits >> 12 & 63;
17653 h3 = bits >> 6 & 63;
17654 h4 = bits & 63;
17655 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
17656 } while (i < data.length);
17657 enc = tmp_arr.join("");
17658 switch (data.length % 3) {
17659 case 1:
17660 enc = enc.slice(0, -2) + "==";
17661 break;
17662 case 2:
17663 enc = enc.slice(0, -1) + "=";
17664 break;
17665 }
17666 return enc;
17667 };
17668 _$1.utf8Encode = function(string) {
17669 string = (string + "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
17670 var utftext = "";
17671 var start;
17672 var end;
17673 var stringl = 0;
17674 var n;
17675 start = end = 0;
17676 stringl = string.length;
17677 for (n = 0; n < stringl; n++) {
17678 var c1 = string.charCodeAt(n);
17679 var enc = null;
17680 if (c1 < 128) end++;
17681 else if (c1 > 127 && c1 < 2048) enc = String.fromCharCode(c1 >> 6 | 192, c1 & 63 | 128);
17682 else enc = String.fromCharCode(c1 >> 12 | 224, c1 >> 6 & 63 | 128, c1 & 63 | 128);
17683 if (enc !== null) {
17684 if (end > start) utftext += string.substring(start, end);
17685 utftext += enc;
17686 start = end = n + 1;
17687 }
17688 }
17689 if (end > start) utftext += string.substring(start, string.length);
17690 return utftext;
17691 };
17692 _$1.UUID = function() {
17693 try {
17694 return win["crypto"]["randomUUID"]();
17695 } catch (err) {
17696 var uuid = new Array(36);
17697 for (var i = 0; i < 36; i++) uuid[i] = Math.floor(Math.random() * 16);
17698 uuid[14] = 4;
17699 uuid[19] = uuid[19] &= -5;
17700 uuid[19] = uuid[19] |= 8;
17701 uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
17702 return _$1.map(uuid, function(x) {
17703 return x.toString(16);
17704 }).join("");
17705 }
17706 };
17707 var BLOCKED_UA_STRS = [
17708 "ahrefsbot",
17709 "ahrefssiteaudit",
17710 "amazonbot",
17711 "baiduspider",
17712 "bingbot",
17713 "bingpreview",
17714 "chrome-lighthouse",
17715 "facebookexternal",
17716 "petalbot",
17717 "pinterest",
17718 "screaming frog",
17719 "yahoo! slurp",
17720 "yandex",
17721 "adsbot-google",
17722 "apis-google",
17723 "duplexweb-google",
17724 "feedfetcher-google",
17725 "google favicon",
17726 "google web preview",
17727 "google-read-aloud",
17728 "googlebot",
17729 "googleweblight",
17730 "mediapartners-google",
17731 "storebot-google"
17732 ];
17733 _$1.isBlockedUA = function(ua) {
17734 var i;
17735 ua = ua.toLowerCase();
17736 for (i = 0; i < BLOCKED_UA_STRS.length; i++) if (ua.indexOf(BLOCKED_UA_STRS[i]) !== -1) return true;
17737 return false;
17738 };
17739 /**
17740 * @param {Object=} formdata
17741 * @param {string=} arg_separator
17742 */
17743 _$1.HTTPBuildQuery = function(formdata, arg_separator) {
17744 var use_val;
17745 var use_key;
17746 var tmp_arr = [];
17747 if (_$1.isUndefined(arg_separator)) arg_separator = "&";
17748 _$1.each(formdata, function(val, key) {
17749 use_val = encodeURIComponent(val.toString());
17750 use_key = encodeURIComponent(key);
17751 tmp_arr[tmp_arr.length] = use_key + "=" + use_val;
17752 });
17753 return tmp_arr.join(arg_separator);
17754 };
17755 _$1.getQueryParam = function(url, param) {
17756 param = param.replace(/[[]/g, "\\[").replace(/[\]]/g, "\\]");
17757 var regexS = "[\\?&]" + param + "=([^&#]*)";
17758 var results = new RegExp(regexS).exec(url);
17759 if (results === null || results && typeof results[1] !== "string" && results[1].length) return "";
17760 else {
17761 var result = results[1];
17762 try {
17763 result = decodeURIComponent(result);
17764 } catch (err) {
17765 console$1.error("Skipping decoding for malformed query param: " + result);
17766 }
17767 return result.replace(/\+/g, " ");
17768 }
17769 };
17770 _$1.cookie = {
17771 get: function(name) {
17772 var nameEQ = name + "=";
17773 var ca = document$1.cookie.split(";");
17774 for (var i = 0; i < ca.length; i++) {
17775 var c = ca[i];
17776 while (c.charAt(0) == " ") c = c.substring(1, c.length);
17777 if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
17778 }
17779 return null;
17780 },
17781 parse: function(name) {
17782 var cookie;
17783 try {
17784 cookie = _$1.JSONDecode(_$1.cookie.get(name)) || {};
17785 } catch (err) {}
17786 return cookie;
17787 },
17788 set_seconds: function(name, value, seconds, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
17789 var cdomain = "";
17790 var expires = "";
17791 var secure = "";
17792 if (domain_override) cdomain = "; domain=" + domain_override;
17793 else if (is_cross_subdomain) {
17794 var domain = extract_domain(document$1.location.hostname);
17795 cdomain = domain ? "; domain=." + domain : "";
17796 }
17797 if (seconds) {
17798 var date = /* @__PURE__ */ new Date();
17799 date.setTime(date.getTime() + seconds * 1e3);
17800 expires = "; expires=" + date.toGMTString();
17801 }
17802 if (is_cross_site) {
17803 is_secure = true;
17804 secure = "; SameSite=None";
17805 }
17806 if (is_secure) secure += "; secure";
17807 document$1.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/" + cdomain + secure;
17808 },
17809 set: function(name, value, days, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
17810 var cdomain = "";
17811 var expires = "";
17812 var secure = "";
17813 if (domain_override) cdomain = "; domain=" + domain_override;
17814 else if (is_cross_subdomain) {
17815 var domain = extract_domain(document$1.location.hostname);
17816 cdomain = domain ? "; domain=." + domain : "";
17817 }
17818 if (days) {
17819 var date = /* @__PURE__ */ new Date();
17820 date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3);
17821 expires = "; expires=" + date.toGMTString();
17822 }
17823 if (is_cross_site) {
17824 is_secure = true;
17825 secure = "; SameSite=None";
17826 }
17827 if (is_secure) secure += "; secure";
17828 var new_cookie_val = name + "=" + encodeURIComponent(value) + expires + "; path=/" + cdomain + secure;
17829 document$1.cookie = new_cookie_val;
17830 return new_cookie_val;
17831 },
17832 remove: function(name, is_cross_subdomain, domain_override) {
17833 _$1.cookie.set(name, "", -1, is_cross_subdomain, false, false, domain_override);
17834 }
17835 };
17836 var _testStorageSupported = function(storage) {
17837 var supported = true;
17838 try {
17839 var key = "__mplss_" + cheap_guid(8);
17840 var val = "xyz";
17841 storage.setItem(key, val);
17842 if (storage.getItem(key) !== val) supported = false;
17843 storage.removeItem(key);
17844 } catch (err) {
17845 supported = false;
17846 }
17847 return supported;
17848 };
17849 var _localStorageSupported = null;
17850 var localStorageSupported = function(storage, forceCheck) {
17851 if (_localStorageSupported !== null && !forceCheck) return _localStorageSupported;
17852 return _localStorageSupported = _testStorageSupported(storage || win.localStorage);
17853 };
17854 var _sessionStorageSupported = null;
17855 var sessionStorageSupported = function(storage, forceCheck) {
17856 if (_sessionStorageSupported !== null && !forceCheck) return _sessionStorageSupported;
17857 return _sessionStorageSupported = _testStorageSupported(storage || win.sessionStorage);
17858 };
17859 function _storageWrapper(storage, name, is_supported_fn) {
17860 var log_error = function(msg) {
17861 console$1.error(name + " error: " + msg);
17862 };
17863 return {
17864 is_supported: function(forceCheck) {
17865 var supported = is_supported_fn(storage, forceCheck);
17866 if (!supported) console$1.error(name + " unsupported");
17867 return supported;
17868 },
17869 error: log_error,
17870 get: function(key) {
17871 try {
17872 return storage.getItem(key);
17873 } catch (err) {
17874 log_error(err);
17875 }
17876 return null;
17877 },
17878 parse: function(key) {
17879 try {
17880 return _$1.JSONDecode(storage.getItem(key)) || {};
17881 } catch (err) {}
17882 return null;
17883 },
17884 set: function(key, value) {
17885 try {
17886 storage.setItem(key, value);
17887 } catch (err) {
17888 log_error(err);
17889 }
17890 },
17891 remove: function(key) {
17892 try {
17893 storage.removeItem(key);
17894 } catch (err) {
17895 log_error(err);
17896 }
17897 }
17898 };
17899 }
17900 _$1.localStorage = _storageWrapper(win.localStorage, "localStorage", localStorageSupported);
17901 _$1.sessionStorage = _storageWrapper(win.sessionStorage, "sessionStorage", sessionStorageSupported);
17902 _$1.register_event = (function() {
17903 /**
17904 * @param {Object} element
17905 * @param {string} type
17906 * @param {function(...*)} handler
17907 * @param {boolean=} oldSchool
17908 * @param {boolean=} useCapture
17909 */
17910 var register_event = function(element, type, handler, oldSchool, useCapture) {
17911 if (!element) {
17912 console$1.error("No valid element provided to register_event");
17913 return;
17914 }
17915 if (element.addEventListener && !oldSchool) element.addEventListener(type, handler, !!useCapture);
17916 else {
17917 var ontype = "on" + type;
17918 var old_handler = element[ontype];
17919 element[ontype] = makeHandler(element, handler, old_handler);
17920 }
17921 };
17922 function makeHandler(element, new_handler, old_handlers) {
17923 var handler = function(event) {
17924 event = event || fixEvent(win.event);
17925 if (!event) return;
17926 var ret = true;
17927 var old_result;
17928 var new_result;
17929 if (_$1.isFunction(old_handlers)) old_result = old_handlers(event);
17930 new_result = new_handler.call(element, event);
17931 if (false === old_result || false === new_result) ret = false;
17932 return ret;
17933 };
17934 return handler;
17935 }
17936 function fixEvent(event) {
17937 if (event) {
17938 event.preventDefault = fixEvent.preventDefault;
17939 event.stopPropagation = fixEvent.stopPropagation;
17940 }
17941 return event;
17942 }
17943 fixEvent.preventDefault = function() {
17944 this.returnValue = false;
17945 };
17946 fixEvent.stopPropagation = function() {
17947 this.cancelBubble = true;
17948 };
17949 return register_event;
17950 })();
17951 var TOKEN_MATCH_REGEX = /* @__PURE__ */ new RegExp("^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?\"?([^\\]\"]*)\"?\\]$");
17952 _$1.dom_query = (function() {
17953 function getAllChildren(e) {
17954 return e.all ? e.all : e.getElementsByTagName("*");
17955 }
17956 var bad_whitespace = /[\t\r\n]/g;
17957 function hasClass(elem, selector) {
17958 var className = " " + selector + " ";
17959 return (" " + elem.className + " ").replace(bad_whitespace, " ").indexOf(className) >= 0;
17960 }
17961 function getElementsBySelector(selector) {
17962 if (!document$1.getElementsByTagName) return [];
17963 var tokens = selector.split(" ");
17964 var token;
17965 var bits;
17966 var tagName;
17967 var found;
17968 var foundCount;
17969 var i;
17970 var j;
17971 var k;
17972 var elements;
17973 var currentContextIndex;
17974 var currentContext = [document$1];
17975 for (i = 0; i < tokens.length; i++) {
17976 token = tokens[i].replace(/^\s+/, "").replace(/\s+$/, "");
17977 if (token.indexOf("#") > -1) {
17978 bits = token.split("#");
17979 tagName = bits[0];
17980 var id = bits[1];
17981 var element = document$1.getElementById(id);
17982 if (!element || tagName && element.nodeName.toLowerCase() != tagName) return [];
17983 currentContext = [element];
17984 continue;
17985 }
17986 if (token.indexOf(".") > -1) {
17987 bits = token.split(".");
17988 tagName = bits[0];
17989 var className = bits[1];
17990 if (!tagName) tagName = "*";
17991 found = [];
17992 foundCount = 0;
17993 for (j = 0; j < currentContext.length; j++) {
17994 if (tagName == "*") elements = getAllChildren(currentContext[j]);
17995 else elements = currentContext[j].getElementsByTagName(tagName);
17996 for (k = 0; k < elements.length; k++) found[foundCount++] = elements[k];
17997 }
17998 currentContext = [];
17999 currentContextIndex = 0;
18000 for (j = 0; j < found.length; j++) if (found[j].className && _$1.isString(found[j].className) && hasClass(found[j], className)) currentContext[currentContextIndex++] = found[j];
18001 continue;
18002 }
18003 var token_match = token.match(TOKEN_MATCH_REGEX);
18004 if (token_match) {
18005 tagName = token_match[1];
18006 var attrName = token_match[2];
18007 var attrOperator = token_match[3];
18008 var attrValue = token_match[4];
18009 if (!tagName) tagName = "*";
18010 found = [];
18011 foundCount = 0;
18012 for (j = 0; j < currentContext.length; j++) {
18013 if (tagName == "*") elements = getAllChildren(currentContext[j]);
18014 else elements = currentContext[j].getElementsByTagName(tagName);
18015 for (k = 0; k < elements.length; k++) found[foundCount++] = elements[k];
18016 }
18017 currentContext = [];
18018 currentContextIndex = 0;
18019 var checkFunction;
18020 switch (attrOperator) {
18021 case "=":
18022 checkFunction = function(e) {
18023 return e.getAttribute(attrName) == attrValue;
18024 };
18025 break;
18026 case "~":
18027 checkFunction = function(e) {
18028 return e.getAttribute(attrName).match(new RegExp("\\b" + attrValue + "\\b"));
18029 };
18030 break;
18031 case "|":
18032 checkFunction = function(e) {
18033 return e.getAttribute(attrName).match(new RegExp("^" + attrValue + "-?"));
18034 };
18035 break;
18036 case "^":
18037 checkFunction = function(e) {
18038 return e.getAttribute(attrName).indexOf(attrValue) === 0;
18039 };
18040 break;
18041 case "$":
18042 checkFunction = function(e) {
18043 return e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length;
18044 };
18045 break;
18046 case "*":
18047 checkFunction = function(e) {
18048 return e.getAttribute(attrName).indexOf(attrValue) > -1;
18049 };
18050 break;
18051 default: checkFunction = function(e) {
18052 return e.getAttribute(attrName);
18053 };
18054 }
18055 currentContext = [];
18056 currentContextIndex = 0;
18057 for (j = 0; j < found.length; j++) if (checkFunction(found[j])) currentContext[currentContextIndex++] = found[j];
18058 continue;
18059 }
18060 tagName = token;
18061 found = [];
18062 foundCount = 0;
18063 for (j = 0; j < currentContext.length; j++) {
18064 elements = currentContext[j].getElementsByTagName(tagName);
18065 for (k = 0; k < elements.length; k++) found[foundCount++] = elements[k];
18066 }
18067 currentContext = found;
18068 }
18069 return currentContext;
18070 }
18071 return function(query) {
18072 if (_$1.isElement(query)) return [query];
18073 else if (_$1.isObject(query) && !_$1.isUndefined(query.length)) return query;
18074 else return getElementsBySelector.call(this, query);
18075 };
18076 })();
18077 var CAMPAIGN_KEYWORDS = [
18078 "utm_source",
18079 "utm_medium",
18080 "utm_campaign",
18081 "utm_content",
18082 "utm_term",
18083 "utm_id",
18084 "utm_source_platform",
18085 "utm_campaign_id",
18086 "utm_creative_format",
18087 "utm_marketing_tactic"
18088 ];
18089 var CLICK_IDS = [
18090 "dclid",
18091 "fbclid",
18092 "gclid",
18093 "ko_click_id",
18094 "li_fat_id",
18095 "msclkid",
18096 "sccid",
18097 "ttclid",
18098 "twclid",
18099 "wbraid"
18100 ];
18101 _$1.info = {
18102 campaignParams: function(default_value) {
18103 var kw = "";
18104 var params = {};
18105 _$1.each(CAMPAIGN_KEYWORDS, function(kwkey) {
18106 kw = _$1.getQueryParam(document$1.URL, kwkey);
18107 if (kw.length) params[kwkey] = kw;
18108 else if (default_value !== void 0) params[kwkey] = default_value;
18109 });
18110 return params;
18111 },
18112 clickParams: function() {
18113 var id = "";
18114 var params = {};
18115 _$1.each(CLICK_IDS, function(idkey) {
18116 id = _$1.getQueryParam(document$1.URL, idkey);
18117 if (id.length) params[idkey] = id;
18118 });
18119 return params;
18120 },
18121 marketingParams: function() {
18122 return _$1.extend(_$1.info.campaignParams(), _$1.info.clickParams());
18123 },
18124 searchEngine: function(referrer) {
18125 if (referrer.search("https?://(.*)google.([^/?]*)") === 0) return "google";
18126 else if (referrer.search("https?://(.*)bing.com") === 0) return "bing";
18127 else if (referrer.search("https?://(.*)yahoo.com") === 0) return "yahoo";
18128 else if (referrer.search("https?://(.*)duckduckgo.com") === 0) return "duckduckgo";
18129 else return null;
18130 },
18131 searchInfo: function(referrer) {
18132 var search = _$1.info.searchEngine(referrer);
18133 var param = search != "yahoo" ? "q" : "p";
18134 var ret = {};
18135 if (search !== null) {
18136 ret["$search_engine"] = search;
18137 var keyword = _$1.getQueryParam(referrer, param);
18138 if (keyword.length) ret["mp_keyword"] = keyword;
18139 }
18140 return ret;
18141 },
18142 /**
18143 * This function detects which browser is running this script.
18144 * The order of the checks are important since many user agents
18145 * include key words used in later checks.
18146 */
18147 browser: function(user_agent, vendor, opera) {
18148 vendor = vendor || "";
18149 if (opera || _$1.includes(user_agent, " OPR/")) {
18150 if (_$1.includes(user_agent, "Mini")) return "Opera Mini";
18151 return "Opera";
18152 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) return "BlackBerry";
18153 else if (_$1.includes(user_agent, "IEMobile") || _$1.includes(user_agent, "WPDesktop")) return "Internet Explorer Mobile";
18154 else if (_$1.includes(user_agent, "SamsungBrowser/")) return "Samsung Internet";
18155 else if (_$1.includes(user_agent, "Edge") || _$1.includes(user_agent, "Edg/")) return "Microsoft Edge";
18156 else if (_$1.includes(user_agent, "FBIOS")) return "Facebook Mobile";
18157 else if (_$1.includes(user_agent, "Whale/")) return "Whale Browser";
18158 else if (_$1.includes(user_agent, "Chrome")) return "Chrome";
18159 else if (_$1.includes(user_agent, "CriOS")) return "Chrome iOS";
18160 else if (_$1.includes(user_agent, "UCWEB") || _$1.includes(user_agent, "UCBrowser")) return "UC Browser";
18161 else if (_$1.includes(user_agent, "FxiOS")) return "Firefox iOS";
18162 else if (_$1.includes(vendor, "Apple")) {
18163 if (_$1.includes(user_agent, "Mobile")) return "Mobile Safari";
18164 return "Safari";
18165 } else if (_$1.includes(user_agent, "Android")) return "Android Mobile";
18166 else if (_$1.includes(user_agent, "Konqueror")) return "Konqueror";
18167 else if (_$1.includes(user_agent, "Firefox")) return "Firefox";
18168 else if (_$1.includes(user_agent, "MSIE") || _$1.includes(user_agent, "Trident/")) return "Internet Explorer";
18169 else if (_$1.includes(user_agent, "Gecko")) return "Mozilla";
18170 else return "";
18171 },
18172 /**
18173 * This function detects which browser version is running this script,
18174 * parsing major and minor version (e.g., 42.1). User agent strings from:
18175 * http://www.useragentstring.com/pages/useragentstring.php
18176 */
18177 browserVersion: function(userAgent, vendor, opera) {
18178 var regex = {
18179 "Internet Explorer Mobile": /rv:(\d+(\.\d+)?)/,
18180 "Microsoft Edge": /Edge?\/(\d+(\.\d+)?)/,
18181 "Chrome": /Chrome\/(\d+(\.\d+)?)/,
18182 "Chrome iOS": /CriOS\/(\d+(\.\d+)?)/,
18183 "UC Browser": /(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,
18184 "Safari": /Version\/(\d+(\.\d+)?)/,
18185 "Mobile Safari": /Version\/(\d+(\.\d+)?)/,
18186 "Opera": /(Opera|OPR)\/(\d+(\.\d+)?)/,
18187 "Firefox": /Firefox\/(\d+(\.\d+)?)/,
18188 "Firefox iOS": /FxiOS\/(\d+(\.\d+)?)/,
18189 "Konqueror": /Konqueror:(\d+(\.\d+)?)/,
18190 "BlackBerry": /BlackBerry (\d+(\.\d+)?)/,
18191 "Android Mobile": /android\s(\d+(\.\d+)?)/,
18192 "Samsung Internet": /SamsungBrowser\/(\d+(\.\d+)?)/,
18193 "Internet Explorer": /(rv:|MSIE )(\d+(\.\d+)?)/,
18194 "Mozilla": /rv:(\d+(\.\d+)?)/,
18195 "Whale Browser": /Whale\/(\d+(\.\d+)?)/
18196 }[_$1.info.browser(userAgent, vendor, opera)];
18197 if (regex === void 0) return null;
18198 var matches = userAgent.match(regex);
18199 if (!matches) return null;
18200 return parseFloat(matches[matches.length - 2]);
18201 },
18202 os: function() {
18203 var a = userAgent;
18204 if (/Windows/i.test(a)) {
18205 if (/Phone/.test(a) || /WPDesktop/.test(a)) return "Windows Phone";
18206 return "Windows";
18207 } else if (/(iPhone|iPad|iPod)/.test(a)) return "iOS";
18208 else if (/Android/.test(a)) return "Android";
18209 else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) return "BlackBerry";
18210 else if (/Mac/i.test(a)) return "Mac OS X";
18211 else if (/Linux/.test(a)) return "Linux";
18212 else if (/CrOS/.test(a)) return "Chrome OS";
18213 else return "";
18214 },
18215 device: function(user_agent) {
18216 if (/Windows Phone/i.test(user_agent) || /WPDesktop/.test(user_agent)) return "Windows Phone";
18217 else if (/iPad/.test(user_agent)) return "iPad";
18218 else if (/iPod/.test(user_agent)) return "iPod Touch";
18219 else if (/iPhone/.test(user_agent)) return "iPhone";
18220 else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) return "BlackBerry";
18221 else if (/Android/.test(user_agent)) return "Android";
18222 else return "";
18223 },
18224 referringDomain: function(referrer) {
18225 var split = referrer.split("/");
18226 if (split.length >= 3) return split[2];
18227 return "";
18228 },
18229 currentUrl: function() {
18230 return win.location.href;
18231 },
18232 properties: function(extra_props) {
18233 if (typeof extra_props !== "object") extra_props = {};
18234 return _$1.extend(_$1.strip_empty_properties({
18235 "$os": _$1.info.os(),
18236 "$browser": _$1.info.browser(userAgent, navigator.vendor, windowOpera),
18237 "$referrer": document$1.referrer,
18238 "$referring_domain": _$1.info.referringDomain(document$1.referrer),
18239 "$device": _$1.info.device(userAgent)
18240 }), {
18241 "$current_url": _$1.info.currentUrl(),
18242 "$browser_version": _$1.info.browserVersion(userAgent, navigator.vendor, windowOpera),
18243 "$screen_height": screen.height,
18244 "$screen_width": screen.width,
18245 "mp_lib": "web",
18246 "$lib_version": Config.LIB_VERSION,
18247 "$insert_id": cheap_guid(),
18248 "time": _$1.timestamp() / 1e3
18249 }, _$1.strip_empty_properties(extra_props));
18250 },
18251 people_properties: function() {
18252 return _$1.extend(_$1.strip_empty_properties({
18253 "$os": _$1.info.os(),
18254 "$browser": _$1.info.browser(userAgent, navigator.vendor, windowOpera)
18255 }), { "$browser_version": _$1.info.browserVersion(userAgent, navigator.vendor, windowOpera) });
18256 },
18257 mpPageViewProperties: function() {
18258 return _$1.strip_empty_properties({
18259 "current_page_title": document$1.title,
18260 "current_domain": win.location.hostname,
18261 "current_url_path": win.location.pathname,
18262 "current_url_protocol": win.location.protocol,
18263 "current_url_search": win.location.search
18264 });
18265 }
18266 };
18267 /**
18268 * Returns a throttled function that will only run at most every `waitMs` and returns a promise that resolves with the next invocation.
18269 * Throttled calls will build up a batch of args and invoke the callback with all args since the last invocation.
18270 */
18271 var batchedThrottle = function(fn, waitMs) {
18272 var timeoutPromise = null;
18273 var throttledItems = [];
18274 return function(item) {
18275 var self = this;
18276 throttledItems.push(item);
18277 if (!timeoutPromise) timeoutPromise = new PromisePolyfill(function(resolve) {
18278 setTimeout(function() {
18279 var returnValue = fn.apply(self, [throttledItems]);
18280 timeoutPromise = null;
18281 throttledItems = [];
18282 resolve(returnValue);
18283 }, waitMs);
18284 });
18285 return timeoutPromise;
18286 };
18287 };
18288 var cheap_guid = function(maxlen) {
18289 var guid = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
18290 return maxlen ? guid.substring(0, maxlen) : guid;
18291 };
18292 /**
18293 * Generates a W3C traceparent header for easy interop with distributed tracing systems i.e Open Telemetry
18294 * https://www.w3.org/TR/trace-context/#traceparent-header
18295 */
18296 var generateTraceparent = function() {
18297 var traceID = _$1.UUID().replace(/-/g, "");
18298 var parentID = _$1.UUID().replace(/-/g, "").substring(0, 16);
18299 return "00-" + traceID + "-" + parentID + "-01";
18300 };
18301 var SIMPLE_DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]*\.[a-z]+$/i;
18302 var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
18303 /**
18304 * Attempts to extract main domain name from full hostname, using a few blunt heuristics. For
18305 * common TLDs like .com/.org that always have a simple SLD.TLD structure (example.com), we
18306 * simply extract the last two .-separated parts of the hostname (SIMPLE_DOMAIN_MATCH_REGEX).
18307 * For others, we attempt to account for short ccSLD+TLD combos (.ac.uk) with the legacy
18308 * DOMAIN_MATCH_REGEX (kept to maintain backwards compatibility with existing Mixpanel
18309 * integrations). The only _reliable_ way to extract domain from hostname is with an up-to-date
18310 * list like at https://publicsuffix.org/ so for cases that this helper fails at, the SDK
18311 * offers the 'cookie_domain' config option to set it explicitly.
18312 * @example
18313 * extract_domain('my.sub.example.com')
18314 * // 'example.com'
18315 */
18316 var extract_domain = function(hostname) {
18317 var domain_regex = DOMAIN_MATCH_REGEX;
18318 var parts = hostname.split(".");
18319 var tld = parts[parts.length - 1];
18320 if (tld.length > 4 || tld === "com" || tld === "org") domain_regex = SIMPLE_DOMAIN_MATCH_REGEX;
18321 var matches = hostname.match(domain_regex);
18322 return matches ? matches[0] : "";
18323 };
18324 /**
18325 * Check whether we have network connection. default to true for browsers that don't support navigator.onLine (IE)
18326 * @returns {boolean}
18327 */
18328 var isOnline = function() {
18329 var onLine = win.navigator["onLine"];
18330 return _$1.isUndefined(onLine) || onLine;
18331 };
18332 var NOOP_FUNC = function() {};
18333 var JSONStringify = null;
18334 var JSONParse = null;
18335 if (typeof JSON !== "undefined") {
18336 JSONStringify = JSON.stringify;
18337 JSONParse = JSON.parse;
18338 }
18339 JSONStringify = JSONStringify || _$1.JSONEncode;
18340 JSONParse = JSONParse || _$1.JSONDecode;
18341 _$1["info"] = _$1.info;
18342 _$1["info"]["browser"] = _$1.info.browser;
18343 _$1["info"]["browserVersion"] = _$1.info.browserVersion;
18344 _$1["info"]["device"] = _$1.info.device;
18345 _$1["info"]["properties"] = _$1.info.properties;
18346 _$1["isBlockedUA"] = _$1.isBlockedUA;
18347 _$1["isEmptyObject"] = _$1.isEmptyObject;
18348 _$1["isObject"] = _$1.isObject;
18349 _$1["JSONDecode"] = _$1.JSONDecode;
18350 _$1["JSONEncode"] = _$1.JSONEncode;
18351 _$1["toArray"] = _$1.toArray;
18352 _$1["NPO"] = NpoPromise;
18353 var MIXPANEL_DB_NAME = "mixpanelBrowserDb";
18354 var RECORDING_EVENTS_STORE_NAME = "mixpanelRecordingEvents";
18355 var RECORDING_REGISTRY_STORE_NAME = "mixpanelRecordingRegistry";
18356 var DB_VERSION = 1;
18357 var OBJECT_STORES = [RECORDING_EVENTS_STORE_NAME, RECORDING_REGISTRY_STORE_NAME];
18358 /**
18359 * @type {import('./wrapper').StorageWrapper}
18360 */
18361 var IDBStorageWrapper = function(storeName) {
18362 /**
18363 * @type {Promise<IDBDatabase>|null}
18364 */
18365 this.dbPromise = null;
18366 this.storeName = storeName;
18367 };
18368 IDBStorageWrapper.prototype._openDb = function() {
18369 return new PromisePolyfill(function(resolve, reject) {
18370 var openRequest = win.indexedDB.open(MIXPANEL_DB_NAME, DB_VERSION);
18371 openRequest["onerror"] = function() {
18372 reject(openRequest.error);
18373 };
18374 openRequest["onsuccess"] = function() {
18375 resolve(openRequest.result);
18376 };
18377 openRequest["onupgradeneeded"] = function(ev) {
18378 var db = ev.target.result;
18379 OBJECT_STORES.forEach(function(storeName) {
18380 db.createObjectStore(storeName);
18381 });
18382 };
18383 });
18384 };
18385 IDBStorageWrapper.prototype.init = function() {
18386 if (!win.indexedDB) return PromisePolyfill.reject("indexedDB is not supported in this browser");
18387 if (!this.dbPromise) this.dbPromise = this._openDb();
18388 return this.dbPromise.then(function(dbOrError) {
18389 if (dbOrError instanceof win["IDBDatabase"]) return PromisePolyfill.resolve();
18390 else return PromisePolyfill.reject(dbOrError);
18391 });
18392 };
18393 IDBStorageWrapper.prototype.isInitialized = function() {
18394 return !!this.dbPromise;
18395 };
18396 /**
18397 * @param {IDBTransactionMode} mode
18398 * @param {function(IDBObjectStore): void} storeCb
18399 */
18400 IDBStorageWrapper.prototype.makeTransaction = function(mode, storeCb) {
18401 var storeName = this.storeName;
18402 var doTransaction = function(db) {
18403 return new PromisePolyfill(function(resolve, reject) {
18404 var transaction = db.transaction(storeName, mode);
18405 transaction.oncomplete = function() {
18406 resolve(transaction);
18407 };
18408 transaction.onabort = transaction.onerror = function() {
18409 reject(transaction.error);
18410 };
18411 storeCb(transaction.objectStore(storeName));
18412 });
18413 };
18414 return this.dbPromise.then(doTransaction).catch(function(err) {
18415 if (err && err["name"] === "InvalidStateError") {
18416 this.dbPromise = this._openDb();
18417 return this.dbPromise.then(doTransaction);
18418 } else return PromisePolyfill.reject(err);
18419 }.bind(this));
18420 };
18421 IDBStorageWrapper.prototype.setItem = function(key, value) {
18422 return this.makeTransaction("readwrite", function(objectStore) {
18423 objectStore.put(value, key);
18424 });
18425 };
18426 IDBStorageWrapper.prototype.getItem = function(key) {
18427 var req;
18428 return this.makeTransaction("readonly", function(objectStore) {
18429 req = objectStore.get(key);
18430 }).then(function() {
18431 return req.result;
18432 });
18433 };
18434 IDBStorageWrapper.prototype.removeItem = function(key) {
18435 return this.makeTransaction("readwrite", function(objectStore) {
18436 objectStore.delete(key);
18437 });
18438 };
18439 IDBStorageWrapper.prototype.getAll = function() {
18440 var req;
18441 return this.makeTransaction("readonly", function(objectStore) {
18442 req = objectStore.getAll();
18443 }).then(function() {
18444 return req.result;
18445 });
18446 };
18447 /**
18448 * GDPR utils
18449 *
18450 * The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection
18451 * and privacy for all individuals within the European Union. It addresses the export of personal
18452 * data outside the EU. The GDPR aims primarily to give control back to citizens and residents
18453 * over their personal data and to simplify the regulatory environment for international business
18454 * by unifying the regulation within the EU.
18455 *
18456 * This set of utilities is intended to enable opt in/out functionality in the Mixpanel JS SDK.
18457 * These functions are used internally by the SDK and are not intended to be publicly exposed.
18458 */
18459 /**
18460 * A function used to track a Mixpanel event (e.g. MixpanelLib.track)
18461 * @callback trackFunction
18462 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
18463 * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.
18464 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
18465 */
18466 /** Public **/
18467 var GDPR_DEFAULT_PERSISTENCE_PREFIX = "__mp_opt_in_out_";
18468 /**
18469 * Opt the user in to data tracking and cookies/localstorage for the given token
18470 * @param {string} token - Mixpanel project tracking token
18471 * @param {Object} [options]
18472 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
18473 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
18474 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
18475 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18476 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18477 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
18478 * @param {string} [options.cookieDomain] - custom cookie domain
18479 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
18480 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
18481 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
18482 */
18483 function optIn(token, options) {
18484 _optInOut(true, token, options);
18485 }
18486 /**
18487 * Opt the user out of data tracking and cookies/localstorage for the given token
18488 * @param {string} token - Mixpanel project tracking token
18489 * @param {Object} [options]
18490 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18491 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18492 * @param {Number} [options.cookieExpiration] - number of days until the opt-out cookie expires
18493 * @param {string} [options.cookieDomain] - custom cookie domain
18494 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
18495 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-out cookie is set as cross-subdomain or not
18496 * @param {boolean} [options.secureCookie] - whether the opt-out cookie is set as secure or not
18497 */
18498 function optOut(token, options) {
18499 _optInOut(false, token, options);
18500 }
18501 /**
18502 * Check whether the user has opted in to data tracking and cookies/localstorage for the given token
18503 * @param {string} token - Mixpanel project tracking token
18504 * @param {Object} [options]
18505 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18506 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18507 * @returns {boolean} whether the user has opted in to the given opt type
18508 */
18509 function hasOptedIn(token, options) {
18510 return _getStorageValue(token, options) === "1";
18511 }
18512 /**
18513 * Check whether the user has opted out of data tracking and cookies/localstorage for the given token
18514 * @param {string} token - Mixpanel project tracking token
18515 * @param {Object} [options]
18516 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18517 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18518 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
18519 * @returns {boolean} whether the user has opted out of the given opt type
18520 */
18521 function hasOptedOut(token, options) {
18522 if (_hasDoNotTrackFlagOn(options)) {
18523 console$1.warn("This browser has \"Do Not Track\" enabled. This will prevent the Mixpanel SDK from sending any data. To ignore the \"Do Not Track\" browser setting, initialize the Mixpanel instance with the config \"ignore_dnt: true\"");
18524 return true;
18525 }
18526 var optedOut = _getStorageValue(token, options) === "0";
18527 if (optedOut) console$1.warn("You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data.");
18528 return optedOut;
18529 }
18530 /**
18531 * Wrap a MixpanelLib method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
18532 * If the user has opted out, return early instead of executing the method.
18533 * If a callback argument was provided, execute it passing the 0 error code.
18534 * @param {function} method - wrapped method to be executed if the user has not opted out
18535 * @returns {*} the result of executing method OR undefined if the user has opted out
18536 */
18537 function addOptOutCheckMixpanelLib(method) {
18538 return _addOptOutCheck(method, function(name) {
18539 return this.get_config(name);
18540 });
18541 }
18542 /**
18543 * Wrap a MixpanelPeople method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
18544 * If the user has opted out, return early instead of executing the method.
18545 * If a callback argument was provided, execute it passing the 0 error code.
18546 * @param {function} method - wrapped method to be executed if the user has not opted out
18547 * @returns {*} the result of executing method OR undefined if the user has opted out
18548 */
18549 function addOptOutCheckMixpanelPeople(method) {
18550 return _addOptOutCheck(method, function(name) {
18551 return this._get_config(name);
18552 });
18553 }
18554 /**
18555 * Wrap a MixpanelGroup method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
18556 * If the user has opted out, return early instead of executing the method.
18557 * If a callback argument was provided, execute it passing the 0 error code.
18558 * @param {function} method - wrapped method to be executed if the user has not opted out
18559 * @returns {*} the result of executing method OR undefined if the user has opted out
18560 */
18561 function addOptOutCheckMixpanelGroup(method) {
18562 return _addOptOutCheck(method, function(name) {
18563 return this._get_config(name);
18564 });
18565 }
18566 /**
18567 * Clear the user's opt in/out status of data tracking and cookies/localstorage for the given token
18568 * @param {string} token - Mixpanel project tracking token
18569 * @param {Object} [options]
18570 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18571 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18572 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
18573 * @param {string} [options.cookieDomain] - custom cookie domain
18574 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
18575 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
18576 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
18577 */
18578 function clearOptInOut(token, options) {
18579 options = options || {};
18580 _getStorage(options).remove(_getStorageKey(token, options), !!options.crossSubdomainCookie, options.cookieDomain);
18581 }
18582 /** Private **/
18583 /**
18584 * Get storage util
18585 * @param {Object} [options]
18586 * @param {string} [options.persistenceType]
18587 * @returns {object} either _.cookie or _.localstorage
18588 */
18589 function _getStorage(options) {
18590 options = options || {};
18591 return options.persistenceType === "localStorage" ? _$1.localStorage : _$1.cookie;
18592 }
18593 /**
18594 * Get the name of the cookie that is used for the given opt type (tracking, cookie, etc.)
18595 * @param {string} token - Mixpanel project tracking token
18596 * @param {Object} [options]
18597 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18598 * @returns {string} the name of the cookie for the given opt type
18599 */
18600 function _getStorageKey(token, options) {
18601 options = options || {};
18602 return (options.persistencePrefix || GDPR_DEFAULT_PERSISTENCE_PREFIX) + token;
18603 }
18604 /**
18605 * Get the value of the cookie that is used for the given opt type (tracking, cookie, etc.)
18606 * @param {string} token - Mixpanel project tracking token
18607 * @param {Object} [options]
18608 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18609 * @returns {string} the value of the cookie for the given opt type
18610 */
18611 function _getStorageValue(token, options) {
18612 return _getStorage(options).get(_getStorageKey(token, options));
18613 }
18614 /**
18615 * Check whether the user has set the DNT/doNotTrack setting to true in their browser
18616 * @param {Object} [options]
18617 * @param {string} [options.window] - alternate window object to check; used to force various DNT settings in browser tests
18618 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
18619 * @returns {boolean} whether the DNT setting is true
18620 */
18621 function _hasDoNotTrackFlagOn(options) {
18622 if (options && options.ignoreDnt) return false;
18623 var win$1 = options && options.window || win;
18624 var nav = win$1["navigator"] || {};
18625 var hasDntOn = false;
18626 _$1.each([
18627 nav["doNotTrack"],
18628 nav["msDoNotTrack"],
18629 win$1["doNotTrack"]
18630 ], function(dntValue) {
18631 if (_$1.includes([
18632 true,
18633 1,
18634 "1",
18635 "yes"
18636 ], dntValue)) hasDntOn = true;
18637 });
18638 return hasDntOn;
18639 }
18640 /**
18641 * Set cookie/localstorage for the user indicating that they are opted in or out for the given opt type
18642 * @param {boolean} optValue - whether to opt the user in or out for the given opt type
18643 * @param {string} token - Mixpanel project tracking token
18644 * @param {Object} [options]
18645 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
18646 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
18647 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
18648 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18649 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
18650 * @param {string} [options.cookieDomain] - custom cookie domain
18651 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
18652 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
18653 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
18654 */
18655 function _optInOut(optValue, token, options) {
18656 if (!_$1.isString(token) || !token.length) {
18657 console$1.error("gdpr." + (optValue ? "optIn" : "optOut") + " called with an invalid token");
18658 return;
18659 }
18660 options = options || {};
18661 _getStorage(options).set(_getStorageKey(token, options), optValue ? 1 : 0, _$1.isNumber(options.cookieExpiration) ? options.cookieExpiration : null, !!options.crossSubdomainCookie, !!options.secureCookie, !!options.crossSiteCookie, options.cookieDomain);
18662 if (options.track && optValue) options.track(options.trackEventName || "$opt_in", options.trackProperties, { "send_immediately": true });
18663 }
18664 /**
18665 * Wrap a method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
18666 * If the user has opted out, return early instead of executing the method.
18667 * If a callback argument was provided, execute it passing the 0 error code.
18668 * @param {function} method - wrapped method to be executed if the user has not opted out
18669 * @param {function} getConfigValue - getter function for the Mixpanel API token and other options to be used with opt-out check
18670 * @returns {*} the result of executing method OR undefined if the user has opted out
18671 */
18672 function _addOptOutCheck(method, getConfigValue) {
18673 return function() {
18674 var optedOut = false;
18675 try {
18676 var token = getConfigValue.call(this, "token");
18677 var ignoreDnt = getConfigValue.call(this, "ignore_dnt");
18678 var persistenceType = getConfigValue.call(this, "opt_out_tracking_persistence_type");
18679 var persistencePrefix = getConfigValue.call(this, "opt_out_tracking_cookie_prefix");
18680 var win = getConfigValue.call(this, "window");
18681 if (token) optedOut = hasOptedOut(token, {
18682 ignoreDnt,
18683 persistenceType,
18684 persistencePrefix,
18685 window: win
18686 });
18687 } catch (err) {
18688 console$1.error("Unexpected error when checking tracking opt-out status: " + err);
18689 }
18690 if (!optedOut) return method.apply(this, arguments);
18691 var callback = arguments[arguments.length - 1];
18692 if (typeof callback === "function") callback(0);
18693 };
18694 }
18695 var logger$6 = console_with_prefix("lock");
18696 /**
18697 * SharedLock: a mutex built on HTML5 localStorage, to ensure that only one browser
18698 * window/tab at a time will be able to access shared resources.
18699 *
18700 * Based on the Alur and Taubenfeld fast lock
18701 * (http://www.cs.rochester.edu/research/synchronization/pseudocode/fastlock.html)
18702 * with an added timeout to ensure there will be eventual progress in the event
18703 * that a window is closed in the middle of the callback.
18704 *
18705 * Implementation based on the original version by David Wolever (https://github.com/wolever)
18706 * at https://gist.github.com/wolever/5fd7573d1ef6166e8f8c4af286a69432.
18707 *
18708 * @example
18709 * const myLock = new SharedLock('some-key');
18710 * myLock.withLock(function() {
18711 * console.log('I hold the mutex!');
18712 * });
18713 *
18714 * @constructor
18715 */
18716 var SharedLock = function(key, options) {
18717 options = options || {};
18718 this.storageKey = key;
18719 this.storage = options.storage || win.localStorage;
18720 this.pollIntervalMS = options.pollIntervalMS || 100;
18721 this.timeoutMS = options.timeoutMS || 2e3;
18722 this.promiseImpl = options.promiseImpl || PromisePolyfill;
18723 };
18724 SharedLock.prototype.withLock = function(lockedCB, pid) {
18725 var Promise = this.promiseImpl;
18726 return new Promise(_$1.bind(function(resolve, reject) {
18727 var i = pid || (/* @__PURE__ */ new Date()).getTime() + "|" + Math.random();
18728 var startTime = (/* @__PURE__ */ new Date()).getTime();
18729 var key = this.storageKey;
18730 var pollIntervalMS = this.pollIntervalMS;
18731 var timeoutMS = this.timeoutMS;
18732 var storage = this.storage;
18733 var keyX = key + ":X";
18734 var keyY = key + ":Y";
18735 var keyZ = key + ":Z";
18736 var delay = function(cb) {
18737 if ((/* @__PURE__ */ new Date()).getTime() - startTime > timeoutMS) {
18738 logger$6.error("Timeout waiting for mutex on " + key + "; clearing lock. [" + i + "]");
18739 storage.removeItem(keyZ);
18740 storage.removeItem(keyY);
18741 loop();
18742 return;
18743 }
18744 setTimeout(function() {
18745 try {
18746 cb();
18747 } catch (err) {
18748 reject(err);
18749 }
18750 }, pollIntervalMS * (Math.random() + .1));
18751 };
18752 var waitFor = function(predicate, cb) {
18753 if (predicate()) cb();
18754 else delay(function() {
18755 waitFor(predicate, cb);
18756 });
18757 };
18758 var getSetY = function() {
18759 var valY = storage.getItem(keyY);
18760 if (valY && valY !== i) return false;
18761 else {
18762 storage.setItem(keyY, i);
18763 if (storage.getItem(keyY) === i) return true;
18764 else {
18765 if (!localStorageSupported(storage, true)) reject(/* @__PURE__ */ new Error("localStorage support dropped while acquiring lock"));
18766 return false;
18767 }
18768 }
18769 };
18770 var loop = function() {
18771 storage.setItem(keyX, i);
18772 waitFor(getSetY, function() {
18773 if (storage.getItem(keyX) === i) {
18774 criticalSection();
18775 return;
18776 }
18777 delay(function() {
18778 if (storage.getItem(keyY) !== i) {
18779 loop();
18780 return;
18781 }
18782 waitFor(function() {
18783 return !storage.getItem(keyZ);
18784 }, criticalSection);
18785 });
18786 });
18787 };
18788 var criticalSection = function() {
18789 storage.setItem(keyZ, "1");
18790 var removeLock = function() {
18791 storage.removeItem(keyZ);
18792 if (storage.getItem(keyY) === i) storage.removeItem(keyY);
18793 if (storage.getItem(keyX) === i) storage.removeItem(keyX);
18794 };
18795 lockedCB().then(function(ret) {
18796 removeLock();
18797 resolve(ret);
18798 }).catch(function(err) {
18799 removeLock();
18800 reject(err);
18801 });
18802 };
18803 try {
18804 if (localStorageSupported(storage, true)) loop();
18805 else throw new Error("localStorage support check failed");
18806 } catch (err) {
18807 reject(err);
18808 }
18809 }, this));
18810 };
18811 /**
18812 * @type {import('./wrapper').StorageWrapper}
18813 */
18814 var LocalStorageWrapper = function(storageOverride) {
18815 this.storage = storageOverride || win.localStorage;
18816 };
18817 LocalStorageWrapper.prototype.init = function() {
18818 return PromisePolyfill.resolve();
18819 };
18820 LocalStorageWrapper.prototype.isInitialized = function() {
18821 return true;
18822 };
18823 LocalStorageWrapper.prototype.setItem = function(key, value) {
18824 return new PromisePolyfill(_$1.bind(function(resolve, reject) {
18825 try {
18826 this.storage.setItem(key, JSONStringify(value));
18827 } catch (e) {
18828 reject(e);
18829 }
18830 resolve();
18831 }, this));
18832 };
18833 LocalStorageWrapper.prototype.getItem = function(key) {
18834 return new PromisePolyfill(_$1.bind(function(resolve, reject) {
18835 var item;
18836 try {
18837 item = JSONParse(this.storage.getItem(key));
18838 } catch (e) {
18839 reject(e);
18840 }
18841 resolve(item);
18842 }, this));
18843 };
18844 LocalStorageWrapper.prototype.removeItem = function(key) {
18845 return new PromisePolyfill(_$1.bind(function(resolve, reject) {
18846 try {
18847 this.storage.removeItem(key);
18848 } catch (e) {
18849 reject(e);
18850 }
18851 resolve();
18852 }, this));
18853 };
18854 var logger$5 = console_with_prefix("batch");
18855 /**
18856 * RequestQueue: queue for batching API requests with localStorage backup for retries.
18857 * Maintains an in-memory queue which represents the source of truth for the current
18858 * page, but also writes all items out to a copy in the browser's localStorage, which
18859 * can be read on subsequent pageloads and retried. For batchability, all the request
18860 * items in the queue should be of the same type (events, people updates, group updates)
18861 * so they can be sent in a single request to the same API endpoint.
18862 *
18863 * LocalStorage keying and locking: In order for reloads and subsequent pageloads of
18864 * the same site to access the same persisted data, they must share the same localStorage
18865 * key (for instance based on project token and queue type). Therefore access to the
18866 * localStorage entry is guarded by an asynchronous mutex (SharedLock) to prevent
18867 * simultaneously open windows/tabs from overwriting each other's data (which would lead
18868 * to data loss in some situations).
18869 * @constructor
18870 */
18871 var RequestQueue = function(storageKey, options) {
18872 options = options || {};
18873 this.storageKey = storageKey;
18874 this.usePersistence = options.usePersistence;
18875 if (this.usePersistence) {
18876 this.queueStorage = options.queueStorage || new LocalStorageWrapper();
18877 this.lock = new SharedLock(storageKey, {
18878 storage: options.sharedLockStorage || win.localStorage,
18879 timeoutMS: options.sharedLockTimeoutMS
18880 });
18881 }
18882 this.reportError = options.errorReporter || _$1.bind(logger$5.error, logger$5);
18883 this.pid = options.pid || null;
18884 this.memQueue = [];
18885 this.initialized = false;
18886 if (options.enqueueThrottleMs) this.enqueuePersisted = batchedThrottle(_$1.bind(this._enqueuePersisted, this), options.enqueueThrottleMs);
18887 else this.enqueuePersisted = _$1.bind(function(queueEntry) {
18888 return this._enqueuePersisted([queueEntry]);
18889 }, this);
18890 };
18891 RequestQueue.prototype.ensureInit = function() {
18892 if (this.initialized || !this.usePersistence) return PromisePolyfill.resolve();
18893 return this.queueStorage.init().then(_$1.bind(function() {
18894 this.initialized = true;
18895 }, this)).catch(_$1.bind(function(err) {
18896 this.reportError("Error initializing queue persistence. Disabling persistence", err);
18897 this.initialized = true;
18898 this.usePersistence = false;
18899 }, this));
18900 };
18901 /**
18902 * Add one item to queues (memory and localStorage). The queued entry includes
18903 * the given item along with an auto-generated ID and a "flush-after" timestamp.
18904 * It is expected that the item will be sent over the network and dequeued
18905 * before the flush-after time; if this doesn't happen it is considered orphaned
18906 * (e.g., the original tab where it was enqueued got closed before it could be
18907 * sent) and the item can be sent by any tab that finds it in localStorage.
18908 *
18909 * The final callback param is called with a param indicating success or
18910 * failure of the enqueue operation; it is asynchronous because the localStorage
18911 * lock is asynchronous.
18912 */
18913 RequestQueue.prototype.enqueue = function(item, flushInterval) {
18914 var queueEntry = {
18915 "id": cheap_guid(),
18916 "flushAfter": (/* @__PURE__ */ new Date()).getTime() + flushInterval * 2,
18917 "payload": item
18918 };
18919 if (!this.usePersistence) {
18920 this.memQueue.push(queueEntry);
18921 return PromisePolyfill.resolve(true);
18922 } else return this.enqueuePersisted(queueEntry);
18923 };
18924 RequestQueue.prototype._enqueuePersisted = function(queueEntries) {
18925 var enqueueItem = _$1.bind(function() {
18926 return this.ensureInit().then(_$1.bind(function() {
18927 return this.readFromStorage();
18928 }, this)).then(_$1.bind(function(storedQueue) {
18929 return this.saveToStorage(storedQueue.concat(queueEntries));
18930 }, this)).then(_$1.bind(function(succeeded) {
18931 if (succeeded) this.memQueue = this.memQueue.concat(queueEntries);
18932 return succeeded;
18933 }, this)).catch(_$1.bind(function(err) {
18934 this.reportError("Error enqueueing items", err, queueEntries);
18935 return false;
18936 }, this));
18937 }, this);
18938 return this.lock.withLock(enqueueItem, this.pid).catch(_$1.bind(function(err) {
18939 this.reportError("Error acquiring storage lock", err);
18940 return false;
18941 }, this));
18942 };
18943 /**
18944 * Read out the given number of queue entries. If this.memQueue
18945 * has fewer than batchSize items, then look for "orphaned" items
18946 * in the persisted queue (items where the 'flushAfter' time has
18947 * already passed).
18948 */
18949 RequestQueue.prototype.fillBatch = function(batchSize) {
18950 var batch = this.memQueue.slice(0, batchSize);
18951 if (this.usePersistence && batch.length < batchSize) return this.ensureInit().then(_$1.bind(function() {
18952 return this.readFromStorage();
18953 }, this)).then(_$1.bind(function(storedQueue) {
18954 if (storedQueue.length) {
18955 var idsInBatch = {};
18956 _$1.each(batch, function(item) {
18957 idsInBatch[item["id"]] = true;
18958 });
18959 for (var i = 0; i < storedQueue.length; i++) {
18960 var item = storedQueue[i];
18961 if ((/* @__PURE__ */ new Date()).getTime() > item["flushAfter"] && !idsInBatch[item["id"]]) {
18962 item.orphaned = true;
18963 batch.push(item);
18964 if (batch.length >= batchSize) break;
18965 }
18966 }
18967 }
18968 return batch;
18969 }, this));
18970 else return PromisePolyfill.resolve(batch);
18971 };
18972 /**
18973 * Remove items with matching 'id' from array (immutably)
18974 * also remove any item without a valid id (e.g., malformed
18975 * storage entries).
18976 */
18977 var filterOutIDsAndInvalid = function(items, idSet) {
18978 var filteredItems = [];
18979 _$1.each(items, function(item) {
18980 if (item["id"] && !idSet[item["id"]]) filteredItems.push(item);
18981 });
18982 return filteredItems;
18983 };
18984 /**
18985 * Remove items with matching IDs from both in-memory queue
18986 * and persisted queue
18987 */
18988 RequestQueue.prototype.removeItemsByID = function(ids) {
18989 var idSet = {};
18990 _$1.each(ids, function(id) {
18991 idSet[id] = true;
18992 });
18993 this.memQueue = filterOutIDsAndInvalid(this.memQueue, idSet);
18994 if (!this.usePersistence) return PromisePolyfill.resolve(true);
18995 else {
18996 var removeFromStorage = _$1.bind(function() {
18997 return this.ensureInit().then(_$1.bind(function() {
18998 return this.readFromStorage();
18999 }, this)).then(_$1.bind(function(storedQueue) {
19000 storedQueue = filterOutIDsAndInvalid(storedQueue, idSet);
19001 return this.saveToStorage(storedQueue);
19002 }, this)).then(_$1.bind(function() {
19003 return this.readFromStorage();
19004 }, this)).then(_$1.bind(function(storedQueue) {
19005 for (var i = 0; i < storedQueue.length; i++) {
19006 var item = storedQueue[i];
19007 if (item["id"] && !!idSet[item["id"]]) throw new Error("Item not removed from storage");
19008 }
19009 return true;
19010 }, this)).catch(_$1.bind(function(err) {
19011 this.reportError("Error removing items", err, ids);
19012 return false;
19013 }, this));
19014 }, this);
19015 return this.lock.withLock(removeFromStorage, this.pid).catch(_$1.bind(function(err) {
19016 this.reportError("Error acquiring storage lock", err);
19017 if (!localStorageSupported(this.lock.storage, true)) return removeFromStorage().then(_$1.bind(function(success) {
19018 if (!success) return this.queueStorage.removeItem(this.storageKey).then(function() {
19019 return success;
19020 });
19021 return success;
19022 }, this)).catch(_$1.bind(function(err) {
19023 this.reportError("Error clearing queue", err);
19024 return false;
19025 }, this));
19026 else return false;
19027 }, this));
19028 }
19029 };
19030 var updatePayloads = function(existingItems, itemsToUpdate) {
19031 var newItems = [];
19032 _$1.each(existingItems, function(item) {
19033 var id = item["id"];
19034 if (id in itemsToUpdate) {
19035 var newPayload = itemsToUpdate[id];
19036 if (newPayload !== null) {
19037 item["payload"] = newPayload;
19038 newItems.push(item);
19039 }
19040 } else newItems.push(item);
19041 });
19042 return newItems;
19043 };
19044 /**
19045 * Update payloads of given items in both in-memory queue and
19046 * persisted queue. Items set to null are removed from queues.
19047 */
19048 RequestQueue.prototype.updatePayloads = function(itemsToUpdate) {
19049 this.memQueue = updatePayloads(this.memQueue, itemsToUpdate);
19050 if (!this.usePersistence) return PromisePolyfill.resolve(true);
19051 else return this.lock.withLock(_$1.bind(function lockAcquired() {
19052 return this.ensureInit().then(_$1.bind(function() {
19053 return this.readFromStorage();
19054 }, this)).then(_$1.bind(function(storedQueue) {
19055 storedQueue = updatePayloads(storedQueue, itemsToUpdate);
19056 return this.saveToStorage(storedQueue);
19057 }, this)).catch(_$1.bind(function(err) {
19058 this.reportError("Error updating items", itemsToUpdate, err);
19059 return false;
19060 }, this));
19061 }, this), this.pid).catch(_$1.bind(function(err) {
19062 this.reportError("Error acquiring storage lock", err);
19063 return false;
19064 }, this));
19065 };
19066 /**
19067 * Read and parse items array from localStorage entry, handling
19068 * malformed/missing data if necessary.
19069 */
19070 RequestQueue.prototype.readFromStorage = function() {
19071 return this.ensureInit().then(_$1.bind(function() {
19072 return this.queueStorage.getItem(this.storageKey);
19073 }, this)).then(_$1.bind(function(storageEntry) {
19074 if (storageEntry) {
19075 if (!_$1.isArray(storageEntry)) {
19076 this.reportError("Invalid storage entry:", storageEntry);
19077 storageEntry = null;
19078 }
19079 }
19080 return storageEntry || [];
19081 }, this)).catch(_$1.bind(function(err) {
19082 this.reportError("Error retrieving queue", err);
19083 return [];
19084 }, this));
19085 };
19086 /**
19087 * Serialize the given items array to localStorage.
19088 */
19089 RequestQueue.prototype.saveToStorage = function(queue) {
19090 return this.ensureInit().then(_$1.bind(function() {
19091 return this.queueStorage.setItem(this.storageKey, queue);
19092 }, this)).then(function() {
19093 return true;
19094 }).catch(_$1.bind(function(err) {
19095 this.reportError("Error saving queue", err);
19096 return false;
19097 }, this));
19098 };
19099 /**
19100 * Clear out queues (memory and localStorage).
19101 */
19102 RequestQueue.prototype.clear = function() {
19103 this.memQueue = [];
19104 if (this.usePersistence) return this.ensureInit().then(_$1.bind(function() {
19105 return this.queueStorage.removeItem(this.storageKey);
19106 }, this));
19107 else return PromisePolyfill.resolve();
19108 };
19109 var MAX_RETRY_INTERVAL_MS = 600 * 1e3;
19110 var logger$4 = console_with_prefix("batch");
19111 /**
19112 * RequestBatcher: manages the queueing, flushing, retry etc of requests of one
19113 * type (events, people, groups).
19114 * Uses RequestQueue to manage the backing store.
19115 * @constructor
19116 */
19117 var RequestBatcher = function(storageKey, options) {
19118 this.errorReporter = options.errorReporter;
19119 this.queue = new RequestQueue(storageKey, {
19120 errorReporter: _$1.bind(this.reportError, this),
19121 queueStorage: options.queueStorage,
19122 sharedLockStorage: options.sharedLockStorage,
19123 sharedLockTimeoutMS: options.sharedLockTimeoutMS,
19124 usePersistence: options.usePersistence,
19125 enqueueThrottleMs: options.enqueueThrottleMs
19126 });
19127 this.libConfig = options.libConfig;
19128 this.sendRequest = options.sendRequestFunc;
19129 this.beforeSendHook = options.beforeSendHook;
19130 this.stopAllBatching = options.stopAllBatchingFunc;
19131 this.batchSize = this.libConfig["batch_size"];
19132 this.flushInterval = this.libConfig["batch_flush_interval_ms"];
19133 this.stopped = !this.libConfig["batch_autostart"];
19134 this.consecutiveRemovalFailures = 0;
19135 this.itemIdsSentSuccessfully = {};
19136 this.flushOnlyOnInterval = options.flushOnlyOnInterval || false;
19137 this._flushPromise = null;
19138 };
19139 /**
19140 * Add one item to queue.
19141 */
19142 RequestBatcher.prototype.enqueue = function(item) {
19143 return this.queue.enqueue(item, this.flushInterval);
19144 };
19145 /**
19146 * Start flushing batches at the configured time interval. Must call
19147 * this method upon SDK init in order to send anything over the network.
19148 */
19149 RequestBatcher.prototype.start = function() {
19150 this.stopped = false;
19151 this.consecutiveRemovalFailures = 0;
19152 return this.flush();
19153 };
19154 /**
19155 * Stop flushing batches. Can be restarted by calling start().
19156 */
19157 RequestBatcher.prototype.stop = function() {
19158 this.stopped = true;
19159 if (this.timeoutID) {
19160 clearTimeout(this.timeoutID);
19161 this.timeoutID = null;
19162 }
19163 };
19164 /**
19165 * Clear out queue.
19166 */
19167 RequestBatcher.prototype.clear = function() {
19168 return this.queue.clear();
19169 };
19170 /**
19171 * Restore batch size configuration to whatever is set in the main SDK.
19172 */
19173 RequestBatcher.prototype.resetBatchSize = function() {
19174 this.batchSize = this.libConfig["batch_size"];
19175 };
19176 /**
19177 * Restore flush interval time configuration to whatever is set in the main SDK.
19178 */
19179 RequestBatcher.prototype.resetFlush = function() {
19180 this.scheduleFlush(this.libConfig["batch_flush_interval_ms"]);
19181 };
19182 /**
19183 * Schedule the next flush in the given number of milliseconds.
19184 */
19185 RequestBatcher.prototype.scheduleFlush = function(flushMS) {
19186 this.flushInterval = flushMS;
19187 if (!this.stopped) this.timeoutID = setTimeout(_$1.bind(function() {
19188 if (!this.stopped) this._flushPromise = this.flush();
19189 }, this), this.flushInterval);
19190 };
19191 /**
19192 * Send a request using the sendRequest callback, but promisified.
19193 * TODO: sendRequest should be promisified in the first place.
19194 */
19195 RequestBatcher.prototype.sendRequestPromise = function(data, options) {
19196 return new PromisePolyfill(_$1.bind(function(resolve) {
19197 this.sendRequest(data, options, resolve);
19198 }, this));
19199 };
19200 /**
19201 * Flush one batch to network. Depending on success/failure modes, it will either
19202 * remove the batch from the queue or leave it in for retry, and schedule the next
19203 * flush. In cases of most network or API failures, it will back off exponentially
19204 * when retrying.
19205 * @param {Object} [options]
19206 * @param {boolean} [options.sendBeacon] - whether to send batch with
19207 * navigator.sendBeacon (only useful for sending batches before page unloads, as
19208 * sendBeacon offers no callbacks or status indications)
19209 */
19210 RequestBatcher.prototype.flush = function(options) {
19211 if (this.requestInProgress) {
19212 logger$4.log("Flush: Request already in progress");
19213 return PromisePolyfill.resolve();
19214 }
19215 this.requestInProgress = true;
19216 options = options || {};
19217 var timeoutMS = this.libConfig["batch_request_timeout_ms"];
19218 var startTime = (/* @__PURE__ */ new Date()).getTime();
19219 var currentBatchSize = this.batchSize;
19220 return this.queue.fillBatch(currentBatchSize).then(_$1.bind(function(batch) {
19221 var attemptSecondaryFlush = batch.length === currentBatchSize;
19222 var dataForRequest = [];
19223 var transformedItems = {};
19224 _$1.each(batch, function(item) {
19225 var payload = item["payload"];
19226 if (this.beforeSendHook && !item.orphaned) payload = this.beforeSendHook(payload);
19227 if (payload) {
19228 if (payload["event"] && payload["properties"]) payload["properties"] = _$1.extend({}, payload["properties"], { "mp_sent_by_lib_version": Config.LIB_VERSION });
19229 var addPayload = true;
19230 var itemId = item["id"];
19231 if (itemId) {
19232 if ((this.itemIdsSentSuccessfully[itemId] || 0) > 5) {
19233 this.reportError("[dupe] item ID sent too many times, not sending", {
19234 item,
19235 batchSize: batch.length,
19236 timesSent: this.itemIdsSentSuccessfully[itemId]
19237 });
19238 addPayload = false;
19239 }
19240 } else this.reportError("[dupe] found item with no ID", { item });
19241 if (addPayload) dataForRequest.push(payload);
19242 }
19243 transformedItems[item["id"]] = payload;
19244 }, this);
19245 if (dataForRequest.length < 1) {
19246 this.requestInProgress = false;
19247 this.resetFlush();
19248 return PromisePolyfill.resolve();
19249 }
19250 var removeItemsFromQueue = _$1.bind(function() {
19251 return this.queue.removeItemsByID(_$1.map(batch, function(item) {
19252 return item["id"];
19253 })).then(_$1.bind(function(succeeded) {
19254 _$1.each(batch, _$1.bind(function(item) {
19255 var itemId = item["id"];
19256 if (itemId) {
19257 this.itemIdsSentSuccessfully[itemId] = this.itemIdsSentSuccessfully[itemId] || 0;
19258 this.itemIdsSentSuccessfully[itemId]++;
19259 if (this.itemIdsSentSuccessfully[itemId] > 5) this.reportError("[dupe] item ID sent too many times", {
19260 item,
19261 batchSize: batch.length,
19262 timesSent: this.itemIdsSentSuccessfully[itemId]
19263 });
19264 } else this.reportError("[dupe] found item with no ID while removing", { item });
19265 }, this));
19266 if (succeeded) {
19267 this.consecutiveRemovalFailures = 0;
19268 if (this.flushOnlyOnInterval && !attemptSecondaryFlush) {
19269 this.resetFlush();
19270 return PromisePolyfill.resolve();
19271 } else return this.flush();
19272 } else {
19273 if (++this.consecutiveRemovalFailures > 5) {
19274 this.reportError("Too many queue failures; disabling batching system.");
19275 this.stopAllBatching();
19276 } else this.resetFlush();
19277 return PromisePolyfill.resolve();
19278 }
19279 }, this));
19280 }, this);
19281 var batchSendCallback = _$1.bind(function(res) {
19282 this.requestInProgress = false;
19283 try {
19284 if (options.unloading) return this.queue.updatePayloads(transformedItems);
19285 else if (_$1.isObject(res) && res.error === "timeout" && (/* @__PURE__ */ new Date()).getTime() - startTime >= timeoutMS) {
19286 this.reportError("Network timeout; retrying");
19287 return this.flush();
19288 } else if (_$1.isObject(res) && (res.httpStatusCode >= 500 || res.httpStatusCode === 429 || res.httpStatusCode <= 0 && !isOnline() || res.error === "timeout")) {
19289 var retryMS = this.flushInterval * 2;
19290 if (res.retryAfter) retryMS = parseInt(res.retryAfter, 10) * 1e3 || retryMS;
19291 retryMS = Math.min(MAX_RETRY_INTERVAL_MS, retryMS);
19292 this.reportError("Error; retry in " + retryMS + " ms");
19293 this.scheduleFlush(retryMS);
19294 return PromisePolyfill.resolve();
19295 } else if (_$1.isObject(res) && res.httpStatusCode === 413) if (batch.length > 1) {
19296 var halvedBatchSize = Math.max(1, Math.floor(currentBatchSize / 2));
19297 this.batchSize = Math.min(this.batchSize, halvedBatchSize, batch.length - 1);
19298 this.reportError("413 response; reducing batch size to " + this.batchSize);
19299 this.resetFlush();
19300 return PromisePolyfill.resolve();
19301 } else {
19302 this.reportError("Single-event request too large; dropping", batch);
19303 this.resetBatchSize();
19304 return removeItemsFromQueue();
19305 }
19306 else return removeItemsFromQueue();
19307 } catch (err) {
19308 this.reportError("Error handling API response", err);
19309 this.resetFlush();
19310 }
19311 }, this);
19312 var requestOptions = {
19313 method: "POST",
19314 verbose: true,
19315 ignore_json_errors: true,
19316 timeout_ms: timeoutMS
19317 };
19318 if (options.unloading) requestOptions.transport = "sendBeacon";
19319 logger$4.log("MIXPANEL REQUEST:", dataForRequest);
19320 return this.sendRequestPromise(dataForRequest, requestOptions).then(batchSendCallback);
19321 }, this)).catch(_$1.bind(function(err) {
19322 this.reportError("Error flushing request queue", err);
19323 this.resetFlush();
19324 }, this));
19325 };
19326 /**
19327 * Log error to global logger and optional user-defined logger.
19328 */
19329 RequestBatcher.prototype.reportError = function(msg, err) {
19330 logger$4.error.apply(logger$4.error, arguments);
19331 if (this.errorReporter) try {
19332 if (!(err instanceof Error)) err = new Error(msg);
19333 this.errorReporter(msg, err);
19334 } catch (err) {
19335 logger$4.error(err);
19336 }
19337 };
19338 /**
19339 * @param {import('./session-recording').SerializedRecording} serializedRecording
19340 * @returns {boolean}
19341 */
19342 var isRecordingExpired = function(serializedRecording) {
19343 var now = Date.now();
19344 return !serializedRecording || now > serializedRecording["maxExpires"] || now > serializedRecording["idleExpires"];
19345 };
19346 var RECORD_ENQUEUE_THROTTLE_MS = 250;
19347 var logger$3 = console_with_prefix("recorder");
19348 var CompressionStream = win["CompressionStream"];
19349 var RECORDER_BATCHER_LIB_CONFIG = {
19350 "batch_size": 1e3,
19351 "batch_flush_interval_ms": 10 * 1e3,
19352 "batch_request_timeout_ms": 90 * 1e3,
19353 "batch_autostart": true
19354 };
19355 var ACTIVE_SOURCES = /* @__PURE__ */ new Set([
19356 IncrementalSource.MouseMove,
19357 IncrementalSource.MouseInteraction,
19358 IncrementalSource.Scroll,
19359 IncrementalSource.ViewportResize,
19360 IncrementalSource.Input,
19361 IncrementalSource.TouchMove,
19362 IncrementalSource.MediaInteraction,
19363 IncrementalSource.Drag,
19364 IncrementalSource.Selection
19365 ]);
19366 function isUserEvent(ev) {
19367 return ev.type === EventType.IncrementalSnapshot && ACTIVE_SOURCES.has(ev.data.source);
19368 }
19369 /**
19370 * @typedef {Object} SerializedRecording
19371 * @property {number} idleExpires
19372 * @property {number} maxExpires
19373 * @property {number} replayStartTime
19374 * @property {number} seqNo
19375 * @property {string} batchStartUrl
19376 * @property {string} replayId
19377 * @property {string} tabId
19378 * @property {string} replayStartUrl
19379 */
19380 /**
19381 * @typedef {Object} SessionRecordingOptions
19382 * @property {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
19383 * @property {String} [options.replayId] - unique uuid for a single replay
19384 * @property {Function} [options.onIdleTimeout] - callback when a recording reaches idle timeout
19385 * @property {Function} [options.onMaxLengthReached] - callback when a recording reaches its maximum length
19386 * @property {Function} [options.rrwebRecord] - rrweb's `record` function
19387 * @property {Function} [options.onBatchSent] - callback when a batch of events is sent to the server
19388 * @property {Storage} [options.sharedLockStorage] - optional storage for shared lock, used for test dependency injection
19389 * optional properties for deserialization:
19390 * @property {number} idleExpires
19391 * @property {number} maxExpires
19392 * @property {number} replayStartTime
19393 * @property {number} seqNo
19394 * @property {string} batchStartUrl
19395 * @property {string} replayStartUrl
19396 */
19397 /**
19398 * @typedef {Object} UserIdInfo
19399 * @property {string} distinct_id
19400 * @property {string} user_id
19401 * @property {string} device_id
19402 */
19403 /**
19404 * This class encapsulates a single session recording and its lifecycle.
19405 * @param {SessionRecordingOptions} options
19406 */
19407 var SessionRecording = function(options) {
19408 this._mixpanel = options.mixpanelInstance;
19409 this._onIdleTimeout = options.onIdleTimeout || NOOP_FUNC;
19410 this._onMaxLengthReached = options.onMaxLengthReached || NOOP_FUNC;
19411 this._onBatchSent = options.onBatchSent || NOOP_FUNC;
19412 this._rrwebRecord = options.rrwebRecord || null;
19413 this._stopRecording = null;
19414 this.replayId = options.replayId;
19415 this.batchStartUrl = options.batchStartUrl || null;
19416 this.replayStartUrl = options.replayStartUrl || null;
19417 this.idleExpires = options.idleExpires || null;
19418 this.maxExpires = options.maxExpires || null;
19419 this.replayStartTime = options.replayStartTime || null;
19420 this.seqNo = options.seqNo || 0;
19421 this.idleTimeoutId = null;
19422 this.maxTimeoutId = null;
19423 this.recordMaxMs = MAX_RECORDING_MS;
19424 this.recordMinMs = 0;
19425 var usePersistence = localStorageSupported(options.sharedLockStorage, true) && !this.getConfig("disable_persistence");
19426 this.batcherKey = "__mprec_" + this.getConfig("name") + "_" + this.getConfig("token") + "_" + this.replayId;
19427 this.queueStorage = new IDBStorageWrapper(RECORDING_EVENTS_STORE_NAME);
19428 this.batcher = new RequestBatcher(this.batcherKey, {
19429 errorReporter: this.reportError.bind(this),
19430 flushOnlyOnInterval: true,
19431 libConfig: RECORDER_BATCHER_LIB_CONFIG,
19432 sendRequestFunc: this.flushEventsWithOptOut.bind(this),
19433 queueStorage: this.queueStorage,
19434 sharedLockStorage: options.sharedLockStorage,
19435 usePersistence,
19436 stopAllBatchingFunc: this.stopRecording.bind(this),
19437 enqueueThrottleMs: RECORD_ENQUEUE_THROTTLE_MS,
19438 sharedLockTimeoutMS: 10 * 1e3
19439 });
19440 };
19441 /**
19442 * @returns {UserIdInfo}
19443 */
19444 SessionRecording.prototype.getUserIdInfo = function() {
19445 if (this.finalFlushUserIdInfo) return this.finalFlushUserIdInfo;
19446 var userIdInfo = { "distinct_id": String(this._mixpanel.get_distinct_id()) };
19447 var deviceId = this._mixpanel.get_property("$device_id");
19448 if (deviceId) userIdInfo["$device_id"] = deviceId;
19449 var userId = this._mixpanel.get_property("$user_id");
19450 if (userId) userIdInfo["$user_id"] = userId;
19451 return userIdInfo;
19452 };
19453 SessionRecording.prototype.unloadPersistedData = function() {
19454 this.batcher.stop();
19455 return this.batcher.flush().then(function() {
19456 return this.queueStorage.removeItem(this.batcherKey);
19457 }.bind(this));
19458 };
19459 SessionRecording.prototype.getConfig = function(configVar) {
19460 return this._mixpanel.get_config(configVar);
19461 };
19462 SessionRecording.prototype.get_config = function(configVar) {
19463 return this.getConfig(configVar);
19464 };
19465 SessionRecording.prototype.startRecording = function(shouldStopBatcher) {
19466 if (this._rrwebRecord === null) {
19467 this.reportError("rrweb record function not provided. ");
19468 return;
19469 }
19470 if (this._stopRecording !== null) {
19471 logger$3.log("Recording already in progress, skipping startRecording.");
19472 return;
19473 }
19474 this.recordMaxMs = this.getConfig("record_max_ms");
19475 if (this.recordMaxMs > MAX_RECORDING_MS) {
19476 this.recordMaxMs = MAX_RECORDING_MS;
19477 logger$3.critical("record_max_ms cannot be greater than " + MAX_RECORDING_MS + "ms. Capping value.");
19478 }
19479 if (!this.maxExpires) this.maxExpires = (/* @__PURE__ */ new Date()).getTime() + this.recordMaxMs;
19480 this.recordMinMs = this.getConfig("record_min_ms");
19481 if (this.recordMinMs > MAX_VALUE_FOR_MIN_RECORDING_MS) {
19482 this.recordMinMs = MAX_VALUE_FOR_MIN_RECORDING_MS;
19483 logger$3.critical("record_min_ms cannot be greater than " + MAX_VALUE_FOR_MIN_RECORDING_MS + "ms. Capping value.");
19484 }
19485 if (!this.replayStartTime) {
19486 this.replayStartTime = (/* @__PURE__ */ new Date()).getTime();
19487 this.batchStartUrl = _$1.info.currentUrl();
19488 this.replayStartUrl = _$1.info.currentUrl();
19489 }
19490 if (shouldStopBatcher || this.recordMinMs > 0) this.batcher.stop();
19491 else this.batcher.start();
19492 var resetIdleTimeout = function() {
19493 clearTimeout(this.idleTimeoutId);
19494 var idleTimeoutMs = this.getConfig("record_idle_timeout_ms");
19495 this.idleTimeoutId = setTimeout(this._onIdleTimeout, idleTimeoutMs);
19496 this.idleExpires = (/* @__PURE__ */ new Date()).getTime() + idleTimeoutMs;
19497 }.bind(this);
19498 resetIdleTimeout();
19499 var blockSelector = this.getConfig("record_block_selector");
19500 if (blockSelector === "" || blockSelector === null) blockSelector = void 0;
19501 try {
19502 this._stopRecording = this._rrwebRecord({
19503 "emit": function(ev) {
19504 if (this.idleExpires && this.idleExpires < ev.timestamp) {
19505 this._onIdleTimeout();
19506 return;
19507 }
19508 if (isUserEvent(ev)) {
19509 if (this.batcher.stopped && (/* @__PURE__ */ new Date()).getTime() - this.replayStartTime >= this.recordMinMs) this.batcher.start();
19510 resetIdleTimeout();
19511 }
19512 this.__enqueuePromise = this.batcher.enqueue(ev);
19513 }.bind(this),
19514 "blockClass": this.getConfig("record_block_class"),
19515 "blockSelector": blockSelector,
19516 "collectFonts": this.getConfig("record_collect_fonts"),
19517 "dataURLOptions": {
19518 "type": "image/webp",
19519 "quality": .6
19520 },
19521 "maskAllInputs": true,
19522 "maskTextClass": this.getConfig("record_mask_text_class"),
19523 "maskTextSelector": this.getConfig("record_mask_text_selector"),
19524 "recordCanvas": this.getConfig("record_canvas"),
19525 "sampling": { "canvas": 15 }
19526 });
19527 } catch (err) {
19528 this.reportError("Unexpected error when starting rrweb recording.", err);
19529 }
19530 if (typeof this._stopRecording !== "function") {
19531 this.reportError("rrweb failed to start, skipping this recording.");
19532 this._stopRecording = null;
19533 this.stopRecording();
19534 return;
19535 }
19536 var maxTimeoutMs = this.maxExpires - (/* @__PURE__ */ new Date()).getTime();
19537 this.maxTimeoutId = setTimeout(this._onMaxLengthReached.bind(this), maxTimeoutMs);
19538 };
19539 SessionRecording.prototype.stopRecording = function(skipFlush) {
19540 this.finalFlushUserIdInfo = this.getUserIdInfo();
19541 if (!this.isRrwebStopped()) {
19542 try {
19543 this._stopRecording();
19544 } catch (err) {
19545 this.reportError("Error with rrweb stopRecording", err);
19546 }
19547 this._stopRecording = null;
19548 }
19549 var flushPromise;
19550 if (this.batcher.stopped) flushPromise = this.batcher.clear();
19551 else if (!skipFlush) flushPromise = this.batcher.flush();
19552 this.batcher.stop();
19553 clearTimeout(this.idleTimeoutId);
19554 clearTimeout(this.maxTimeoutId);
19555 return flushPromise;
19556 };
19557 SessionRecording.prototype.isRrwebStopped = function() {
19558 return this._stopRecording === null;
19559 };
19560 /**
19561 * Flushes the current batch of events to the server, but passes an opt-out callback to make sure
19562 * we stop recording and dump any queued events if the user has opted out.
19563 */
19564 SessionRecording.prototype.flushEventsWithOptOut = function(data, options, cb) {
19565 var onOptOut = function(code) {
19566 if (code === 0) {
19567 this.stopRecording();
19568 cb({ error: "Tracking has been opted out, stopping recording." });
19569 }
19570 }.bind(this);
19571 this._flushEvents(data, options, cb, onOptOut);
19572 };
19573 /**
19574 * @returns {SerializedRecording}
19575 */
19576 SessionRecording.prototype.serialize = function() {
19577 var tabId;
19578 try {
19579 tabId = this._mixpanel.get_tab_id();
19580 } catch (e) {
19581 this.reportError("Error getting tab ID for serialization ", e);
19582 tabId = null;
19583 }
19584 return {
19585 "replayId": this.replayId,
19586 "seqNo": this.seqNo,
19587 "replayStartTime": this.replayStartTime,
19588 "batchStartUrl": this.batchStartUrl,
19589 "replayStartUrl": this.replayStartUrl,
19590 "idleExpires": this.idleExpires,
19591 "maxExpires": this.maxExpires,
19592 "tabId": tabId
19593 };
19594 };
19595 /**
19596 * @static
19597 * @param {SerializedRecording} serializedRecording
19598 * @param {SessionRecordingOptions} options
19599 * @returns {SessionRecording}
19600 */
19601 SessionRecording.deserialize = function(serializedRecording, options) {
19602 return new SessionRecording(_$1.extend({}, options, {
19603 replayId: serializedRecording["replayId"],
19604 batchStartUrl: serializedRecording["batchStartUrl"],
19605 replayStartUrl: serializedRecording["replayStartUrl"],
19606 idleExpires: serializedRecording["idleExpires"],
19607 maxExpires: serializedRecording["maxExpires"],
19608 replayStartTime: serializedRecording["replayStartTime"],
19609 seqNo: serializedRecording["seqNo"],
19610 sharedLockStorage: options.sharedLockStorage
19611 }));
19612 };
19613 SessionRecording.prototype._sendRequest = function(currentReplayId, reqParams, reqBody, callback) {
19614 var onSuccess = function(response, responseBody) {
19615 if (response.status === 200 && this.replayId === currentReplayId) {
19616 this.seqNo++;
19617 this.batchStartUrl = _$1.info.currentUrl();
19618 }
19619 this._onBatchSent();
19620 callback({
19621 status: 0,
19622 httpStatusCode: response.status,
19623 responseBody,
19624 retryAfter: response.headers.get("Retry-After")
19625 });
19626 }.bind(this);
19627 var apiHost = this._mixpanel.get_api_host && this._mixpanel.get_api_host("record") || this.getConfig("api_host");
19628 win["fetch"](apiHost + "/" + this.getConfig("api_routes")["record"] + "?" + new URLSearchParams(reqParams), {
19629 "method": "POST",
19630 "headers": {
19631 "Authorization": "Basic " + btoa(this.getConfig("token") + ":"),
19632 "Content-Type": "application/octet-stream"
19633 },
19634 "body": reqBody
19635 }).then(function(response) {
19636 response.json().then(function(responseBody) {
19637 onSuccess(response, responseBody);
19638 }).catch(function(error) {
19639 callback({ error });
19640 });
19641 }).catch(function(error) {
19642 callback({
19643 error,
19644 httpStatusCode: 0
19645 });
19646 });
19647 };
19648 SessionRecording.prototype._flushEvents = addOptOutCheckMixpanelLib(function(data, options, callback) {
19649 var numEvents = data.length;
19650 if (numEvents > 0) {
19651 var replayId = this.replayId;
19652 var batchStartTime = Infinity;
19653 var batchEndTime = -Infinity;
19654 var hasFullSnapshot = false;
19655 for (var i = 0; i < numEvents; i++) {
19656 batchStartTime = Math.min(batchStartTime, data[i].timestamp);
19657 batchEndTime = Math.max(batchEndTime, data[i].timestamp);
19658 if (data[i].type === EventType.FullSnapshot) hasFullSnapshot = true;
19659 }
19660 if (this.seqNo === 0) {
19661 if (!hasFullSnapshot) {
19662 callback({ error: "First batch does not contain a full snapshot. Aborting recording." });
19663 this.stopRecording(true);
19664 return;
19665 }
19666 this.replayStartTime = batchStartTime;
19667 } else if (!this.replayStartTime) {
19668 this.reportError("Replay start time not set but seqNo is not 0. Using current batch start time as a fallback.");
19669 this.replayStartTime = batchStartTime;
19670 }
19671 var replayLengthMs = batchEndTime - this.replayStartTime;
19672 var reqParams = {
19673 "$current_url": this.batchStartUrl,
19674 "$lib_version": Config.LIB_VERSION,
19675 "batch_start_time": batchStartTime / 1e3,
19676 "mp_lib": "web",
19677 "replay_id": replayId,
19678 "replay_length_ms": replayLengthMs,
19679 "replay_start_time": this.replayStartTime / 1e3,
19680 "replay_start_url": this.replayStartUrl,
19681 "seq": this.seqNo
19682 };
19683 var eventsJson = JSON.stringify(data);
19684 Object.assign(reqParams, this.getUserIdInfo());
19685 if (CompressionStream) {
19686 var gzipStream = new Blob([eventsJson], { type: "application/json" }).stream().pipeThrough(new CompressionStream("gzip"));
19687 new Response(gzipStream).blob().then(function(compressedBlob) {
19688 reqParams["format"] = "gzip";
19689 this._sendRequest(replayId, reqParams, compressedBlob, callback);
19690 }.bind(this));
19691 } else {
19692 reqParams["format"] = "body";
19693 this._sendRequest(replayId, reqParams, eventsJson, callback);
19694 }
19695 }
19696 });
19697 SessionRecording.prototype.reportError = function(msg, err) {
19698 logger$3.error.apply(logger$3.error, arguments);
19699 try {
19700 if (!err && !(msg instanceof Error)) msg = new Error(msg);
19701 this.getConfig("error_reporter")(msg, err);
19702 } catch (err) {
19703 logger$3.error(err);
19704 }
19705 };
19706 /**
19707 * Module for handling the storage and retrieval of recording metadata as well as any active recordings.
19708 * Makes sure that only one tab can be recording at a time.
19709 */
19710 var RecordingRegistry = function(options) {
19711 /** @type {IDBStorageWrapper} */
19712 this.idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
19713 this.errorReporter = options.errorReporter;
19714 this.mixpanelInstance = options.mixpanelInstance;
19715 this.sharedLockStorage = options.sharedLockStorage;
19716 };
19717 RecordingRegistry.prototype.isPersistenceEnabled = function() {
19718 return !this.mixpanelInstance.get_config("disable_persistence");
19719 };
19720 RecordingRegistry.prototype.handleError = function(err) {
19721 this.errorReporter("IndexedDB error: ", err);
19722 };
19723 /**
19724 * @param {import('./session-recording').SerializedRecording} serializedRecording
19725 */
19726 RecordingRegistry.prototype.setActiveRecording = function(serializedRecording) {
19727 if (!this.isPersistenceEnabled()) return PromisePolyfill.resolve();
19728 var tabId = serializedRecording["tabId"];
19729 if (!tabId) {
19730 console.warn("No tab ID is set, cannot persist recording metadata.");
19731 return PromisePolyfill.resolve();
19732 }
19733 return this.idb.init().then(function() {
19734 return this.idb.setItem(tabId, serializedRecording);
19735 }.bind(this)).catch(this.handleError.bind(this));
19736 };
19737 /**
19738 * @returns {Promise<import('./session-recording').SerializedRecording>}
19739 */
19740 RecordingRegistry.prototype.getActiveRecording = function() {
19741 if (!this.isPersistenceEnabled()) return PromisePolyfill.resolve(null);
19742 return this.idb.init().then(function() {
19743 return this.idb.getItem(this.mixpanelInstance.get_tab_id());
19744 }.bind(this)).then(function(serializedRecording) {
19745 return isRecordingExpired(serializedRecording) ? null : serializedRecording;
19746 }.bind(this)).catch(this.handleError.bind(this));
19747 };
19748 RecordingRegistry.prototype.clearActiveRecording = function() {
19749 if (this.isPersistenceEnabled()) return this.markActiveRecordingExpired();
19750 else return this.deleteActiveRecording();
19751 };
19752 RecordingRegistry.prototype.markActiveRecordingExpired = function() {
19753 return this.getActiveRecording().then(function(serializedRecording) {
19754 if (serializedRecording) {
19755 serializedRecording["maxExpires"] = 0;
19756 return this.setActiveRecording(serializedRecording);
19757 }
19758 }.bind(this)).catch(this.handleError.bind(this));
19759 };
19760 RecordingRegistry.prototype.deleteActiveRecording = function() {
19761 if (this.idb.isInitialized()) return this.idb.removeItem(this.mixpanelInstance.get_tab_id()).catch(this.handleError.bind(this));
19762 else return PromisePolyfill.resolve();
19763 };
19764 /**
19765 * Flush any inactive recordings from the registry to minimize data loss.
19766 * The main idea here is that we can flush remaining rrweb events on the next page load if a tab is closed mid-batch.
19767 */
19768 RecordingRegistry.prototype.flushInactiveRecordings = function() {
19769 if (!this.isPersistenceEnabled()) return PromisePolyfill.resolve([]);
19770 return this.idb.init().then(function() {
19771 return this.idb.getAll();
19772 }.bind(this)).then(function(serializedRecordings) {
19773 var unloadPromises = serializedRecordings.filter(function(serializedRecording) {
19774 return isRecordingExpired(serializedRecording);
19775 }).map(function(serializedRecording) {
19776 return SessionRecording.deserialize(serializedRecording, {
19777 mixpanelInstance: this.mixpanelInstance,
19778 sharedLockStorage: this.sharedLockStorage
19779 }).unloadPersistedData().then(function() {
19780 return this.idb.removeItem(serializedRecording["tabId"]);
19781 }.bind(this)).catch(this.handleError.bind(this));
19782 }.bind(this));
19783 return PromisePolyfill.all(unloadPromises);
19784 }.bind(this)).catch(this.handleError.bind(this));
19785 };
19786 var logger$2 = console_with_prefix("recorder");
19787 /**
19788 * Recorder API: bundles rrweb and and exposes methods to start and stop recordings.
19789 * @param {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
19790 */
19791 var MixpanelRecorder = function(mixpanelInstance, rrwebRecord, sharedLockStorage) {
19792 this.mixpanelInstance = mixpanelInstance;
19793 this.rrwebRecord = rrwebRecord || record;
19794 this.sharedLockStorage = sharedLockStorage;
19795 /**
19796 * @member {import('./registry').RecordingRegistry}
19797 */
19798 this.recordingRegistry = new RecordingRegistry({
19799 mixpanelInstance: this.mixpanelInstance,
19800 errorReporter: logger$2.error,
19801 sharedLockStorage
19802 });
19803 this._flushInactivePromise = this.recordingRegistry.flushInactiveRecordings();
19804 this.activeRecording = null;
19805 this.stopRecordingInProgress = false;
19806 };
19807 MixpanelRecorder.prototype.startRecording = function(options) {
19808 options = options || {};
19809 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
19810 logger$2.log("Recording already in progress, skipping startRecording.");
19811 return;
19812 }
19813 var onIdleTimeout = function() {
19814 logger$2.log("Idle timeout reached, restarting recording.");
19815 this.resetRecording();
19816 }.bind(this);
19817 var onMaxLengthReached = function() {
19818 logger$2.log("Max recording length reached, stopping recording.");
19819 this.resetRecording();
19820 }.bind(this);
19821 var onBatchSent = function() {
19822 this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
19823 this["__flushPromise"] = this.activeRecording.batcher._flushPromise;
19824 }.bind(this);
19825 /**
19826 * @type {import('./session-recording').SessionRecordingOptions}
19827 */
19828 var sessionRecordingOptions = {
19829 mixpanelInstance: this.mixpanelInstance,
19830 onBatchSent,
19831 onIdleTimeout,
19832 onMaxLengthReached,
19833 replayId: _$1.UUID(),
19834 rrwebRecord: this.rrwebRecord,
19835 sharedLockStorage: this.sharedLockStorage
19836 };
19837 if (options.activeSerializedRecording) this.activeRecording = SessionRecording.deserialize(options.activeSerializedRecording, sessionRecordingOptions);
19838 else this.activeRecording = new SessionRecording(sessionRecordingOptions);
19839 this.activeRecording.startRecording(options.shouldStopBatcher);
19840 return this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
19841 };
19842 MixpanelRecorder.prototype.stopRecording = function() {
19843 this.stopRecordingInProgress = true;
19844 return this._stopCurrentRecording(false, true).then(function() {
19845 return this.recordingRegistry.clearActiveRecording();
19846 }.bind(this)).then(function() {
19847 this.stopRecordingInProgress = false;
19848 }.bind(this));
19849 };
19850 MixpanelRecorder.prototype.pauseRecording = function() {
19851 return this._stopCurrentRecording(false);
19852 };
19853 MixpanelRecorder.prototype._stopCurrentRecording = function(skipFlush, disableActiveRecording) {
19854 if (this.activeRecording) {
19855 var stopRecordingPromise = this.activeRecording.stopRecording(skipFlush);
19856 if (disableActiveRecording) this.activeRecording = null;
19857 return stopRecordingPromise;
19858 }
19859 return PromisePolyfill.resolve();
19860 };
19861 MixpanelRecorder.prototype.resumeRecording = function(startNewIfInactive) {
19862 if (this.activeRecording && this.activeRecording.isRrwebStopped()) {
19863 this.activeRecording.startRecording(false);
19864 return PromisePolyfill.resolve(null);
19865 }
19866 return this.recordingRegistry.getActiveRecording().then(function(activeSerializedRecording) {
19867 if (activeSerializedRecording && !this.stopRecordingInProgress) return this.startRecording({ activeSerializedRecording });
19868 else if (startNewIfInactive) return this.startRecording({ shouldStopBatcher: false });
19869 else {
19870 logger$2.log("No resumable recording found.");
19871 return null;
19872 }
19873 }.bind(this));
19874 };
19875 MixpanelRecorder.prototype.resetRecording = function() {
19876 this.stopRecording();
19877 this.startRecording({ shouldStopBatcher: true });
19878 };
19879 MixpanelRecorder.prototype.getActiveReplayId = function() {
19880 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) return this.activeRecording.replayId;
19881 else return null;
19882 };
19883 Object.defineProperty(MixpanelRecorder.prototype, "replayId", { get: function() {
19884 return this.getActiveReplayId();
19885 } });
19886 win["__mp_recorder"] = MixpanelRecorder;
19887 var EV_CHANGE = "change";
19888 var EV_CLICK = "click";
19889 var EV_HASHCHANGE = "hashchange";
19890 var EV_INPUT = "input";
19891 var EV_LOAD = "load";
19892 var EV_MP_LOCATION_CHANGE = "mp_locationchange";
19893 var EV_POPSTATE = "popstate";
19894 var EV_SCROLLEND = "scrollend";
19895 var EV_SCROLL = "scroll";
19896 var EV_SELECT = "select";
19897 var EV_SUBMIT = "submit";
19898 var EV_TOGGLE = "toggle";
19899 var EV_VISIBILITYCHANGE = "visibilitychange";
19900 var CLICK_EVENT_PROPS = [
19901 "clientX",
19902 "clientY",
19903 "offsetX",
19904 "offsetY",
19905 "pageX",
19906 "pageY",
19907 "screenX",
19908 "screenY",
19909 "x",
19910 "y"
19911 ];
19912 var OPT_IN_CLASSES = ["mp-include"];
19913 var OPT_OUT_CLASSES = ["mp-no-track"];
19914 var SENSITIVE_DATA_CLASSES = OPT_OUT_CLASSES.concat(["mp-sensitive"]);
19915 var TRACKED_ATTRS = [
19916 "aria-label",
19917 "aria-labelledby",
19918 "aria-describedby",
19919 "href",
19920 "name",
19921 "role",
19922 "title",
19923 "type"
19924 ];
19925 var INTERACTIVE_ARIA_ROLES = {
19926 "button": true,
19927 "checkbox": true,
19928 "combobox": true,
19929 "grid": true,
19930 "link": true,
19931 "listbox": true,
19932 "menu": true,
19933 "menubar": true,
19934 "menuitem": true,
19935 "menuitemcheckbox": true,
19936 "menuitemradio": true,
19937 "navigation": true,
19938 "option": true,
19939 "radio": true,
19940 "radiogroup": true,
19941 "searchbox": true,
19942 "slider": true,
19943 "spinbutton": true,
19944 "switch": true,
19945 "tab": true,
19946 "tablist": true,
19947 "textbox": true,
19948 "tree": true,
19949 "treegrid": true,
19950 "treeitem": true
19951 };
19952 var ALWAYS_NON_INTERACTIVE_TAGS = {
19953 "base": true,
19954 "head": true,
19955 "html": true,
19956 "link": true,
19957 "meta": true,
19958 "script": true,
19959 "style": true,
19960 "title": true,
19961 "br": true,
19962 "hr": true,
19963 "wbr": true,
19964 "noscript": true,
19965 "picture": true,
19966 "source": true,
19967 "template": true,
19968 "track": true
19969 };
19970 var TEXT_CONTAINER_TAGS = {
19971 "article": true,
19972 "div": true,
19973 "h1": true,
19974 "h2": true,
19975 "h3": true,
19976 "h4": true,
19977 "h5": true,
19978 "h6": true,
19979 "p": true,
19980 "section": true,
19981 "span": true
19982 };
19983 var EVENT_HANDLER_ATTRIBUTES = [
19984 "onclick",
19985 "onmousedown",
19986 "onmouseup",
19987 "onpointerdown",
19988 "onpointerup",
19989 "ontouchend",
19990 "ontouchstart"
19991 ];
19992 var MAX_DEPTH = 5;
19993 var logger$1 = console_with_prefix("autocapture");
19994 function getClasses(el) {
19995 var classes = {};
19996 var classList = getClassName(el).split(" ");
19997 for (var i = 0; i < classList.length; i++) {
19998 var cls = classList[i];
19999 if (cls) classes[cls] = true;
20000 }
20001 return classes;
20002 }
20003 function getClassName(el) {
20004 switch (typeof el.className) {
20005 case "string": return el.className;
20006 case "object": return el.className.baseVal || el.getAttribute("class") || "";
20007 default: return "";
20008 }
20009 }
20010 function getPreviousElementSibling(el) {
20011 if (el.previousElementSibling) return el.previousElementSibling;
20012 else {
20013 do
20014 el = el.previousSibling;
20015 while (el && !isElementNode(el));
20016 return el;
20017 }
20018 }
20019 function getPropertiesFromElement(el, ev, blockAttrsSet, extraAttrs, allowElementCallback, allowSelectors) {
20020 var props = {
20021 "$classes": getClassName(el).split(" "),
20022 "$tag_name": el.tagName.toLowerCase()
20023 };
20024 var elId = el.id;
20025 if (elId) props["$id"] = elId;
20026 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors)) _$1.each(TRACKED_ATTRS.concat(extraAttrs), function(attr) {
20027 if (el.hasAttribute(attr) && !blockAttrsSet[attr]) {
20028 var attrVal = el.getAttribute(attr);
20029 if (shouldTrackValue(attrVal)) props["$attr-" + attr] = attrVal;
20030 }
20031 });
20032 var nthChild = 1;
20033 var nthOfType = 1;
20034 var currentElem = el;
20035 while (currentElem = getPreviousElementSibling(currentElem)) {
20036 nthChild++;
20037 if (currentElem.tagName === el.tagName) nthOfType++;
20038 }
20039 props["$nth_child"] = nthChild;
20040 props["$nth_of_type"] = nthOfType;
20041 return props;
20042 }
20043 function getPropsForDOMEvent(ev, config) {
20044 var allowElementCallback = config.allowElementCallback;
20045 var allowSelectors = config.allowSelectors || [];
20046 var blockAttrs = config.blockAttrs || [];
20047 var blockElementCallback = config.blockElementCallback;
20048 var blockSelectors = config.blockSelectors || [];
20049 var captureTextContent = config.captureTextContent || false;
20050 var captureExtraAttrs = config.captureExtraAttrs || [];
20051 var capturedForHeatMap = config.capturedForHeatMap || false;
20052 var blockAttrsSet = {};
20053 _$1.each(blockAttrs, function(attr) {
20054 blockAttrsSet[attr] = true;
20055 });
20056 var props = null;
20057 var target = typeof ev.target === "undefined" ? ev.srcElement : ev.target;
20058 if (isTextNode(target)) target = target.parentNode;
20059 if (shouldTrackDomEvent(target, ev) && isElementAllowed(target, ev, allowElementCallback, allowSelectors) && !isElementBlocked(target, ev, blockElementCallback, blockSelectors)) {
20060 var targetElementList = [target];
20061 var curEl = target;
20062 while (curEl.parentNode && !isTag(curEl, "body")) {
20063 targetElementList.push(curEl.parentNode);
20064 curEl = curEl.parentNode;
20065 }
20066 var elementsJson = [];
20067 var href;
20068 var explicitNoTrack = false;
20069 _$1.each(targetElementList, function(el) {
20070 var shouldTrackDetails = shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors);
20071 if (!blockAttrsSet["href"] && el.tagName.toLowerCase() === "a") {
20072 href = el.getAttribute("href");
20073 href = shouldTrackDetails && shouldTrackValue(href) && href;
20074 }
20075 if (isElementBlocked(el, ev, blockElementCallback, blockSelectors)) explicitNoTrack = true;
20076 elementsJson.push(getPropertiesFromElement(el, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors));
20077 }, this);
20078 if (!explicitNoTrack) {
20079 var docElement = document$1["documentElement"];
20080 props = {
20081 "$event_type": ev.type,
20082 "$host": win.location.host,
20083 "$pathname": win.location.pathname,
20084 "$elements": elementsJson,
20085 "$el_attr__href": href,
20086 "$viewportHeight": Math.max(docElement["clientHeight"], win["innerHeight"] || 0),
20087 "$viewportWidth": Math.max(docElement["clientWidth"], win["innerWidth"] || 0),
20088 "$pageHeight": document$1["body"]["offsetHeight"] || 0,
20089 "$pageWidth": document$1["body"]["offsetWidth"] || 0
20090 };
20091 _$1.each(captureExtraAttrs, function(attr) {
20092 if (!blockAttrsSet[attr] && target.hasAttribute(attr)) {
20093 var attrVal = target.getAttribute(attr);
20094 if (shouldTrackValue(attrVal)) props["$el_attr__" + attr] = attrVal;
20095 }
20096 });
20097 if (captureTextContent) {
20098 elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
20099 if (elementText && elementText.length) props["$el_text"] = elementText;
20100 }
20101 if (ev.type === EV_CLICK) {
20102 _$1.each(CLICK_EVENT_PROPS, function(prop) {
20103 if (prop in ev) props["$" + prop] = ev[prop];
20104 });
20105 if (capturedForHeatMap) props["$captured_for_heatmap"] = true;
20106 target = guessRealClickTarget(ev);
20107 }
20108 if (captureTextContent) {
20109 var elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
20110 if (elementText && elementText.length) props["$el_text"] = elementText;
20111 }
20112 if (target) {
20113 if (!isElementAllowed(target, ev, allowElementCallback, allowSelectors) || isElementBlocked(target, ev, blockElementCallback, blockSelectors)) return null;
20114 var targetProps = getPropertiesFromElement(target, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors);
20115 props["$target"] = targetProps;
20116 props["$el_classes"] = targetProps["$classes"];
20117 _$1.extend(props, _$1.strip_empty_properties({
20118 "$el_id": targetProps["$id"],
20119 "$el_tag_name": targetProps["$tag_name"]
20120 }));
20121 }
20122 }
20123 }
20124 return props;
20125 }
20126 /**
20127 * Get the direct text content of an element, protecting against sensitive data collection.
20128 * Concats textContent of each of the element's text node children; this avoids potential
20129 * collection of sensitive data that could happen if we used element.textContent and the
20130 * element had sensitive child elements, since element.textContent includes child content.
20131 * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
20132 * @param {Element} el - element to get the text of
20133 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
20134 * @returns {string} the element's direct text content
20135 */
20136 function getSafeText(el, ev, allowElementCallback, allowSelectors) {
20137 var elText = "";
20138 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) && el.childNodes && el.childNodes.length) _$1.each(el.childNodes, function(child) {
20139 if (isTextNode(child) && child.textContent) elText += _$1.trim(child.textContent).split(/(\s+)/).filter(shouldTrackValue).join("").replace(/[\r\n]/g, " ").replace(/[ ]+/g, " ").substring(0, 255);
20140 });
20141 return _$1.trim(elText);
20142 }
20143 function guessRealClickTarget(ev) {
20144 var target = ev.target;
20145 var composedPath = ev["composedPath"]();
20146 for (var i = 0; i < composedPath.length; i++) {
20147 var node = composedPath[i];
20148 if (isTag(node, "a") || isTag(node, "button") || isTag(node, "input") || isTag(node, "select") || node.getAttribute && node.getAttribute("role") === "button") {
20149 target = node;
20150 break;
20151 }
20152 if (node === target) break;
20153 }
20154 return target;
20155 }
20156 function isElementAllowed(el, ev, allowElementCallback, allowSelectors) {
20157 if (allowElementCallback) try {
20158 if (!allowElementCallback(el, ev)) return false;
20159 } catch (err) {
20160 logger$1.critical("Error while checking element in allowElementCallback", err);
20161 return false;
20162 }
20163 if (!allowSelectors.length) return true;
20164 for (var i = 0; i < allowSelectors.length; i++) {
20165 var sel = allowSelectors[i];
20166 try {
20167 if (el["matches"](sel)) return true;
20168 } catch (err) {
20169 logger$1.critical("Error while checking selector: " + sel, err);
20170 }
20171 }
20172 return false;
20173 }
20174 function isElementBlocked(el, ev, blockElementCallback, blockSelectors) {
20175 var i;
20176 if (blockElementCallback) try {
20177 if (blockElementCallback(el, ev)) return true;
20178 } catch (err) {
20179 logger$1.critical("Error while checking element in blockElementCallback", err);
20180 return true;
20181 }
20182 if (blockSelectors && blockSelectors.length) for (i = 0; i < blockSelectors.length; i++) {
20183 var sel = blockSelectors[i];
20184 try {
20185 if (el["matches"](sel)) return true;
20186 } catch (err) {
20187 logger$1.critical("Error while checking selector: " + sel, err);
20188 }
20189 }
20190 var classes = getClasses(el);
20191 for (i = 0; i < OPT_OUT_CLASSES.length; i++) if (classes[OPT_OUT_CLASSES[i]]) return true;
20192 return false;
20193 }
20194 function isElementNode(node) {
20195 return node && node.nodeType === 1;
20196 }
20197 function isTag(el, tag) {
20198 return el && el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
20199 }
20200 function isTextNode(node) {
20201 return node && node.nodeType === 3;
20202 }
20203 function minDOMApisSupported() {
20204 try {
20205 return !!document$1.createElement("div")["matches"];
20206 } catch (err) {
20207 return false;
20208 }
20209 }
20210 function weakSetSupported() {
20211 return typeof WeakSet !== "undefined";
20212 }
20213 function shouldTrackDomEvent(el, ev) {
20214 if (!el || isTag(el, "html") || !isElementNode(el)) return false;
20215 switch (el.tagName.toLowerCase()) {
20216 case "form": return ev.type === EV_SUBMIT;
20217 case "input": if (["button", "submit"].indexOf(el.getAttribute("type")) === -1) return ev.type === EV_CHANGE;
20218 else return ev.type === EV_CLICK;
20219 case "select":
20220 case "textarea": return ev.type === EV_CHANGE;
20221 default: return ev.type === EV_CLICK;
20222 }
20223 }
20224 function shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) {
20225 var i;
20226 if (!isElementAllowed(el, ev, allowElementCallback, allowSelectors)) return false;
20227 for (var curEl = el; curEl.parentNode && !isTag(curEl, "body"); curEl = curEl.parentNode) {
20228 var classes = getClasses(curEl);
20229 for (i = 0; i < SENSITIVE_DATA_CLASSES.length; i++) if (classes[SENSITIVE_DATA_CLASSES[i]]) return false;
20230 }
20231 var elClasses = getClasses(el);
20232 for (i = 0; i < OPT_IN_CLASSES.length; i++) if (elClasses[OPT_IN_CLASSES[i]]) return true;
20233 if (isTag(el, "input") || isTag(el, "select") || isTag(el, "textarea") || el.getAttribute("contenteditable") === "true") return false;
20234 var type = el.type || "";
20235 if (typeof type === "string") switch (type.toLowerCase()) {
20236 case "hidden": return false;
20237 case "password": return false;
20238 }
20239 var name = el.name || el.id || "";
20240 if (typeof name === "string") {
20241 if (/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(name.replace(/[^a-zA-Z0-9]/g, ""))) return false;
20242 }
20243 return true;
20244 }
20245 function shouldTrackValue(value) {
20246 if (value === null || _$1.isUndefined(value)) return false;
20247 if (typeof value === "string") {
20248 value = _$1.trim(value);
20249 if (/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((value || "").replace(/[- ]/g, ""))) return false;
20250 if (/(^\d{3}-?\d{2}-?\d{4}$)/.test(value)) return false;
20251 }
20252 return true;
20253 }
20254 /**
20255 * Creates a cross-browser compatible scroll end function with appropriate event listener.
20256 * For browsers that support scrollend, returns the original function with scrollend event.
20257 * For browsers without scrollend support, returns a debounced function that triggers
20258 * 100ms after the last scroll event to simulate scrollend behavior.
20259 * @param {Function} originalFunction - The function to call when scrolling ends
20260 * @returns {Object} Object containing listener function and eventType string
20261 * @returns {Function} returns.listener - The wrapped function to use as event listener
20262 * @returns {string} returns.eventType - The event type to listen for ('scrollend' or 'scroll')
20263 */
20264 function getPolyfillScrollEndFunction(originalFunction) {
20265 var supportsScrollEnd = "onscrollend" in win;
20266 var polyfillFunction = safewrap(originalFunction);
20267 var polyfillEvent = EV_SCROLLEND;
20268 if (!supportsScrollEnd) {
20269 var scrollTimer = null;
20270 var scrollDelayMs = 100;
20271 polyfillFunction = safewrap(function() {
20272 clearTimeout(scrollTimer);
20273 scrollTimer = setTimeout(originalFunction, scrollDelayMs);
20274 });
20275 polyfillEvent = EV_SCROLL;
20276 }
20277 return {
20278 listener: polyfillFunction,
20279 eventType: polyfillEvent
20280 };
20281 }
20282 function hasInlineEventHandlers(element) {
20283 for (var i = 0; i < EVENT_HANDLER_ATTRIBUTES.length; i++) if (element.hasAttribute(EVENT_HANDLER_ATTRIBUTES[i])) return true;
20284 return false;
20285 }
20286 function hasInteractiveAriaRole(element) {
20287 var role = element.getAttribute("role");
20288 if (!role) return false;
20289 return INTERACTIVE_ARIA_ROLES[role.trim().split(/\s+/)[0].toLowerCase()];
20290 }
20291 function hasAnyInteractivityIndicators(element) {
20292 var tagName = element.tagName.toLowerCase();
20293 if (tagName === "button" || tagName === "input" || tagName === "select" || tagName === "textarea" || tagName === "details" || tagName === "dialog") return true;
20294 if (element.isContentEditable) return true;
20295 if (element.onclick || element.onmousedown || element.onmouseup || element.ontouchstart || element.ontouchend) return true;
20296 if (hasInlineEventHandlers(element)) return true;
20297 if (hasInteractiveAriaRole(element)) return true;
20298 if (tagName === "a" && element.hasAttribute("href")) return true;
20299 if (element.hasAttribute("tabindex")) return true;
20300 return false;
20301 }
20302 function isDefinitelyNonInteractive(element) {
20303 if (!element || !element.tagName) return true;
20304 var tagName = element.tagName.toLowerCase();
20305 if (ALWAYS_NON_INTERACTIVE_TAGS[tagName]) return true;
20306 if (hasAnyInteractivityIndicators(element)) return false;
20307 var parent = element.parentElement;
20308 var depth = 0;
20309 while (parent && depth < MAX_DEPTH) {
20310 if (hasAnyInteractivityIndicators(parent)) return false;
20311 if (parent.getRootNode && parent.getRootNode() !== document$1) {
20312 var root = parent.getRootNode();
20313 if (root.host && hasAnyInteractivityIndicators(root.host)) return false;
20314 }
20315 parent = parent.parentElement;
20316 depth++;
20317 }
20318 if (TEXT_CONTAINER_TAGS[tagName]) return true;
20319 return false;
20320 }
20321 /** @const */ var DEFAULT_RAGE_CLICK_THRESHOLD_PX = 30;
20322 /** @const */ var DEFAULT_RAGE_CLICK_TIMEOUT_MS = 1e3;
20323 /** @const */ var DEFAULT_RAGE_CLICK_CLICK_COUNT = 4;
20324 function RageClickTracker() {
20325 this.clicks = [];
20326 }
20327 RageClickTracker.prototype.isRageClick = function(x, y, options) {
20328 options = options || {};
20329 var thresholdPx = options["threshold_px"] || DEFAULT_RAGE_CLICK_THRESHOLD_PX;
20330 var timeoutMs = options["timeout_ms"] || DEFAULT_RAGE_CLICK_TIMEOUT_MS;
20331 var clickCount = options["click_count"] || DEFAULT_RAGE_CLICK_CLICK_COUNT;
20332 var timestamp = Date.now();
20333 var lastClick = this.clicks[this.clicks.length - 1];
20334 if (lastClick && timestamp - lastClick.timestamp < timeoutMs && Math.sqrt(Math.pow(x - lastClick.x, 2) + Math.pow(y - lastClick.y, 2)) < thresholdPx) {
20335 this.clicks.push({
20336 x,
20337 y,
20338 timestamp
20339 });
20340 if (this.clicks.length >= clickCount) {
20341 this.clicks = [];
20342 return true;
20343 }
20344 } else this.clicks = [{
20345 x,
20346 y,
20347 timestamp
20348 }];
20349 return false;
20350 };
20351 function ShadowDOMObserver(changeCallback, observerConfig) {
20352 this.changeCallback = changeCallback || function() {};
20353 this.observerConfig = observerConfig;
20354 this.observedShadowRoots = null;
20355 this.shadowObservers = [];
20356 }
20357 ShadowDOMObserver.prototype.getEventTarget = function(event) {
20358 if (!this.observedShadowRoots) return;
20359 var path = this.getComposedPath(event);
20360 if (path && path.length) return path[0];
20361 return event["target"] || event["srcElement"];
20362 };
20363 ShadowDOMObserver.prototype.getComposedPath = function(event) {
20364 if ("composedPath" in event) return event["composedPath"]();
20365 return [];
20366 };
20367 ShadowDOMObserver.prototype.observeFromEvent = function(event) {
20368 if (!this.observedShadowRoots) return;
20369 var path = this.getComposedPath(event);
20370 for (var i = 0; i < path.length; i++) {
20371 var element = path[i];
20372 if (element && element.shadowRoot) this.observeShadowRoot(element.shadowRoot);
20373 }
20374 };
20375 ShadowDOMObserver.prototype.observeShadowRoot = function(shadowRoot) {
20376 if (!this.observedShadowRoots || this.observedShadowRoots.has(shadowRoot)) return;
20377 var self = this;
20378 try {
20379 this.observedShadowRoots.add(shadowRoot);
20380 var observer = new window.MutationObserver(function() {
20381 self.changeCallback();
20382 });
20383 observer.observe(shadowRoot, this.observerConfig);
20384 this.shadowObservers.push(observer);
20385 } catch (e) {
20386 logger$1.critical("Error while observing shadow root", e);
20387 }
20388 };
20389 ShadowDOMObserver.prototype.start = function() {
20390 if (this.observedShadowRoots) return;
20391 if (!weakSetSupported()) {
20392 logger$1.critical("Shadow DOM observation unavailable: WeakSet not supported");
20393 return;
20394 }
20395 this.observedShadowRoots = /* @__PURE__ */ new WeakSet();
20396 };
20397 ShadowDOMObserver.prototype.stop = function() {
20398 if (!this.observedShadowRoots) return;
20399 for (var i = 0; i < this.shadowObservers.length; i++) try {
20400 this.shadowObservers[i].disconnect();
20401 } catch (e) {
20402 logger$1.critical("Error while disconnecting shadow DOM observer", e);
20403 }
20404 this.shadowObservers = [];
20405 this.observedShadowRoots = null;
20406 };
20407 /** @const */ var DEFAULT_DEAD_CLICK_TIMEOUT_MS = 500;
20408 /** @const */ var INTERACTION_EVENTS = [
20409 EV_CHANGE,
20410 EV_INPUT,
20411 EV_SUBMIT,
20412 EV_SELECT,
20413 EV_TOGGLE
20414 ];
20415 /** @const */ var LAYOUT_EVENTS = [EV_SCROLLEND];
20416 /** @const */ var NAVIGATION_EVENTS = [EV_HASHCHANGE];
20417 /** @const */ var MUTATION_OBSERVER_CONFIG = {
20418 characterData: true,
20419 childList: true,
20420 subtree: true,
20421 attributes: true,
20422 attributeFilter: [
20423 "style",
20424 "class",
20425 "hidden",
20426 "checked",
20427 "selected",
20428 "value",
20429 "display",
20430 "visibility"
20431 ]
20432 };
20433 function DeadClickTracker(onDeadClickCallback) {
20434 this.eventListeners = [];
20435 this.mutationObserver = null;
20436 this.shadowDOMObserver = null;
20437 this.isTracking = false;
20438 this.lastChangeEventTimestamp = 0;
20439 this.pendingClicks = [];
20440 this.onDeadClickCallback = onDeadClickCallback;
20441 this.processingActive = false;
20442 this.processingTimeout = null;
20443 }
20444 DeadClickTracker.prototype.addClick = function(event) {
20445 var element = this.shadowDOMObserver && this.shadowDOMObserver.getEventTarget(event);
20446 if (!element) element = event["target"] || event["srcElement"];
20447 if (!element || isDefinitelyNonInteractive(element)) return false;
20448 if (this.shadowDOMObserver) this.shadowDOMObserver.observeFromEvent(event);
20449 this.pendingClicks.push({
20450 element,
20451 event,
20452 timestamp: Date.now()
20453 });
20454 return true;
20455 };
20456 DeadClickTracker.prototype.trackClick = function(event, config) {
20457 if (!this.isTracking) return false;
20458 var added = this.addClick(event);
20459 if (added) this.triggerProcessing(config);
20460 return added;
20461 };
20462 DeadClickTracker.prototype.getDeadClicks = function(config) {
20463 if (this.pendingClicks.length === 0) return [];
20464 var timeoutMs = config["timeout_ms"];
20465 var now = Date.now();
20466 var clicksToEvaluate = this.pendingClicks.slice();
20467 this.pendingClicks = [];
20468 var deadClicks = [];
20469 for (var i = 0; i < clicksToEvaluate.length; i++) {
20470 var click = clicksToEvaluate[i];
20471 if (now - click.timestamp >= timeoutMs) {
20472 if (!this.hasChangesAfter(click.timestamp)) deadClicks.push(click);
20473 } else this.pendingClicks.push(click);
20474 }
20475 return deadClicks;
20476 };
20477 DeadClickTracker.prototype.hasChangesAfter = function(timestamp) {
20478 return this.lastChangeEventTimestamp >= timestamp - 100;
20479 };
20480 DeadClickTracker.prototype.recordChangeEvent = function() {
20481 this.lastChangeEventTimestamp = Date.now();
20482 };
20483 DeadClickTracker.prototype.triggerProcessing = function(config) {
20484 if (this.processingActive) return;
20485 this.processingActive = true;
20486 this.processRecursively(config);
20487 };
20488 DeadClickTracker.prototype.processRecursively = function(config) {
20489 if (!this.isTracking || !this.onDeadClickCallback) {
20490 this.processingActive = false;
20491 return;
20492 }
20493 var timeoutMs = config["timeout_ms"];
20494 var self = this;
20495 this.processingTimeout = setTimeout(function() {
20496 if (!self.processingActive) return;
20497 var deadClicks = self.getDeadClicks(config);
20498 for (var i = 0; i < deadClicks.length; i++) self.onDeadClickCallback(deadClicks[i].event);
20499 if (self.pendingClicks.length > 0) self.processRecursively(config);
20500 else self.processingActive = false;
20501 }, timeoutMs);
20502 };
20503 DeadClickTracker.prototype.startTracking = function() {
20504 if (this.isTracking) return;
20505 this.isTracking = true;
20506 var self = this;
20507 INTERACTION_EVENTS.forEach(function(event) {
20508 var handler = function() {
20509 self.recordChangeEvent();
20510 };
20511 document.addEventListener(event, handler, {
20512 capture: true,
20513 passive: true
20514 });
20515 self.eventListeners.push({
20516 target: document,
20517 event,
20518 handler,
20519 options: {
20520 capture: true,
20521 passive: true
20522 }
20523 });
20524 });
20525 NAVIGATION_EVENTS.forEach(function(event) {
20526 var handler = function() {
20527 self.recordChangeEvent();
20528 };
20529 window.addEventListener(event, handler);
20530 self.eventListeners.push({
20531 target: window,
20532 event,
20533 handler
20534 });
20535 });
20536 LAYOUT_EVENTS.forEach(function(event) {
20537 var handler = function() {
20538 self.recordChangeEvent();
20539 };
20540 window.addEventListener(event, handler, { passive: true });
20541 self.eventListeners.push({
20542 target: window,
20543 event,
20544 handler,
20545 options: { passive: true }
20546 });
20547 });
20548 var selectionHandler = function() {
20549 self.recordChangeEvent();
20550 };
20551 document.addEventListener("selectionchange", selectionHandler);
20552 self.eventListeners.push({
20553 target: document,
20554 event: "selectionchange",
20555 handler: selectionHandler
20556 });
20557 if (window.MutationObserver) try {
20558 this.mutationObserver = new window.MutationObserver(function() {
20559 self.recordChangeEvent();
20560 });
20561 this.mutationObserver.observe(document.body || document.documentElement, MUTATION_OBSERVER_CONFIG);
20562 } catch (e) {
20563 logger$1.critical("Error while setting up mutation observer", e);
20564 }
20565 if (window.customElements) try {
20566 this.shadowDOMObserver = new ShadowDOMObserver(function() {
20567 self.recordChangeEvent();
20568 }, MUTATION_OBSERVER_CONFIG);
20569 this.shadowDOMObserver.start();
20570 } catch (e) {
20571 logger$1.critical("Error while setting up shadow DOM observer", e);
20572 this.shadowDOMObserver = null;
20573 }
20574 };
20575 DeadClickTracker.prototype.stopTracking = function() {
20576 if (!this.isTracking) return;
20577 this.isTracking = false;
20578 this.pendingClicks = [];
20579 this.lastChangeEventTimestamp = 0;
20580 this.processingActive = false;
20581 if (this.processingTimeout) {
20582 clearTimeout(this.processingTimeout);
20583 this.processingTimeout = null;
20584 }
20585 for (var i = 0; i < this.eventListeners.length; i++) {
20586 var listener = this.eventListeners[i];
20587 try {
20588 listener.target.removeEventListener(listener.event, listener.handler, listener.options);
20589 } catch (e) {
20590 logger$1.critical("Error while removing event listener", e);
20591 }
20592 }
20593 this.eventListeners = [];
20594 if (this.mutationObserver) {
20595 try {
20596 this.mutationObserver.disconnect();
20597 } catch (e) {
20598 logger$1.critical("Error while disconnecting mutation observer", e);
20599 }
20600 this.mutationObserver = null;
20601 }
20602 if (this.shadowDOMObserver) {
20603 try {
20604 this.shadowDOMObserver.stop();
20605 } catch (e) {
20606 logger$1.critical("Error while stopping shadow DOM observer", e);
20607 }
20608 this.shadowDOMObserver = null;
20609 }
20610 };
20611 var AUTOCAPTURE_CONFIG_KEY = "autocapture";
20612 var LEGACY_PAGEVIEW_CONFIG_KEY = "track_pageview";
20613 var PAGEVIEW_OPTION_FULL_URL = "full-url";
20614 var PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING = "url-with-path-and-query-string";
20615 var PAGEVIEW_OPTION_URL_WITH_PATH = "url-with-path";
20616 var CONFIG_ALLOW_ELEMENT_CALLBACK = "allow_element_callback";
20617 var CONFIG_ALLOW_SELECTORS = "allow_selectors";
20618 var CONFIG_ALLOW_URL_REGEXES = "allow_url_regexes";
20619 var CONFIG_BLOCK_ATTRS = "block_attrs";
20620 var CONFIG_BLOCK_ELEMENT_CALLBACK = "block_element_callback";
20621 var CONFIG_BLOCK_SELECTORS = "block_selectors";
20622 var CONFIG_BLOCK_URL_REGEXES = "block_url_regexes";
20623 var CONFIG_CAPTURE_EXTRA_ATTRS = "capture_extra_attrs";
20624 var CONFIG_CAPTURE_TEXT_CONTENT = "capture_text_content";
20625 var CONFIG_SCROLL_CAPTURE_ALL = "scroll_capture_all";
20626 var CONFIG_SCROLL_CHECKPOINTS = "scroll_depth_percent_checkpoints";
20627 var CONFIG_TRACK_CLICK = "click";
20628 var CONFIG_TRACK_DEAD_CLICK = "dead_click";
20629 var CONFIG_TRACK_INPUT = "input";
20630 var CONFIG_TRACK_PAGEVIEW = "pageview";
20631 var CONFIG_TRACK_RAGE_CLICK = "rage_click";
20632 var CONFIG_TRACK_SCROLL = "scroll";
20633 var CONFIG_TRACK_PAGE_LEAVE = "page_leave";
20634 var CONFIG_TRACK_SUBMIT = "submit";
20635 var CONFIG_DEFAULTS$1 = {};
20636 CONFIG_DEFAULTS$1[CONFIG_ALLOW_SELECTORS] = [];
20637 CONFIG_DEFAULTS$1[CONFIG_ALLOW_URL_REGEXES] = [];
20638 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ATTRS] = [];
20639 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ELEMENT_CALLBACK] = null;
20640 CONFIG_DEFAULTS$1[CONFIG_BLOCK_SELECTORS] = [];
20641 CONFIG_DEFAULTS$1[CONFIG_BLOCK_URL_REGEXES] = [];
20642 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_EXTRA_ATTRS] = [];
20643 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_TEXT_CONTENT] = false;
20644 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CAPTURE_ALL] = false;
20645 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CHECKPOINTS] = [
20646 25,
20647 50,
20648 75,
20649 100
20650 ];
20651 CONFIG_DEFAULTS$1[CONFIG_TRACK_CLICK] = true;
20652 CONFIG_DEFAULTS$1[CONFIG_TRACK_DEAD_CLICK] = true;
20653 CONFIG_DEFAULTS$1[CONFIG_TRACK_INPUT] = true;
20654 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGEVIEW] = PAGEVIEW_OPTION_FULL_URL;
20655 CONFIG_DEFAULTS$1[CONFIG_TRACK_RAGE_CLICK] = true;
20656 CONFIG_DEFAULTS$1[CONFIG_TRACK_SCROLL] = true;
20657 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGE_LEAVE] = false;
20658 CONFIG_DEFAULTS$1[CONFIG_TRACK_SUBMIT] = true;
20659 var DEFAULT_PROPS = { "$mp_autocapture": true };
20660 var MP_EV_CLICK = "$mp_click";
20661 var MP_EV_DEAD_CLICK = "$mp_dead_click";
20662 var MP_EV_INPUT = "$mp_input_change";
20663 var MP_EV_RAGE_CLICK = "$mp_rage_click";
20664 var MP_EV_SCROLL = "$mp_scroll";
20665 var MP_EV_SUBMIT = "$mp_submit";
20666 var MP_EV_PAGE_LEAVE = "$mp_page_leave";
20667 /**
20668 * Autocapture: manages automatic event tracking
20669 * @constructor
20670 */
20671 var Autocapture = function(mp) {
20672 this.mp = mp;
20673 this.maxScrollViewDepth = 0;
20674 this.hasTrackedScrollSession = false;
20675 this.previousScrollHeight = 0;
20676 };
20677 Autocapture.prototype.init = function() {
20678 if (!minDOMApisSupported()) {
20679 logger$1.critical("Autocapture unavailable: missing required DOM APIs");
20680 return;
20681 }
20682 this.initPageListeners();
20683 this.initPageviewTracking();
20684 this.initClickTracking();
20685 this.initDeadClickTracking();
20686 this.initInputTracking();
20687 this.initScrollTracking();
20688 this.initSubmitTracking();
20689 this.initRageClickTracking();
20690 this.initPageLeaveTracking();
20691 };
20692 Autocapture.prototype.getFullConfig = function() {
20693 var autocaptureConfig = this.mp.get_config(AUTOCAPTURE_CONFIG_KEY);
20694 if (!autocaptureConfig) return {};
20695 else if (_$1.isObject(autocaptureConfig)) return _$1.extend({}, CONFIG_DEFAULTS$1, autocaptureConfig);
20696 else return CONFIG_DEFAULTS$1;
20697 };
20698 Autocapture.prototype.getConfig = function(key) {
20699 return this.getFullConfig()[key];
20700 };
20701 Autocapture.prototype.currentUrlBlocked = function() {
20702 var i;
20703 var currentUrl = _$1.info.currentUrl();
20704 var allowUrlRegexes = this.getConfig(CONFIG_ALLOW_URL_REGEXES) || [];
20705 if (allowUrlRegexes.length) {
20706 var allowed = false;
20707 for (i = 0; i < allowUrlRegexes.length; i++) {
20708 var allowRegex = allowUrlRegexes[i];
20709 try {
20710 if (currentUrl.match(allowRegex)) {
20711 allowed = true;
20712 break;
20713 }
20714 } catch (err) {
20715 logger$1.critical("Error while checking block URL regex: " + allowRegex, err);
20716 return true;
20717 }
20718 }
20719 if (!allowed) return true;
20720 }
20721 var blockUrlRegexes = this.getConfig(CONFIG_BLOCK_URL_REGEXES) || [];
20722 if (!blockUrlRegexes || !blockUrlRegexes.length) return false;
20723 for (i = 0; i < blockUrlRegexes.length; i++) try {
20724 if (currentUrl.match(blockUrlRegexes[i])) return true;
20725 } catch (err) {
20726 logger$1.critical("Error while checking block URL regex: " + blockUrlRegexes[i], err);
20727 return true;
20728 }
20729 return false;
20730 };
20731 Autocapture.prototype.pageviewTrackingConfig = function() {
20732 if (this.mp.get_config(AUTOCAPTURE_CONFIG_KEY)) return this.getConfig(CONFIG_TRACK_PAGEVIEW);
20733 else return this.mp.get_config(LEGACY_PAGEVIEW_CONFIG_KEY);
20734 };
20735 Autocapture.prototype.trackDomEvent = function(ev, mpEventName) {
20736 if (this.currentUrlBlocked()) return;
20737 var isCapturedForHeatMap = this.mp.is_recording_heatmap_data() && (mpEventName === MP_EV_CLICK && !this.getConfig(CONFIG_TRACK_CLICK) || mpEventName === MP_EV_RAGE_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK) || mpEventName === MP_EV_DEAD_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK));
20738 var props = getPropsForDOMEvent(ev, {
20739 allowElementCallback: this.getConfig(CONFIG_ALLOW_ELEMENT_CALLBACK),
20740 allowSelectors: this.getConfig(CONFIG_ALLOW_SELECTORS),
20741 blockAttrs: this.getConfig(CONFIG_BLOCK_ATTRS),
20742 blockElementCallback: this.getConfig(CONFIG_BLOCK_ELEMENT_CALLBACK),
20743 blockSelectors: this.getConfig(CONFIG_BLOCK_SELECTORS),
20744 captureExtraAttrs: this.getConfig(CONFIG_CAPTURE_EXTRA_ATTRS),
20745 captureTextContent: this.getConfig(CONFIG_CAPTURE_TEXT_CONTENT),
20746 capturedForHeatMap: isCapturedForHeatMap
20747 });
20748 if (props) {
20749 _$1.extend(props, DEFAULT_PROPS);
20750 this.mp.track(mpEventName, props);
20751 }
20752 };
20753 Autocapture.prototype.initPageListeners = function() {
20754 win.removeEventListener(EV_POPSTATE, this.listenerPopstate);
20755 win.removeEventListener(EV_HASHCHANGE, this.listenerHashchange);
20756 if (!this.pageviewTrackingConfig() && !this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config("record_heatmap_data")) return;
20757 this.listenerPopstate = function() {
20758 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
20759 };
20760 this.listenerHashchange = function() {
20761 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
20762 };
20763 win.addEventListener(EV_POPSTATE, this.listenerPopstate);
20764 win.addEventListener(EV_HASHCHANGE, this.listenerHashchange);
20765 var nativePushState = win.history.pushState;
20766 if (typeof nativePushState === "function") win.history.pushState = function(state, unused, url) {
20767 nativePushState.call(win.history, state, unused, url);
20768 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
20769 };
20770 var nativeReplaceState = win.history.replaceState;
20771 if (typeof nativeReplaceState === "function") win.history.replaceState = function(state, unused, url) {
20772 nativeReplaceState.call(win.history, state, unused, url);
20773 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
20774 };
20775 };
20776 Autocapture.prototype._getClickTrackingConfig = function(configKey) {
20777 var config = this.getConfig(configKey);
20778 if (!config) return null;
20779 if (config === true) return {};
20780 if (typeof config === "object") return config;
20781 return {};
20782 };
20783 Autocapture.prototype._trackPageLeave = function(ev, currentUrl, currentScrollHeight) {
20784 if (this.hasTrackedScrollSession) return;
20785 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.is_recording_heatmap_data()) return;
20786 this.hasTrackedScrollSession = true;
20787 var viewportHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
20788 var scrollPercentage = Math.round(Math.max(this.maxScrollViewDepth - viewportHeight, 0) / (currentScrollHeight - viewportHeight) * 100);
20789 var foldLinePercentage = Math.round(viewportHeight / currentScrollHeight * 100);
20790 if (currentScrollHeight <= viewportHeight) {
20791 scrollPercentage = 100;
20792 foldLinePercentage = 100;
20793 }
20794 var props = _$1.extend({
20795 "$max_scroll_view_depth": this.maxScrollViewDepth,
20796 "$max_scroll_percentage": scrollPercentage,
20797 "$fold_line_percentage": foldLinePercentage,
20798 "$scroll_height": currentScrollHeight,
20799 "$event_type": ev.type,
20800 "$current_url": currentUrl || _$1.info.currentUrl(),
20801 "$viewportHeight": viewportHeight,
20802 "$viewportWidth": Math.max(document$1.documentElement.clientWidth, win.innerWidth || 0),
20803 "$captured_for_heatmap": this.mp.is_recording_heatmap_data()
20804 }, DEFAULT_PROPS);
20805 this.mp.track(MP_EV_PAGE_LEAVE, props, { transport: "sendBeacon" });
20806 };
20807 Autocapture.prototype._initScrollDepthTracking = function() {
20808 win.removeEventListener(EV_SCROLL, this.listenerScrollDepth);
20809 win.removeEventListener(EV_SCROLLEND, this.listenerScrollDepth);
20810 if (!this.mp.get_config("record_heatmap_data")) return;
20811 logger$1.log("Initializing scroll depth tracking");
20812 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
20813 var scrollEndPolyfill = getPolyfillScrollEndFunction(function() {
20814 if (this.currentUrlBlocked()) return;
20815 var scrollViewHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0) + win.scrollY;
20816 if (scrollViewHeight > this.maxScrollViewDepth) this.maxScrollViewDepth = scrollViewHeight;
20817 this.previousScrollHeight = document$1.body.scrollHeight;
20818 }.bind(this));
20819 this.listenerScrollDepth = scrollEndPolyfill.listener;
20820 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScrollDepth);
20821 };
20822 Autocapture.prototype.initClickTracking = function() {
20823 win.removeEventListener(EV_CLICK, this.listenerClick);
20824 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.get_config("record_heatmap_data")) return;
20825 logger$1.log("Initializing click tracking");
20826 this.listenerClick = function(ev) {
20827 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.is_recording_heatmap_data()) return;
20828 this.trackDomEvent(ev, MP_EV_CLICK);
20829 }.bind(this);
20830 win.addEventListener(EV_CLICK, this.listenerClick);
20831 };
20832 Autocapture.prototype.initDeadClickTracking = function() {
20833 if (!this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK) && !this.mp.get_config("record_heatmap_data")) {
20834 this.stopDeadClickTracking();
20835 return;
20836 }
20837 logger$1.log("Initializing dead click tracking");
20838 if (!this._deadClickTracker) {
20839 this._deadClickTracker = new DeadClickTracker(function(deadClickEvent) {
20840 this.trackDomEvent(deadClickEvent, MP_EV_DEAD_CLICK);
20841 }.bind(this));
20842 this._deadClickTracker.startTracking();
20843 }
20844 if (!this.listenerDeadClick) {
20845 this.listenerDeadClick = function(ev) {
20846 var currentDeadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
20847 if (!currentDeadClickConfig && !this.mp.is_recording_heatmap_data()) return;
20848 if (this.currentUrlBlocked()) return;
20849 var normalizedConfig = currentDeadClickConfig || {};
20850 if (!normalizedConfig["timeout_ms"]) normalizedConfig["timeout_ms"] = DEFAULT_DEAD_CLICK_TIMEOUT_MS;
20851 this._deadClickTracker.trackClick(ev, normalizedConfig);
20852 }.bind(this);
20853 win.addEventListener(EV_CLICK, this.listenerDeadClick);
20854 }
20855 };
20856 Autocapture.prototype.initInputTracking = function() {
20857 win.removeEventListener(EV_CHANGE, this.listenerChange);
20858 if (!this.getConfig(CONFIG_TRACK_INPUT)) return;
20859 logger$1.log("Initializing input tracking");
20860 this.listenerChange = function(ev) {
20861 if (!this.getConfig(CONFIG_TRACK_INPUT)) return;
20862 this.trackDomEvent(ev, MP_EV_INPUT);
20863 }.bind(this);
20864 win.addEventListener(EV_CHANGE, this.listenerChange);
20865 };
20866 Autocapture.prototype.initPageviewTracking = function() {
20867 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
20868 if (!this.pageviewTrackingConfig()) return;
20869 logger$1.log("Initializing pageview tracking");
20870 var previousTrackedUrl = "";
20871 var tracked = false;
20872 if (!this.currentUrlBlocked()) tracked = this.mp.track_pageview(DEFAULT_PROPS);
20873 if (tracked) previousTrackedUrl = _$1.info.currentUrl();
20874 this.listenerLocationchange = safewrap(function() {
20875 if (this.currentUrlBlocked()) return;
20876 var currentUrl = _$1.info.currentUrl();
20877 var shouldTrack = false;
20878 var didPathChange = currentUrl.split("#")[0].split("?")[0] !== previousTrackedUrl.split("#")[0].split("?")[0];
20879 var trackPageviewOption = this.pageviewTrackingConfig();
20880 if (trackPageviewOption === PAGEVIEW_OPTION_FULL_URL) shouldTrack = currentUrl !== previousTrackedUrl;
20881 else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING) shouldTrack = currentUrl.split("#")[0] !== previousTrackedUrl.split("#")[0];
20882 else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH) shouldTrack = didPathChange;
20883 if (shouldTrack) {
20884 if (this.mp.track_pageview(DEFAULT_PROPS)) previousTrackedUrl = currentUrl;
20885 if (didPathChange) {
20886 this.lastScrollCheckpoint = 0;
20887 logger$1.log("Path change: re-initializing scroll depth checkpoints");
20888 }
20889 }
20890 }.bind(this));
20891 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
20892 };
20893 Autocapture.prototype.initRageClickTracking = function() {
20894 win.removeEventListener(EV_CLICK, this.listenerRageClick);
20895 if (!this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK) && !this.mp.get_config("record_heatmap_data")) return;
20896 logger$1.log("Initializing rage click tracking");
20897 if (!this._rageClickTracker) this._rageClickTracker = new RageClickTracker();
20898 this.listenerRageClick = function(ev) {
20899 var currentRageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
20900 if (!currentRageClickConfig && !this.mp.is_recording_heatmap_data()) return;
20901 if (this.currentUrlBlocked()) return;
20902 if (this._rageClickTracker.isRageClick(ev["pageX"], ev["pageY"], currentRageClickConfig)) this.trackDomEvent(ev, MP_EV_RAGE_CLICK);
20903 }.bind(this);
20904 win.addEventListener(EV_CLICK, this.listenerRageClick);
20905 };
20906 Autocapture.prototype.initScrollTracking = function() {
20907 win.removeEventListener(EV_SCROLLEND, this.listenerScroll);
20908 win.removeEventListener(EV_SCROLL, this.listenerScroll);
20909 if (!this.getConfig(CONFIG_TRACK_SCROLL)) return;
20910 logger$1.log("Initializing scroll tracking");
20911 this.lastScrollCheckpoint = 0;
20912 var scrollEndPolyfill = getPolyfillScrollEndFunction(function() {
20913 if (!this.getConfig(CONFIG_TRACK_SCROLL)) return;
20914 if (this.currentUrlBlocked()) return;
20915 var shouldTrack = this.getConfig(CONFIG_SCROLL_CAPTURE_ALL);
20916 var scrollCheckpoints = (this.getConfig(CONFIG_SCROLL_CHECKPOINTS) || []).slice().sort(function(a, b) {
20917 return a - b;
20918 });
20919 var scrollTop = win.scrollY;
20920 var props = _$1.extend({ "$scroll_top": scrollTop }, DEFAULT_PROPS);
20921 try {
20922 var scrollHeight = document$1.body.scrollHeight;
20923 var scrollPercentage = Math.round(scrollTop / (scrollHeight - win.innerHeight) * 100);
20924 props["$scroll_height"] = scrollHeight;
20925 props["$scroll_percentage"] = scrollPercentage;
20926 if (scrollPercentage > this.lastScrollCheckpoint) for (var i = 0; i < scrollCheckpoints.length; i++) {
20927 var checkpoint = scrollCheckpoints[i];
20928 if (scrollPercentage >= checkpoint && this.lastScrollCheckpoint < checkpoint) {
20929 props["$scroll_checkpoint"] = checkpoint;
20930 this.lastScrollCheckpoint = checkpoint;
20931 shouldTrack = true;
20932 }
20933 }
20934 } catch (err) {
20935 logger$1.critical("Error while calculating scroll percentage", err);
20936 }
20937 if (shouldTrack) this.mp.track(MP_EV_SCROLL, props);
20938 }.bind(this));
20939 this.listenerScroll = scrollEndPolyfill.listener;
20940 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScroll);
20941 };
20942 Autocapture.prototype.initSubmitTracking = function() {
20943 win.removeEventListener(EV_SUBMIT, this.listenerSubmit);
20944 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) return;
20945 logger$1.log("Initializing submit tracking");
20946 this.listenerSubmit = function(ev) {
20947 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) return;
20948 this.trackDomEvent(ev, MP_EV_SUBMIT);
20949 }.bind(this);
20950 win.addEventListener(EV_SUBMIT, this.listenerSubmit);
20951 };
20952 Autocapture.prototype.initPageLeaveTracking = function() {
20953 document$1.removeEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
20954 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
20955 win.removeEventListener(EV_LOAD, this.listenerPageLoad);
20956 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config("record_heatmap_data")) return;
20957 logger$1.log("Initializing page visibility tracking.");
20958 this._initScrollDepthTracking();
20959 var previousTrackedUrl = _$1.info.currentUrl();
20960 this.listenerPageLoad = function() {
20961 this.previousScrollHeight = document$1.body.scrollHeight;
20962 }.bind(this);
20963 win.addEventListener(EV_LOAD, this.listenerPageLoad);
20964 this.listenerPageLeaveLocationchange = safewrap(function(ev) {
20965 if (this.currentUrlBlocked()) return;
20966 var currentUrl = _$1.info.currentUrl();
20967 if (currentUrl !== previousTrackedUrl) {
20968 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
20969 previousTrackedUrl = currentUrl;
20970 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
20971 this.previousScrollHeight = document$1.body.scrollHeight;
20972 this.hasTrackedScrollSession = false;
20973 }
20974 }.bind(this));
20975 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
20976 this.listenerPageLeaveVisibilitychange = function(ev) {
20977 if (document$1.hidden) this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
20978 }.bind(this);
20979 document$1.addEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
20980 };
20981 Autocapture.prototype.stopDeadClickTracking = function() {
20982 if (this.listenerDeadClick) {
20983 win.removeEventListener(EV_CLICK, this.listenerDeadClick);
20984 this.listenerDeadClick = null;
20985 }
20986 if (this._deadClickTracker) {
20987 this._deadClickTracker.stopTracking();
20988 this._deadClickTracker = null;
20989 }
20990 };
20991 safewrapClass(Autocapture);
20992 var logger = console_with_prefix("flags");
20993 var FLAGS_CONFIG_KEY = "flags";
20994 var CONFIG_CONTEXT = "context";
20995 var CONFIG_DEFAULTS = {};
20996 CONFIG_DEFAULTS[CONFIG_CONTEXT] = {};
20997 /**
20998 * FeatureFlagManager: support for Mixpanel's feature flagging product
20999 * @constructor
21000 */
21001 var FeatureFlagManager = function(initOptions) {
21002 this.fetch = win["fetch"];
21003 this.getFullApiRoute = initOptions.getFullApiRoute;
21004 this.getMpConfig = initOptions.getConfigFunc;
21005 this.setMpConfig = initOptions.setConfigFunc;
21006 this.getMpProperty = initOptions.getPropertyFunc;
21007 this.track = initOptions.trackingFunc;
21008 };
21009 FeatureFlagManager.prototype.init = function() {
21010 if (!this.minApisSupported()) {
21011 logger.critical("Feature Flags unavailable: missing minimum required APIs");
21012 return;
21013 }
21014 this.flags = null;
21015 this.fetchFlags();
21016 this.trackedFeatures = /* @__PURE__ */ new Set();
21017 };
21018 FeatureFlagManager.prototype.getFullConfig = function() {
21019 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
21020 if (!ffConfig) return {};
21021 else if (_$1.isObject(ffConfig)) return _$1.extend({}, CONFIG_DEFAULTS, ffConfig);
21022 else return CONFIG_DEFAULTS;
21023 };
21024 FeatureFlagManager.prototype.getConfig = function(key) {
21025 return this.getFullConfig()[key];
21026 };
21027 FeatureFlagManager.prototype.isSystemEnabled = function() {
21028 return !!this.getMpConfig(FLAGS_CONFIG_KEY);
21029 };
21030 FeatureFlagManager.prototype.updateContext = function(newContext, options) {
21031 if (!this.isSystemEnabled()) {
21032 logger.critical("Feature Flags not enabled, cannot update context");
21033 return Promise.resolve();
21034 }
21035 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
21036 if (!_$1.isObject(ffConfig)) ffConfig = {};
21037 var oldContext = options && options["replace"] ? {} : this.getConfig(CONFIG_CONTEXT);
21038 ffConfig[CONFIG_CONTEXT] = _$1.extend({}, oldContext, newContext);
21039 this.setMpConfig(FLAGS_CONFIG_KEY, ffConfig);
21040 return this.fetchFlags();
21041 };
21042 FeatureFlagManager.prototype.areFlagsReady = function() {
21043 if (!this.isSystemEnabled()) logger.error("Feature Flags not enabled");
21044 return !!this.flags;
21045 };
21046 FeatureFlagManager.prototype.fetchFlags = function() {
21047 if (!this.isSystemEnabled()) return Promise.resolve();
21048 var distinctId = this.getMpProperty("distinct_id");
21049 var deviceId = this.getMpProperty("$device_id");
21050 var traceparent = generateTraceparent();
21051 logger.log("Fetching flags for distinct ID: " + distinctId);
21052 var context = _$1.extend({
21053 "distinct_id": distinctId,
21054 "device_id": deviceId
21055 }, this.getConfig(CONFIG_CONTEXT));
21056 var searchParams = new URLSearchParams();
21057 searchParams.set("context", JSON.stringify(context));
21058 searchParams.set("token", this.getMpConfig("token"));
21059 searchParams.set("mp_lib", "web");
21060 searchParams.set("$lib_version", Config.LIB_VERSION);
21061 var url = this.getFullApiRoute() + "?" + searchParams.toString();
21062 this._fetchInProgressStartTime = Date.now();
21063 this.fetchPromise = this.fetch.call(win, url, {
21064 "method": "GET",
21065 "headers": {
21066 "Authorization": "Basic " + btoa(this.getMpConfig("token") + ":"),
21067 "traceparent": traceparent
21068 }
21069 }).then(function(response) {
21070 this.markFetchComplete();
21071 return response.json().then(function(responseBody) {
21072 var responseFlags = responseBody["flags"];
21073 if (!responseFlags) throw new Error("No flags in API response");
21074 var flags = /* @__PURE__ */ new Map();
21075 _$1.each(responseFlags, function(data, key) {
21076 flags.set(key, {
21077 "key": data["variant_key"],
21078 "value": data["variant_value"],
21079 "experiment_id": data["experiment_id"],
21080 "is_experiment_active": data["is_experiment_active"],
21081 "is_qa_tester": data["is_qa_tester"]
21082 });
21083 });
21084 this.flags = flags;
21085 this._traceparent = traceparent;
21086 }.bind(this)).catch(function(error) {
21087 this.markFetchComplete();
21088 logger.error(error);
21089 }.bind(this));
21090 }.bind(this)).catch(function(error) {
21091 this.markFetchComplete();
21092 logger.error(error);
21093 }.bind(this));
21094 return this.fetchPromise;
21095 };
21096 FeatureFlagManager.prototype.markFetchComplete = function() {
21097 if (!this._fetchInProgressStartTime) {
21098 logger.error("Fetch in progress started time not set, cannot mark fetch complete");
21099 return;
21100 }
21101 this._fetchStartTime = this._fetchInProgressStartTime;
21102 this._fetchCompleteTime = Date.now();
21103 this._fetchLatency = this._fetchCompleteTime - this._fetchStartTime;
21104 this._fetchInProgressStartTime = null;
21105 };
21106 FeatureFlagManager.prototype.getVariant = function(featureName, fallback) {
21107 if (!this.fetchPromise) return new Promise(function(resolve) {
21108 logger.critical("Feature Flags not initialized");
21109 resolve(fallback);
21110 });
21111 return this.fetchPromise.then(function() {
21112 return this.getVariantSync(featureName, fallback);
21113 }.bind(this)).catch(function(error) {
21114 logger.error(error);
21115 return fallback;
21116 });
21117 };
21118 FeatureFlagManager.prototype.getVariantSync = function(featureName, fallback) {
21119 if (!this.areFlagsReady()) {
21120 logger.log("Flags not loaded yet");
21121 return fallback;
21122 }
21123 var feature = this.flags.get(featureName);
21124 if (!feature) {
21125 logger.log("No flag found: \"" + featureName + "\"");
21126 return fallback;
21127 }
21128 this.trackFeatureCheck(featureName, feature);
21129 return feature;
21130 };
21131 FeatureFlagManager.prototype.getVariantValue = function(featureName, fallbackValue) {
21132 return this.getVariant(featureName, { "value": fallbackValue }).then(function(feature) {
21133 return feature["value"];
21134 }).catch(function(error) {
21135 logger.error(error);
21136 return fallbackValue;
21137 });
21138 };
21139 FeatureFlagManager.prototype.getFeatureData = function(featureName, fallbackValue) {
21140 logger.critical("mixpanel.flags.get_feature_data() is deprecated and will be removed in a future release. Use mixpanel.flags.get_variant_value() instead.");
21141 return this.getVariantValue(featureName, fallbackValue);
21142 };
21143 FeatureFlagManager.prototype.getVariantValueSync = function(featureName, fallbackValue) {
21144 return this.getVariantSync(featureName, { "value": fallbackValue })["value"];
21145 };
21146 FeatureFlagManager.prototype.isEnabled = function(featureName, fallbackValue) {
21147 return this.getVariantValue(featureName).then(function() {
21148 return this.isEnabledSync(featureName, fallbackValue);
21149 }.bind(this)).catch(function(error) {
21150 logger.error(error);
21151 return fallbackValue;
21152 });
21153 };
21154 FeatureFlagManager.prototype.isEnabledSync = function(featureName, fallbackValue) {
21155 fallbackValue = fallbackValue || false;
21156 var val = this.getVariantValueSync(featureName, fallbackValue);
21157 if (val !== true && val !== false) {
21158 logger.error("Feature flag \"" + featureName + "\" value: " + val + " is not a boolean; returning fallback value: " + fallbackValue);
21159 val = fallbackValue;
21160 }
21161 return val;
21162 };
21163 FeatureFlagManager.prototype.trackFeatureCheck = function(featureName, feature) {
21164 if (this.trackedFeatures.has(featureName)) return;
21165 this.trackedFeatures.add(featureName);
21166 var trackingProperties = {
21167 "Experiment name": featureName,
21168 "Variant name": feature["key"],
21169 "$experiment_type": "feature_flag",
21170 "Variant fetch start time": new Date(this._fetchStartTime).toISOString(),
21171 "Variant fetch complete time": new Date(this._fetchCompleteTime).toISOString(),
21172 "Variant fetch latency (ms)": this._fetchLatency,
21173 "Variant fetch traceparent": this._traceparent
21174 };
21175 if (feature["experiment_id"] !== "undefined") trackingProperties["$experiment_id"] = feature["experiment_id"];
21176 if (feature["is_experiment_active"] !== "undefined") trackingProperties["$is_experiment_active"] = feature["is_experiment_active"];
21177 if (feature["is_qa_tester"] !== "undefined") trackingProperties["$is_qa_tester"] = feature["is_qa_tester"];
21178 this.track("$experiment_started", trackingProperties);
21179 };
21180 FeatureFlagManager.prototype.minApisSupported = function() {
21181 return !!this.fetch && typeof Promise !== "undefined" && typeof Map !== "undefined" && typeof Set !== "undefined";
21182 };
21183 safewrapClass(FeatureFlagManager);
21184 FeatureFlagManager.prototype["are_flags_ready"] = FeatureFlagManager.prototype.areFlagsReady;
21185 FeatureFlagManager.prototype["get_variant"] = FeatureFlagManager.prototype.getVariant;
21186 FeatureFlagManager.prototype["get_variant_sync"] = FeatureFlagManager.prototype.getVariantSync;
21187 FeatureFlagManager.prototype["get_variant_value"] = FeatureFlagManager.prototype.getVariantValue;
21188 FeatureFlagManager.prototype["get_variant_value_sync"] = FeatureFlagManager.prototype.getVariantValueSync;
21189 FeatureFlagManager.prototype["is_enabled"] = FeatureFlagManager.prototype.isEnabled;
21190 FeatureFlagManager.prototype["is_enabled_sync"] = FeatureFlagManager.prototype.isEnabledSync;
21191 FeatureFlagManager.prototype["update_context"] = FeatureFlagManager.prototype.updateContext;
21192 FeatureFlagManager.prototype["get_feature_data"] = FeatureFlagManager.prototype.getFeatureData;
21193 /**
21194 * DomTracker Object
21195 * @constructor
21196 */
21197 var DomTracker = function() {};
21198 DomTracker.prototype.create_properties = function() {};
21199 DomTracker.prototype.event_handler = function() {};
21200 DomTracker.prototype.after_track_handler = function() {};
21201 DomTracker.prototype.init = function(mixpanel_instance) {
21202 this.mp = mixpanel_instance;
21203 return this;
21204 };
21205 /**
21206 * @param {Object|string} query
21207 * @param {string} event_name
21208 * @param {Object=} properties
21209 * @param {function=} user_callback
21210 */
21211 DomTracker.prototype.track = function(query, event_name, properties, user_callback) {
21212 var that = this;
21213 var elements = _$1.dom_query(query);
21214 if (elements.length === 0) {
21215 console$1.error("The DOM query (" + query + ") returned 0 elements");
21216 return;
21217 }
21218 _$1.each(elements, function(element) {
21219 _$1.register_event(element, this.override_event, function(e) {
21220 var options = {};
21221 var props = that.create_properties(properties, this);
21222 var timeout = that.mp.get_config("track_links_timeout");
21223 that.event_handler(e, this, options);
21224 window.setTimeout(that.track_callback(user_callback, props, options, true), timeout);
21225 that.mp.track(event_name, props, that.track_callback(user_callback, props, options));
21226 });
21227 }, this);
21228 return true;
21229 };
21230 /**
21231 * @param {function} user_callback
21232 * @param {Object} props
21233 * @param {boolean=} timeout_occured
21234 */
21235 DomTracker.prototype.track_callback = function(user_callback, props, options, timeout_occured) {
21236 timeout_occured = timeout_occured || false;
21237 var that = this;
21238 return function() {
21239 if (options.callback_fired) return;
21240 options.callback_fired = true;
21241 if (user_callback && user_callback(timeout_occured, props) === false) return;
21242 that.after_track_handler(props, options, timeout_occured);
21243 };
21244 };
21245 DomTracker.prototype.create_properties = function(properties, element) {
21246 var props;
21247 if (typeof properties === "function") props = properties(element);
21248 else props = _$1.extend({}, properties);
21249 return props;
21250 };
21251 /**
21252 * LinkTracker Object
21253 * @constructor
21254 * @extends DomTracker
21255 */
21256 var LinkTracker = function() {
21257 this.override_event = "click";
21258 };
21259 _$1.inherit(LinkTracker, DomTracker);
21260 LinkTracker.prototype.create_properties = function(properties, element) {
21261 var props = LinkTracker.superclass.create_properties.apply(this, arguments);
21262 if (element.href) props["url"] = element.href;
21263 return props;
21264 };
21265 LinkTracker.prototype.event_handler = function(evt, element, options) {
21266 options.new_tab = evt.which === 2 || evt.metaKey || evt.ctrlKey || element.target === "_blank";
21267 options.href = element.href;
21268 if (!options.new_tab) evt.preventDefault();
21269 };
21270 LinkTracker.prototype.after_track_handler = function(props, options) {
21271 if (options.new_tab) return;
21272 setTimeout(function() {
21273 window.location = options.href;
21274 }, 0);
21275 };
21276 /**
21277 * FormTracker Object
21278 * @constructor
21279 * @extends DomTracker
21280 */
21281 var FormTracker = function() {
21282 this.override_event = "submit";
21283 };
21284 _$1.inherit(FormTracker, DomTracker);
21285 FormTracker.prototype.event_handler = function(evt, element, options) {
21286 options.element = element;
21287 evt.preventDefault();
21288 };
21289 FormTracker.prototype.after_track_handler = function(props, options) {
21290 setTimeout(function() {
21291 options.element.submit();
21292 }, 0);
21293 };
21294 /** @const */ var SET_ACTION = "$set";
21295 /** @const */ var SET_ONCE_ACTION = "$set_once";
21296 /** @const */ var UNSET_ACTION = "$unset";
21297 /** @const */ var ADD_ACTION = "$add";
21298 /** @const */ var APPEND_ACTION = "$append";
21299 /** @const */ var UNION_ACTION = "$union";
21300 /** @const */ var REMOVE_ACTION = "$remove";
21301 /** @const */ var DELETE_ACTION = "$delete";
21302 var apiActions = {
21303 set_action: function(prop, to) {
21304 var data = {};
21305 var $set = {};
21306 if (_$1.isObject(prop)) _$1.each(prop, function(v, k) {
21307 if (!this._is_reserved_property(k)) $set[k] = v;
21308 }, this);
21309 else $set[prop] = to;
21310 data[SET_ACTION] = $set;
21311 return data;
21312 },
21313 unset_action: function(prop) {
21314 var data = {};
21315 var $unset = [];
21316 if (!_$1.isArray(prop)) prop = [prop];
21317 _$1.each(prop, function(k) {
21318 if (!this._is_reserved_property(k)) $unset.push(k);
21319 }, this);
21320 data[UNSET_ACTION] = $unset;
21321 return data;
21322 },
21323 set_once_action: function(prop, to) {
21324 var data = {};
21325 var $set_once = {};
21326 if (_$1.isObject(prop)) _$1.each(prop, function(v, k) {
21327 if (!this._is_reserved_property(k)) $set_once[k] = v;
21328 }, this);
21329 else $set_once[prop] = to;
21330 data[SET_ONCE_ACTION] = $set_once;
21331 return data;
21332 },
21333 union_action: function(list_name, values) {
21334 var data = {};
21335 var $union = {};
21336 if (_$1.isObject(list_name)) _$1.each(list_name, function(v, k) {
21337 if (!this._is_reserved_property(k)) $union[k] = _$1.isArray(v) ? v : [v];
21338 }, this);
21339 else $union[list_name] = _$1.isArray(values) ? values : [values];
21340 data[UNION_ACTION] = $union;
21341 return data;
21342 },
21343 append_action: function(list_name, value) {
21344 var data = {};
21345 var $append = {};
21346 if (_$1.isObject(list_name)) _$1.each(list_name, function(v, k) {
21347 if (!this._is_reserved_property(k)) $append[k] = v;
21348 }, this);
21349 else $append[list_name] = value;
21350 data[APPEND_ACTION] = $append;
21351 return data;
21352 },
21353 remove_action: function(list_name, value) {
21354 var data = {};
21355 var $remove = {};
21356 if (_$1.isObject(list_name)) _$1.each(list_name, function(v, k) {
21357 if (!this._is_reserved_property(k)) $remove[k] = v;
21358 }, this);
21359 else $remove[list_name] = value;
21360 data[REMOVE_ACTION] = $remove;
21361 return data;
21362 },
21363 delete_action: function() {
21364 var data = {};
21365 data[DELETE_ACTION] = "";
21366 return data;
21367 }
21368 };
21369 /**
21370 * Mixpanel Group Object
21371 * @constructor
21372 */
21373 var MixpanelGroup = function() {};
21374 _$1.extend(MixpanelGroup.prototype, apiActions);
21375 MixpanelGroup.prototype._init = function(mixpanel_instance, group_key, group_id) {
21376 this._mixpanel = mixpanel_instance;
21377 this._group_key = group_key;
21378 this._group_id = group_id;
21379 };
21380 /**
21381 * Set properties on a group.
21382 *
21383 * ### Usage:
21384 *
21385 * mixpanel.get_group('company', 'mixpanel').set('Location', '405 Howard');
21386 *
21387 * // or set multiple properties at once
21388 * mixpanel.get_group('company', 'mixpanel').set({
21389 * 'Location': '405 Howard',
21390 * 'Founded' : 2009,
21391 * });
21392 * // properties can be strings, integers, dates, or lists
21393 *
21394 * @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.
21395 * @param {*} [to] A value to set on the given property name
21396 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21397 */
21398 MixpanelGroup.prototype.set = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
21399 var data = this.set_action(prop, to);
21400 if (_$1.isObject(prop)) callback = to;
21401 return this._send_request(data, callback);
21402 });
21403 /**
21404 * Set properties on a group, only if they do not yet exist.
21405 * This will not overwrite previous group property values, unlike
21406 * group.set().
21407 *
21408 * ### Usage:
21409 *
21410 * mixpanel.get_group('company', 'mixpanel').set_once('Location', '405 Howard');
21411 *
21412 * // or set multiple properties at once
21413 * mixpanel.get_group('company', 'mixpanel').set_once({
21414 * 'Location': '405 Howard',
21415 * 'Founded' : 2009,
21416 * });
21417 * // properties can be strings, integers, lists or dates
21418 *
21419 * @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.
21420 * @param {*} [to] A value to set on the given property name
21421 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21422 */
21423 MixpanelGroup.prototype.set_once = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
21424 var data = this.set_once_action(prop, to);
21425 if (_$1.isObject(prop)) callback = to;
21426 return this._send_request(data, callback);
21427 });
21428 /**
21429 * Unset properties on a group permanently.
21430 *
21431 * ### Usage:
21432 *
21433 * mixpanel.get_group('company', 'mixpanel').unset('Founded');
21434 *
21435 * @param {String} prop The name of the property.
21436 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21437 */
21438 MixpanelGroup.prototype.unset = addOptOutCheckMixpanelGroup(function(prop, callback) {
21439 var data = this.unset_action(prop);
21440 return this._send_request(data, callback);
21441 });
21442 /**
21443 * Merge a given list with a list-valued group property, excluding duplicate values.
21444 *
21445 * ### Usage:
21446 *
21447 * // merge a value to a list, creating it if needed
21448 * mixpanel.get_group('company', 'mixpanel').union('Location', ['San Francisco', 'London']);
21449 *
21450 * @param {String} list_name Name of the property.
21451 * @param {Array} values Values to merge with the given property
21452 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21453 */
21454 MixpanelGroup.prototype.union = addOptOutCheckMixpanelGroup(function(list_name, values, callback) {
21455 if (_$1.isObject(list_name)) callback = values;
21456 var data = this.union_action(list_name, values);
21457 return this._send_request(data, callback);
21458 });
21459 /**
21460 * Permanently delete a group.
21461 *
21462 * ### Usage:
21463 *
21464 * mixpanel.get_group('company', 'mixpanel').delete();
21465 *
21466 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21467 */
21468 MixpanelGroup.prototype["delete"] = addOptOutCheckMixpanelGroup(function(callback) {
21469 var data = this.delete_action();
21470 return this._send_request(data, callback);
21471 });
21472 /**
21473 * Remove a property from a group. The value will be ignored if doesn't exist.
21474 *
21475 * ### Usage:
21476 *
21477 * mixpanel.get_group('company', 'mixpanel').remove('Location', 'London');
21478 *
21479 * @param {String} list_name Name of the property.
21480 * @param {Object} value Value to remove from the given group property
21481 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21482 */
21483 MixpanelGroup.prototype.remove = addOptOutCheckMixpanelGroup(function(list_name, value, callback) {
21484 var data = this.remove_action(list_name, value);
21485 return this._send_request(data, callback);
21486 });
21487 MixpanelGroup.prototype._send_request = function(data, callback) {
21488 data["$group_key"] = this._group_key;
21489 data["$group_id"] = this._group_id;
21490 data["$token"] = this._get_config("token");
21491 var date_encoded_data = _$1.encodeDates(data);
21492 return this._mixpanel._track_or_batch({
21493 type: "groups",
21494 data: date_encoded_data,
21495 endpoint: this._mixpanel.get_api_host("groups") + "/" + this._get_config("api_routes")["groups"],
21496 batcher: this._mixpanel.request_batchers.groups
21497 }, callback);
21498 };
21499 MixpanelGroup.prototype._is_reserved_property = function(prop) {
21500 return prop === "$group_key" || prop === "$group_id";
21501 };
21502 MixpanelGroup.prototype._get_config = function(conf) {
21503 return this._mixpanel.get_config(conf);
21504 };
21505 MixpanelGroup.prototype.toString = function() {
21506 return this._mixpanel.toString() + ".group." + this._group_key + "." + this._group_id;
21507 };
21508 MixpanelGroup.prototype["remove"] = MixpanelGroup.prototype.remove;
21509 MixpanelGroup.prototype["set"] = MixpanelGroup.prototype.set;
21510 MixpanelGroup.prototype["set_once"] = MixpanelGroup.prototype.set_once;
21511 MixpanelGroup.prototype["union"] = MixpanelGroup.prototype.union;
21512 MixpanelGroup.prototype["unset"] = MixpanelGroup.prototype.unset;
21513 MixpanelGroup.prototype["toString"] = MixpanelGroup.prototype.toString;
21514 /**
21515 * Mixpanel People Object
21516 * @constructor
21517 */
21518 var MixpanelPeople = function() {};
21519 _$1.extend(MixpanelPeople.prototype, apiActions);
21520 MixpanelPeople.prototype._init = function(mixpanel_instance) {
21521 this._mixpanel = mixpanel_instance;
21522 };
21523 MixpanelPeople.prototype.set = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
21524 var data = this.set_action(prop, to);
21525 if (_$1.isObject(prop)) callback = to;
21526 if (this._get_config("save_referrer")) this._mixpanel["persistence"].update_referrer_info(document.referrer);
21527 data[SET_ACTION] = _$1.extend({}, _$1.info.people_properties(), data[SET_ACTION]);
21528 return this._send_request(data, callback);
21529 });
21530 MixpanelPeople.prototype.set_once = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
21531 var data = this.set_once_action(prop, to);
21532 if (_$1.isObject(prop)) callback = to;
21533 return this._send_request(data, callback);
21534 });
21535 MixpanelPeople.prototype.unset = addOptOutCheckMixpanelPeople(function(prop, callback) {
21536 var data = this.unset_action(prop);
21537 return this._send_request(data, callback);
21538 });
21539 MixpanelPeople.prototype.increment = addOptOutCheckMixpanelPeople(function(prop, by, callback) {
21540 var data = {};
21541 var $add = {};
21542 if (_$1.isObject(prop)) {
21543 _$1.each(prop, function(v, k) {
21544 if (!this._is_reserved_property(k)) if (isNaN(parseFloat(v))) {
21545 console$1.error("Invalid increment value passed to mixpanel.people.increment - must be a number");
21546 return;
21547 } else $add[k] = v;
21548 }, this);
21549 callback = by;
21550 } else {
21551 if (_$1.isUndefined(by)) by = 1;
21552 $add[prop] = by;
21553 }
21554 data[ADD_ACTION] = $add;
21555 return this._send_request(data, callback);
21556 });
21557 MixpanelPeople.prototype.append = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
21558 if (_$1.isObject(list_name)) callback = value;
21559 var data = this.append_action(list_name, value);
21560 return this._send_request(data, callback);
21561 });
21562 MixpanelPeople.prototype.remove = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
21563 if (_$1.isObject(list_name)) callback = value;
21564 var data = this.remove_action(list_name, value);
21565 return this._send_request(data, callback);
21566 });
21567 MixpanelPeople.prototype.union = addOptOutCheckMixpanelPeople(function(list_name, values, callback) {
21568 if (_$1.isObject(list_name)) callback = values;
21569 var data = this.union_action(list_name, values);
21570 return this._send_request(data, callback);
21571 });
21572 MixpanelPeople.prototype.track_charge = addOptOutCheckMixpanelPeople(function() {
21573 console$1.error("mixpanel.people.track_charge() is deprecated and no longer has any effect.");
21574 });
21575 MixpanelPeople.prototype.clear_charges = function(callback) {
21576 return this.set("$transactions", [], callback);
21577 };
21578 MixpanelPeople.prototype.delete_user = function() {
21579 if (!this._identify_called()) {
21580 console$1.error("mixpanel.people.delete_user() requires you to call identify() first");
21581 return;
21582 }
21583 var data = { "$delete": this._mixpanel.get_distinct_id() };
21584 return this._send_request(data);
21585 };
21586 MixpanelPeople.prototype.toString = function() {
21587 return this._mixpanel.toString() + ".people";
21588 };
21589 MixpanelPeople.prototype._send_request = function(data, callback) {
21590 data["$token"] = this._get_config("token");
21591 data["$distinct_id"] = this._mixpanel.get_distinct_id();
21592 var device_id = this._mixpanel.get_property("$device_id");
21593 var user_id = this._mixpanel.get_property("$user_id");
21594 var had_persisted_distinct_id = this._mixpanel.get_property("$had_persisted_distinct_id");
21595 if (device_id) data["$device_id"] = device_id;
21596 if (user_id) data["$user_id"] = user_id;
21597 if (had_persisted_distinct_id) data["$had_persisted_distinct_id"] = had_persisted_distinct_id;
21598 var date_encoded_data = _$1.encodeDates(data);
21599 if (!this._identify_called()) {
21600 this._enqueue(data);
21601 if (!_$1.isUndefined(callback)) if (this._get_config("verbose")) callback({
21602 status: -1,
21603 error: null
21604 });
21605 else callback(-1);
21606 return _$1.truncate(date_encoded_data, 255);
21607 }
21608 return this._mixpanel._track_or_batch({
21609 type: "people",
21610 data: date_encoded_data,
21611 endpoint: this._mixpanel.get_api_host("people") + "/" + this._get_config("api_routes")["engage"],
21612 batcher: this._mixpanel.request_batchers.people
21613 }, callback);
21614 };
21615 MixpanelPeople.prototype._get_config = function(conf_var) {
21616 return this._mixpanel.get_config(conf_var);
21617 };
21618 MixpanelPeople.prototype._identify_called = function() {
21619 return this._mixpanel._flags.identify_called === true;
21620 };
21621 MixpanelPeople.prototype._enqueue = function(data) {
21622 if (SET_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(SET_ACTION, data);
21623 else if (SET_ONCE_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(SET_ONCE_ACTION, data);
21624 else if (UNSET_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(UNSET_ACTION, data);
21625 else if (ADD_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(ADD_ACTION, data);
21626 else if (APPEND_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(APPEND_ACTION, data);
21627 else if (REMOVE_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(REMOVE_ACTION, data);
21628 else if (UNION_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(UNION_ACTION, data);
21629 else console$1.error("Invalid call to _enqueue():", data);
21630 };
21631 MixpanelPeople.prototype._flush_one_queue = function(action, action_method, callback, queue_to_params_fn) {
21632 var _this = this;
21633 var queued_data = _$1.extend({}, this._mixpanel["persistence"].load_queue(action));
21634 var action_params = queued_data;
21635 if (!_$1.isUndefined(queued_data) && _$1.isObject(queued_data) && !_$1.isEmptyObject(queued_data)) {
21636 _this._mixpanel["persistence"]._pop_from_people_queue(action, queued_data);
21637 _this._mixpanel["persistence"].save();
21638 if (queue_to_params_fn) action_params = queue_to_params_fn(queued_data);
21639 action_method.call(_this, action_params, function(response, data) {
21640 if (response === 0) _this._mixpanel["persistence"]._add_to_people_queue(action, queued_data);
21641 if (!_$1.isUndefined(callback)) callback(response, data);
21642 });
21643 }
21644 };
21645 MixpanelPeople.prototype._flush = function(_set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback) {
21646 var _this = this;
21647 this._flush_one_queue(SET_ACTION, this.set, _set_callback);
21648 this._flush_one_queue(SET_ONCE_ACTION, this.set_once, _set_once_callback);
21649 this._flush_one_queue(UNSET_ACTION, this.unset, _unset_callback, function(queue) {
21650 return _$1.keys(queue);
21651 });
21652 this._flush_one_queue(ADD_ACTION, this.increment, _add_callback);
21653 this._flush_one_queue(UNION_ACTION, this.union, _union_callback);
21654 var $append_queue = this._mixpanel["persistence"].load_queue(APPEND_ACTION);
21655 if (!_$1.isUndefined($append_queue) && _$1.isArray($append_queue) && $append_queue.length) {
21656 var $append_item;
21657 var append_callback = function(response, data) {
21658 if (response === 0) _this._mixpanel["persistence"]._add_to_people_queue(APPEND_ACTION, $append_item);
21659 if (!_$1.isUndefined(_append_callback)) _append_callback(response, data);
21660 };
21661 for (var i = $append_queue.length - 1; i >= 0; i--) {
21662 $append_queue = this._mixpanel["persistence"].load_queue(APPEND_ACTION);
21663 $append_item = $append_queue.pop();
21664 _this._mixpanel["persistence"].save();
21665 if (!_$1.isEmptyObject($append_item)) _this.append($append_item, append_callback);
21666 }
21667 }
21668 var $remove_queue = this._mixpanel["persistence"].load_queue(REMOVE_ACTION);
21669 if (!_$1.isUndefined($remove_queue) && _$1.isArray($remove_queue) && $remove_queue.length) {
21670 var $remove_item;
21671 var remove_callback = function(response, data) {
21672 if (response === 0) _this._mixpanel["persistence"]._add_to_people_queue(REMOVE_ACTION, $remove_item);
21673 if (!_$1.isUndefined(_remove_callback)) _remove_callback(response, data);
21674 };
21675 for (var j = $remove_queue.length - 1; j >= 0; j--) {
21676 $remove_queue = this._mixpanel["persistence"].load_queue(REMOVE_ACTION);
21677 $remove_item = $remove_queue.pop();
21678 _this._mixpanel["persistence"].save();
21679 if (!_$1.isEmptyObject($remove_item)) _this.remove($remove_item, remove_callback);
21680 }
21681 }
21682 };
21683 MixpanelPeople.prototype._is_reserved_property = function(prop) {
21684 return prop === "$distinct_id" || prop === "$token" || prop === "$device_id" || prop === "$user_id" || prop === "$had_persisted_distinct_id";
21685 };
21686 MixpanelPeople.prototype["set"] = MixpanelPeople.prototype.set;
21687 MixpanelPeople.prototype["set_once"] = MixpanelPeople.prototype.set_once;
21688 MixpanelPeople.prototype["unset"] = MixpanelPeople.prototype.unset;
21689 MixpanelPeople.prototype["increment"] = MixpanelPeople.prototype.increment;
21690 MixpanelPeople.prototype["append"] = MixpanelPeople.prototype.append;
21691 MixpanelPeople.prototype["remove"] = MixpanelPeople.prototype.remove;
21692 MixpanelPeople.prototype["union"] = MixpanelPeople.prototype.union;
21693 MixpanelPeople.prototype["track_charge"] = MixpanelPeople.prototype.track_charge;
21694 MixpanelPeople.prototype["clear_charges"] = MixpanelPeople.prototype.clear_charges;
21695 MixpanelPeople.prototype["delete_user"] = MixpanelPeople.prototype.delete_user;
21696 MixpanelPeople.prototype["toString"] = MixpanelPeople.prototype.toString;
21697 /** @const */ var SET_QUEUE_KEY = "__mps";
21698 /** @const */ var SET_ONCE_QUEUE_KEY = "__mpso";
21699 /** @const */ var UNSET_QUEUE_KEY = "__mpus";
21700 /** @const */ var ADD_QUEUE_KEY = "__mpa";
21701 /** @const */ var APPEND_QUEUE_KEY = "__mpap";
21702 /** @const */ var REMOVE_QUEUE_KEY = "__mpr";
21703 /** @const */ var UNION_QUEUE_KEY = "__mpu";
21704 /** @const */ var PEOPLE_DISTINCT_ID_KEY = "$people_distinct_id";
21705 /** @const */ var ALIAS_ID_KEY = "__alias";
21706 /** @const */ var EVENT_TIMERS_KEY = "__timers";
21707 /** @const */ var RESERVED_PROPERTIES = [
21708 SET_QUEUE_KEY,
21709 SET_ONCE_QUEUE_KEY,
21710 UNSET_QUEUE_KEY,
21711 ADD_QUEUE_KEY,
21712 APPEND_QUEUE_KEY,
21713 REMOVE_QUEUE_KEY,
21714 UNION_QUEUE_KEY,
21715 PEOPLE_DISTINCT_ID_KEY,
21716 ALIAS_ID_KEY,
21717 EVENT_TIMERS_KEY
21718 ];
21719 /**
21720 * Mixpanel Persistence Object
21721 * @constructor
21722 */
21723 var MixpanelPersistence = function(config) {
21724 this["props"] = {};
21725 this.campaign_params_saved = false;
21726 if (config["persistence_name"]) this.name = "mp_" + config["persistence_name"];
21727 else this.name = "mp_" + config["token"] + "_mixpanel";
21728 var storage_type = config["persistence"];
21729 if (storage_type !== "cookie" && storage_type !== "localStorage") {
21730 console$1.critical("Unknown persistence type " + storage_type + "; falling back to cookie");
21731 storage_type = config["persistence"] = "cookie";
21732 }
21733 if (storage_type === "localStorage" && _$1.localStorage.is_supported()) this.storage = _$1.localStorage;
21734 else this.storage = _$1.cookie;
21735 this.load();
21736 this.update_config(config);
21737 this.upgrade();
21738 this.save();
21739 };
21740 MixpanelPersistence.prototype.properties = function() {
21741 var p = {};
21742 this.load();
21743 _$1.each(this["props"], function(v, k) {
21744 if (!_$1.include(RESERVED_PROPERTIES, k)) p[k] = v;
21745 });
21746 return p;
21747 };
21748 MixpanelPersistence.prototype.load = function() {
21749 if (this.disabled) return;
21750 var entry = this.storage.parse(this.name);
21751 if (entry) this["props"] = _$1.extend({}, entry);
21752 };
21753 MixpanelPersistence.prototype.upgrade = function() {
21754 var old_cookie;
21755 var old_localstorage;
21756 if (this.storage === _$1.localStorage) {
21757 old_cookie = _$1.cookie.parse(this.name);
21758 _$1.cookie.remove(this.name);
21759 _$1.cookie.remove(this.name, true);
21760 if (old_cookie) this.register_once(old_cookie);
21761 } else if (this.storage === _$1.cookie) {
21762 old_localstorage = _$1.localStorage.parse(this.name);
21763 _$1.localStorage.remove(this.name);
21764 if (old_localstorage) this.register_once(old_localstorage);
21765 }
21766 };
21767 MixpanelPersistence.prototype.save = function() {
21768 if (this.disabled) return;
21769 this.storage.set(this.name, JSONStringify(this["props"]), this.expire_days, this.cross_subdomain, this.secure, this.cross_site, this.cookie_domain);
21770 };
21771 MixpanelPersistence.prototype.load_prop = function(key) {
21772 this.load();
21773 return this["props"][key];
21774 };
21775 MixpanelPersistence.prototype.remove = function() {
21776 this.storage.remove(this.name, false, this.cookie_domain);
21777 this.storage.remove(this.name, true, this.cookie_domain);
21778 };
21779 MixpanelPersistence.prototype.clear = function() {
21780 this.remove();
21781 this["props"] = {};
21782 };
21783 /**
21784 * @param {Object} props
21785 * @param {*=} default_value
21786 * @param {number=} days
21787 */
21788 MixpanelPersistence.prototype.register_once = function(props, default_value, days) {
21789 if (_$1.isObject(props)) {
21790 if (typeof default_value === "undefined") default_value = "None";
21791 this.expire_days = typeof days === "undefined" ? this.default_expiry : days;
21792 this.load();
21793 _$1.each(props, function(val, prop) {
21794 if (!this["props"].hasOwnProperty(prop) || this["props"][prop] === default_value) this["props"][prop] = val;
21795 }, this);
21796 this.save();
21797 return true;
21798 }
21799 return false;
21800 };
21801 /**
21802 * @param {Object} props
21803 * @param {number=} days
21804 */
21805 MixpanelPersistence.prototype.register = function(props, days) {
21806 if (_$1.isObject(props)) {
21807 this.expire_days = typeof days === "undefined" ? this.default_expiry : days;
21808 this.load();
21809 _$1.extend(this["props"], props);
21810 this.save();
21811 return true;
21812 }
21813 return false;
21814 };
21815 MixpanelPersistence.prototype.unregister = function(prop) {
21816 this.load();
21817 if (prop in this["props"]) {
21818 delete this["props"][prop];
21819 this.save();
21820 }
21821 };
21822 MixpanelPersistence.prototype.update_search_keyword = function(referrer) {
21823 this.register(_$1.info.searchInfo(referrer));
21824 };
21825 MixpanelPersistence.prototype.update_referrer_info = function(referrer) {
21826 this.register_once({
21827 "$initial_referrer": referrer || "$direct",
21828 "$initial_referring_domain": _$1.info.referringDomain(referrer) || "$direct"
21829 }, "");
21830 };
21831 MixpanelPersistence.prototype.get_referrer_info = function() {
21832 return _$1.strip_empty_properties({
21833 "$initial_referrer": this["props"]["$initial_referrer"],
21834 "$initial_referring_domain": this["props"]["$initial_referring_domain"]
21835 });
21836 };
21837 MixpanelPersistence.prototype.update_config = function(config) {
21838 this.default_expiry = this.expire_days = config["cookie_expiration"];
21839 this.set_disabled(config["disable_persistence"]);
21840 this.set_cookie_domain(config["cookie_domain"]);
21841 this.set_cross_site(config["cross_site_cookie"]);
21842 this.set_cross_subdomain(config["cross_subdomain_cookie"]);
21843 this.set_secure(config["secure_cookie"]);
21844 };
21845 MixpanelPersistence.prototype.set_disabled = function(disabled) {
21846 this.disabled = disabled;
21847 if (this.disabled) this.remove();
21848 else this.save();
21849 };
21850 MixpanelPersistence.prototype.set_cookie_domain = function(cookie_domain) {
21851 if (cookie_domain !== this.cookie_domain) {
21852 this.remove();
21853 this.cookie_domain = cookie_domain;
21854 this.save();
21855 }
21856 };
21857 MixpanelPersistence.prototype.set_cross_site = function(cross_site) {
21858 if (cross_site !== this.cross_site) {
21859 this.cross_site = cross_site;
21860 this.remove();
21861 this.save();
21862 }
21863 };
21864 MixpanelPersistence.prototype.set_cross_subdomain = function(cross_subdomain) {
21865 if (cross_subdomain !== this.cross_subdomain) {
21866 this.cross_subdomain = cross_subdomain;
21867 this.remove();
21868 this.save();
21869 }
21870 };
21871 MixpanelPersistence.prototype.get_cross_subdomain = function() {
21872 return this.cross_subdomain;
21873 };
21874 MixpanelPersistence.prototype.set_secure = function(secure) {
21875 if (secure !== this.secure) {
21876 this.secure = secure ? true : false;
21877 this.remove();
21878 this.save();
21879 }
21880 };
21881 MixpanelPersistence.prototype._add_to_people_queue = function(queue, data) {
21882 var q_key = this._get_queue_key(queue);
21883 var q_data = data[queue];
21884 var set_q = this._get_or_create_queue(SET_ACTION);
21885 var set_once_q = this._get_or_create_queue(SET_ONCE_ACTION);
21886 var unset_q = this._get_or_create_queue(UNSET_ACTION);
21887 var add_q = this._get_or_create_queue(ADD_ACTION);
21888 var union_q = this._get_or_create_queue(UNION_ACTION);
21889 var remove_q = this._get_or_create_queue(REMOVE_ACTION, []);
21890 var append_q = this._get_or_create_queue(APPEND_ACTION, []);
21891 if (q_key === SET_QUEUE_KEY) {
21892 _$1.extend(set_q, q_data);
21893 this._pop_from_people_queue(ADD_ACTION, q_data);
21894 this._pop_from_people_queue(UNION_ACTION, q_data);
21895 this._pop_from_people_queue(UNSET_ACTION, q_data);
21896 } else if (q_key === SET_ONCE_QUEUE_KEY) {
21897 _$1.each(q_data, function(v, k) {
21898 if (!(k in set_once_q)) set_once_q[k] = v;
21899 });
21900 this._pop_from_people_queue(UNSET_ACTION, q_data);
21901 } else if (q_key === UNSET_QUEUE_KEY) _$1.each(q_data, function(prop) {
21902 _$1.each([
21903 set_q,
21904 set_once_q,
21905 add_q,
21906 union_q
21907 ], function(enqueued_obj) {
21908 if (prop in enqueued_obj) delete enqueued_obj[prop];
21909 });
21910 _$1.each(append_q, function(append_obj) {
21911 if (prop in append_obj) delete append_obj[prop];
21912 });
21913 unset_q[prop] = true;
21914 });
21915 else if (q_key === ADD_QUEUE_KEY) {
21916 _$1.each(q_data, function(v, k) {
21917 if (k in set_q) set_q[k] += v;
21918 else {
21919 if (!(k in add_q)) add_q[k] = 0;
21920 add_q[k] += v;
21921 }
21922 }, this);
21923 this._pop_from_people_queue(UNSET_ACTION, q_data);
21924 } else if (q_key === UNION_QUEUE_KEY) {
21925 _$1.each(q_data, function(v, k) {
21926 if (_$1.isArray(v)) {
21927 if (!(k in union_q)) union_q[k] = [];
21928 _$1.each(v, function(item) {
21929 if (!_$1.include(union_q[k], item)) union_q[k].push(item);
21930 });
21931 }
21932 });
21933 this._pop_from_people_queue(UNSET_ACTION, q_data);
21934 } else if (q_key === REMOVE_QUEUE_KEY) {
21935 remove_q.push(q_data);
21936 this._pop_from_people_queue(APPEND_ACTION, q_data);
21937 } else if (q_key === APPEND_QUEUE_KEY) {
21938 append_q.push(q_data);
21939 this._pop_from_people_queue(UNSET_ACTION, q_data);
21940 }
21941 console$1.log("MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):");
21942 console$1.log(data);
21943 this.save();
21944 };
21945 MixpanelPersistence.prototype._pop_from_people_queue = function(queue, data) {
21946 var q = this["props"][this._get_queue_key(queue)];
21947 if (!_$1.isUndefined(q)) _$1.each(data, function(v, k) {
21948 if (queue === APPEND_ACTION || queue === REMOVE_ACTION) _$1.each(q, function(queued_action) {
21949 if (queued_action[k] === v) delete queued_action[k];
21950 });
21951 else delete q[k];
21952 }, this);
21953 };
21954 MixpanelPersistence.prototype.load_queue = function(queue) {
21955 return this.load_prop(this._get_queue_key(queue));
21956 };
21957 MixpanelPersistence.prototype._get_queue_key = function(queue) {
21958 if (queue === SET_ACTION) return SET_QUEUE_KEY;
21959 else if (queue === SET_ONCE_ACTION) return SET_ONCE_QUEUE_KEY;
21960 else if (queue === UNSET_ACTION) return UNSET_QUEUE_KEY;
21961 else if (queue === ADD_ACTION) return ADD_QUEUE_KEY;
21962 else if (queue === APPEND_ACTION) return APPEND_QUEUE_KEY;
21963 else if (queue === REMOVE_ACTION) return REMOVE_QUEUE_KEY;
21964 else if (queue === UNION_ACTION) return UNION_QUEUE_KEY;
21965 else console$1.error("Invalid queue:", queue);
21966 };
21967 MixpanelPersistence.prototype._get_or_create_queue = function(queue, default_val) {
21968 var key = this._get_queue_key(queue);
21969 default_val = _$1.isUndefined(default_val) ? {} : default_val;
21970 return this["props"][key] || (this["props"][key] = default_val);
21971 };
21972 MixpanelPersistence.prototype.set_event_timer = function(event_name, timestamp) {
21973 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
21974 timers[event_name] = timestamp;
21975 this["props"][EVENT_TIMERS_KEY] = timers;
21976 this.save();
21977 };
21978 MixpanelPersistence.prototype.remove_event_timer = function(event_name) {
21979 var timestamp = (this.load_prop(EVENT_TIMERS_KEY) || {})[event_name];
21980 if (!_$1.isUndefined(timestamp)) {
21981 delete this["props"][EVENT_TIMERS_KEY][event_name];
21982 this.save();
21983 }
21984 return timestamp;
21985 };
21986 var init_type;
21987 var load_extra_bundle = function(src, _onload) {
21988 throw new Error(src + " not available in this build.");
21989 };
21990 var mixpanel_master;
21991 var INIT_MODULE = 0;
21992 var INIT_SNIPPET = 1;
21993 var IDENTITY_FUNC = function(x) {
21994 return x;
21995 };
21996 /** @const */ var PRIMARY_INSTANCE_NAME = "mixpanel";
21997 /** @const */ var PAYLOAD_TYPE_BASE64 = "base64";
21998 /** @const */ var PAYLOAD_TYPE_JSON = "json";
21999 /** @const */ var DEVICE_ID_PREFIX = "$device:";
22000 var USE_XHR = win.XMLHttpRequest && "withCredentials" in new XMLHttpRequest();
22001 var ENQUEUE_REQUESTS = !USE_XHR && userAgent.indexOf("MSIE") === -1 && userAgent.indexOf("Mozilla") === -1;
22002 var sendBeacon = null;
22003 if (navigator["sendBeacon"]) sendBeacon = function() {
22004 return navigator["sendBeacon"].apply(navigator, arguments);
22005 };
22006 var DEFAULT_API_ROUTES = {
22007 "track": "track/",
22008 "engage": "engage/",
22009 "groups": "groups/",
22010 "record": "record/",
22011 "flags": "flags/"
22012 };
22013 var DEFAULT_CONFIG = {
22014 "api_host": "https://api-js.mixpanel.com",
22015 "api_hosts": {},
22016 "api_routes": DEFAULT_API_ROUTES,
22017 "api_extra_query_params": {},
22018 "api_method": "POST",
22019 "api_transport": "XHR",
22020 "api_payload_format": PAYLOAD_TYPE_BASE64,
22021 "app_host": "https://mixpanel.com",
22022 "autocapture": false,
22023 "cdn": "https://cdn.mxpnl.com",
22024 "cross_site_cookie": false,
22025 "cross_subdomain_cookie": true,
22026 "error_reporter": NOOP_FUNC,
22027 "flags": false,
22028 "persistence": "cookie",
22029 "persistence_name": "",
22030 "cookie_domain": "",
22031 "cookie_name": "",
22032 "loaded": NOOP_FUNC,
22033 "mp_loader": null,
22034 "track_marketing": true,
22035 "track_pageview": false,
22036 "skip_first_touch_marketing": false,
22037 "store_google": true,
22038 "stop_utm_persistence": false,
22039 "save_referrer": true,
22040 "test": false,
22041 "verbose": false,
22042 "img": false,
22043 "debug": false,
22044 "track_links_timeout": 300,
22045 "cookie_expiration": 365,
22046 "upgrade": false,
22047 "disable_persistence": false,
22048 "disable_cookie": false,
22049 "secure_cookie": false,
22050 "ip": true,
22051 "opt_out_tracking_by_default": false,
22052 "opt_out_persistence_by_default": false,
22053 "opt_out_tracking_persistence_type": "localStorage",
22054 "opt_out_tracking_cookie_prefix": null,
22055 "property_blacklist": [],
22056 "xhr_headers": {},
22057 "ignore_dnt": false,
22058 "batch_requests": true,
22059 "batch_size": 50,
22060 "batch_flush_interval_ms": 5e3,
22061 "batch_request_timeout_ms": 9e4,
22062 "batch_autostart": true,
22063 "hooks": {},
22064 "record_block_class": /* @__PURE__ */ new RegExp("^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$"),
22065 "record_block_selector": "img, video, audio",
22066 "record_canvas": false,
22067 "record_collect_fonts": false,
22068 "record_heatmap_data": false,
22069 "record_idle_timeout_ms": 1800 * 1e3,
22070 "record_mask_text_class": /* @__PURE__ */ new RegExp("^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$"),
22071 "record_mask_text_selector": "*",
22072 "record_max_ms": MAX_RECORDING_MS,
22073 "record_min_ms": 0,
22074 "record_sessions_percent": 0,
22075 "recorder_src": "https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js"
22076 };
22077 var DOM_LOADED = false;
22078 /**
22079 * Mixpanel Library Object
22080 * @constructor
22081 */
22082 var MixpanelLib = function() {};
22083 /**
22084 * create_mplib(token:string, config:object, name:string)
22085 *
22086 * This function is used by the init method of MixpanelLib objects
22087 * as well as the main initializer at the end of the JSLib (that
22088 * initializes document.mixpanel as well as any additional instances
22089 * declared before this file has loaded).
22090 */
22091 var create_mplib = function(token, config, name) {
22092 var instance;
22093 var target = name === PRIMARY_INSTANCE_NAME ? mixpanel_master : mixpanel_master[name];
22094 if (target && init_type === INIT_MODULE) instance = target;
22095 else {
22096 if (target && !_$1.isArray(target)) {
22097 console$1.error("You have already initialized " + name);
22098 return;
22099 }
22100 instance = new MixpanelLib();
22101 }
22102 instance._cached_groups = {};
22103 instance._init(token, config, name);
22104 instance["people"] = new MixpanelPeople();
22105 instance["people"]._init(instance);
22106 if (!instance.get_config("skip_first_touch_marketing")) {
22107 var utm_params = _$1.info.campaignParams(null);
22108 var initial_utm_params = {};
22109 var has_utm = false;
22110 _$1.each(utm_params, function(utm_value, utm_key) {
22111 initial_utm_params["initial_" + utm_key] = utm_value;
22112 if (utm_value) has_utm = true;
22113 });
22114 if (has_utm) instance["people"].set_once(initial_utm_params);
22115 }
22116 Config.DEBUG = Config.DEBUG || instance.get_config("debug");
22117 if (!_$1.isUndefined(target) && _$1.isArray(target)) {
22118 instance._execute_array.call(instance["people"], target["people"]);
22119 instance._execute_array(target);
22120 }
22121 return instance;
22122 };
22123 /**
22124 * This function initializes a new instance of the Mixpanel tracking object.
22125 * All new instances are added to the main mixpanel object as sub properties (such as
22126 * mixpanel.library_name) and also returned by this function. To define a
22127 * second instance on the page, you would call:
22128 *
22129 * mixpanel.init('new token', { your: 'config' }, 'library_name');
22130 *
22131 * and use it like so:
22132 *
22133 * mixpanel.library_name.track(...);
22134 *
22135 * @param {String} token Your Mixpanel API token
22136 * @param {Object} [config] A dictionary of config options to override. <a href="https://github.com/mixpanel/mixpanel-js/blob/v2.46.0/src/mixpanel-core.js#L88-L127">See a list of default config options</a>.
22137 * @param {String} [name] The name for the new mixpanel instance that you want created
22138 */
22139 MixpanelLib.prototype.init = function(token, config, name) {
22140 if (_$1.isUndefined(name)) {
22141 this.report_error("You must name your new library: init(token, config, name)");
22142 return;
22143 }
22144 if (name === PRIMARY_INSTANCE_NAME) {
22145 this.report_error("You must initialize the main mixpanel object right after you include the Mixpanel js snippet");
22146 return;
22147 }
22148 var instance = create_mplib(token, config, name);
22149 mixpanel_master[name] = instance;
22150 instance._loaded();
22151 return instance;
22152 };
22153 MixpanelLib.prototype._init = function(token, config, name) {
22154 config = config || {};
22155 this["__loaded"] = true;
22156 this["config"] = {};
22157 var variable_features = {};
22158 if (!("api_payload_format" in config)) {
22159 if ((config["api_host"] || DEFAULT_CONFIG["api_host"]).match(/\.mixpanel\.com/)) variable_features["api_payload_format"] = PAYLOAD_TYPE_JSON;
22160 }
22161 this.set_config(_$1.extend({}, DEFAULT_CONFIG, variable_features, config, {
22162 "name": name,
22163 "token": token,
22164 "callback_fn": (name === PRIMARY_INSTANCE_NAME ? name : PRIMARY_INSTANCE_NAME + "." + name) + "._jsc"
22165 }));
22166 this["_jsc"] = NOOP_FUNC;
22167 this.__dom_loaded_queue = [];
22168 this.__request_queue = [];
22169 this.__disabled_events = [];
22170 this._flags = {
22171 "disable_all_events": false,
22172 "identify_called": false
22173 };
22174 this.request_batchers = {};
22175 this._batch_requests = this.get_config("batch_requests");
22176 if (this._batch_requests) if (!_$1.localStorage.is_supported(true) || !USE_XHR) {
22177 this._batch_requests = false;
22178 console$1.log("Turning off Mixpanel request-queueing; needs XHR and localStorage support");
22179 _$1.each(this.get_batcher_configs(), function(batcher_config) {
22180 console$1.log("Clearing batch queue " + batcher_config.queue_key);
22181 _$1.localStorage.remove(batcher_config.queue_key);
22182 });
22183 } else {
22184 this.init_batchers();
22185 if (sendBeacon && win.addEventListener) {
22186 var flush_on_unload = _$1.bind(function() {
22187 if (!this.request_batchers.events.stopped) this.request_batchers.events.flush({ unloading: true });
22188 }, this);
22189 win.addEventListener("pagehide", function(ev) {
22190 if (ev["persisted"]) flush_on_unload();
22191 });
22192 win.addEventListener("visibilitychange", function() {
22193 if (document$1["visibilityState"] === "hidden") flush_on_unload();
22194 });
22195 }
22196 }
22197 this["persistence"] = this["cookie"] = new MixpanelPersistence(this["config"]);
22198 this.unpersisted_superprops = {};
22199 this._gdpr_init();
22200 var uuid = _$1.UUID();
22201 if (!this.get_distinct_id()) this.register_once({
22202 "distinct_id": DEVICE_ID_PREFIX + uuid,
22203 "$device_id": uuid
22204 }, "");
22205 this.flags = new FeatureFlagManager({
22206 getFullApiRoute: _$1.bind(function() {
22207 return this.get_api_host("flags") + "/" + this.get_config("api_routes")["flags"];
22208 }, this),
22209 getConfigFunc: _$1.bind(this.get_config, this),
22210 setConfigFunc: _$1.bind(this.set_config, this),
22211 getPropertyFunc: _$1.bind(this.get_property, this),
22212 trackingFunc: _$1.bind(this.track, this)
22213 });
22214 this.flags.init();
22215 this["flags"] = this.flags;
22216 this.autocapture = new Autocapture(this);
22217 this.autocapture.init();
22218 this._init_tab_id();
22219 this._check_and_start_session_recording();
22220 };
22221 /**
22222 * Assigns a unique UUID to this tab / window by leveraging sessionStorage.
22223 * This is primarily used for session recording, where data must be isolated to the current tab.
22224 */
22225 MixpanelLib.prototype._init_tab_id = function() {
22226 if (this.get_config("disable_persistence")) console$1.log("Tab ID initialization skipped due to disable_persistence config");
22227 else if (_$1.sessionStorage.is_supported()) try {
22228 var key_suffix = this.get_config("name") + "_" + this.get_config("token");
22229 var tab_id_key = "mp_tab_id_" + key_suffix;
22230 var should_generate_new_tab_id_key = "mp_gen_new_tab_id_" + key_suffix;
22231 if (_$1.sessionStorage.get(should_generate_new_tab_id_key) || !_$1.sessionStorage.get(tab_id_key)) _$1.sessionStorage.set(tab_id_key, "$tab-" + _$1.UUID());
22232 _$1.sessionStorage.set(should_generate_new_tab_id_key, "1");
22233 this.tab_id = _$1.sessionStorage.get(tab_id_key);
22234 win.addEventListener("beforeunload", function() {
22235 _$1.sessionStorage.remove(should_generate_new_tab_id_key);
22236 });
22237 } catch (err) {
22238 this.report_error("Error initializing tab id", err);
22239 }
22240 else this.report_error("Session storage is not supported, cannot keep track of unique tab ID.");
22241 };
22242 MixpanelLib.prototype.get_tab_id = function() {
22243 return this.tab_id || null;
22244 };
22245 MixpanelLib.prototype._should_load_recorder = function() {
22246 if (this.get_config("disable_persistence")) {
22247 console$1.log("Load recorder check skipped due to disable_persistence config");
22248 return Promise.resolve(false);
22249 }
22250 var recording_registry_idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
22251 var tab_id = this.get_tab_id();
22252 return recording_registry_idb.init().then(function() {
22253 return recording_registry_idb.getAll();
22254 }).then(function(recordings) {
22255 for (var i = 0; i < recordings.length; i++) if (isRecordingExpired(recordings[i]) || recordings[i]["tabId"] === tab_id) return true;
22256 return false;
22257 }).catch(_$1.bind(function(err) {
22258 this.report_error("Error checking recording registry", err);
22259 }, this));
22260 };
22261 MixpanelLib.prototype._check_and_start_session_recording = addOptOutCheckMixpanelLib(function(force_start) {
22262 if (!win["MutationObserver"]) {
22263 console$1.critical("Browser does not support MutationObserver; skipping session recording");
22264 return;
22265 }
22266 var loadRecorder = _$1.bind(function(startNewIfInactive) {
22267 var handleLoadedRecorder = _$1.bind(function() {
22268 this._recorder = this._recorder || new win["__mp_recorder"](this);
22269 this._recorder["resumeRecording"](startNewIfInactive);
22270 }, this);
22271 if (_$1.isUndefined(win["__mp_recorder"])) load_extra_bundle(this.get_config("recorder_src"), handleLoadedRecorder);
22272 else handleLoadedRecorder();
22273 }, this);
22274 /**
22275 * If the user is sampled or start_session_recording is called, we always load the recorder since it's guaranteed a recording should start.
22276 * Otherwise, if the recording registry has any records then it's likely there's a recording in progress or orphaned data that needs to be flushed.
22277 */
22278 var is_sampled = this.get_config("record_sessions_percent") > 0 && Math.random() * 100 <= this.get_config("record_sessions_percent");
22279 if (force_start || is_sampled) loadRecorder(true);
22280 else this._should_load_recorder().then(function(shouldLoad) {
22281 if (shouldLoad) loadRecorder(false);
22282 });
22283 });
22284 MixpanelLib.prototype.start_session_recording = function() {
22285 this._check_and_start_session_recording(true);
22286 };
22287 MixpanelLib.prototype.stop_session_recording = function() {
22288 if (this._recorder) return this._recorder["stopRecording"]();
22289 return Promise.resolve();
22290 };
22291 MixpanelLib.prototype.pause_session_recording = function() {
22292 if (this._recorder) return this._recorder["pauseRecording"]();
22293 return Promise.resolve();
22294 };
22295 MixpanelLib.prototype.resume_session_recording = function() {
22296 if (this._recorder) return this._recorder["resumeRecording"]();
22297 return Promise.resolve();
22298 };
22299 MixpanelLib.prototype.is_recording_heatmap_data = function() {
22300 return this._get_session_replay_id() && this.get_config("record_heatmap_data");
22301 };
22302 MixpanelLib.prototype.get_session_recording_properties = function() {
22303 var props = {};
22304 var replay_id = this._get_session_replay_id();
22305 if (replay_id) props["$mp_replay_id"] = replay_id;
22306 return props;
22307 };
22308 MixpanelLib.prototype.get_session_replay_url = function() {
22309 var replay_url = null;
22310 var replay_id = this._get_session_replay_id();
22311 if (replay_id) replay_url = "https://mixpanel.com/projects/replay-redirect?" + _$1.HTTPBuildQuery({
22312 "replay_id": replay_id,
22313 "distinct_id": this.get_distinct_id(),
22314 "token": this.get_config("token")
22315 });
22316 return replay_url;
22317 };
22318 MixpanelLib.prototype._get_session_replay_id = function() {
22319 var replay_id = null;
22320 if (this._recorder) replay_id = this._recorder["replayId"];
22321 return replay_id || null;
22322 };
22323 MixpanelLib.prototype.__get_recorder = function() {
22324 return this._recorder;
22325 };
22326 MixpanelLib.prototype._loaded = function() {
22327 this.get_config("loaded")(this);
22328 this._set_default_superprops();
22329 this["people"].set_once(this["persistence"].get_referrer_info());
22330 if (this.get_config("store_google") && this.get_config("stop_utm_persistence")) {
22331 var utm_params = _$1.info.campaignParams(null);
22332 _$1.each(utm_params, function(_utm_value, utm_key) {
22333 this.unregister(utm_key);
22334 }.bind(this));
22335 }
22336 };
22337 MixpanelLib.prototype._set_default_superprops = function() {
22338 this["persistence"].update_search_keyword(document$1.referrer);
22339 if (this.get_config("store_google") && !this.get_config("stop_utm_persistence")) this.register(_$1.info.campaignParams());
22340 if (this.get_config("save_referrer")) this["persistence"].update_referrer_info(document$1.referrer);
22341 };
22342 MixpanelLib.prototype._dom_loaded = function() {
22343 _$1.each(this.__dom_loaded_queue, function(item) {
22344 this._track_dom.apply(this, item);
22345 }, this);
22346 if (!this.has_opted_out_tracking()) _$1.each(this.__request_queue, function(item) {
22347 this._send_request.apply(this, item);
22348 }, this);
22349 delete this.__dom_loaded_queue;
22350 delete this.__request_queue;
22351 };
22352 MixpanelLib.prototype._track_dom = function(DomClass, args) {
22353 if (this.get_config("img")) {
22354 this.report_error("You can't use DOM tracking functions with img = true.");
22355 return false;
22356 }
22357 if (!DOM_LOADED) {
22358 this.__dom_loaded_queue.push([DomClass, args]);
22359 return false;
22360 }
22361 var dt = new DomClass().init(this);
22362 return dt.track.apply(dt, args);
22363 };
22364 /**
22365 * _prepare_callback() should be called by callers of _send_request for use
22366 * as the callback argument.
22367 *
22368 * If there is no callback, this returns null.
22369 * If we are going to make XHR/XDR requests, this returns a function.
22370 * If we are going to use script tags, this returns a string to use as the
22371 * callback GET param.
22372 */
22373 MixpanelLib.prototype._prepare_callback = function(callback, data) {
22374 if (_$1.isUndefined(callback)) return null;
22375 if (USE_XHR) {
22376 var callback_function = function(response) {
22377 callback(response, data);
22378 };
22379 return callback_function;
22380 } else {
22381 var jsc = this["_jsc"];
22382 var randomized_cb = "" + Math.floor(Math.random() * 1e8);
22383 var callback_string = this.get_config("callback_fn") + "[" + randomized_cb + "]";
22384 jsc[randomized_cb] = function(response) {
22385 delete jsc[randomized_cb];
22386 callback(response, data);
22387 };
22388 return callback_string;
22389 }
22390 };
22391 MixpanelLib.prototype._send_request = function(url, data, options, callback) {
22392 var succeeded = true;
22393 if (ENQUEUE_REQUESTS) {
22394 this.__request_queue.push(arguments);
22395 return succeeded;
22396 }
22397 var DEFAULT_OPTIONS = {
22398 method: this.get_config("api_method"),
22399 transport: this.get_config("api_transport"),
22400 verbose: this.get_config("verbose")
22401 };
22402 var body_data = null;
22403 if (!callback && (_$1.isFunction(options) || typeof options === "string")) {
22404 callback = options;
22405 options = null;
22406 }
22407 options = _$1.extend(DEFAULT_OPTIONS, options || {});
22408 if (!USE_XHR) options.method = "GET";
22409 var use_post = options.method === "POST";
22410 var use_sendBeacon = sendBeacon && use_post && options.transport.toLowerCase() === "sendbeacon";
22411 var verbose_mode = options.verbose;
22412 if (data["verbose"]) verbose_mode = true;
22413 if (this.get_config("test")) data["test"] = 1;
22414 if (verbose_mode) data["verbose"] = 1;
22415 if (this.get_config("img")) data["img"] = 1;
22416 if (!USE_XHR) {
22417 if (callback) data["callback"] = callback;
22418 else if (verbose_mode || this.get_config("test")) data["callback"] = "(function(){})";
22419 }
22420 data["ip"] = this.get_config("ip") ? 1 : 0;
22421 data["_"] = (/* @__PURE__ */ new Date()).getTime().toString();
22422 if (use_post) {
22423 body_data = "data=" + encodeURIComponent(data["data"]);
22424 delete data["data"];
22425 }
22426 _$1.extend(data, this.get_config("api_extra_query_params"));
22427 url += "?" + _$1.HTTPBuildQuery(data);
22428 var lib = this;
22429 if ("img" in data) {
22430 var img = document$1.createElement("img");
22431 img.src = url;
22432 document$1.body.appendChild(img);
22433 } else if (use_sendBeacon) {
22434 try {
22435 succeeded = sendBeacon(url, body_data);
22436 } catch (e) {
22437 lib.report_error(e);
22438 succeeded = false;
22439 }
22440 try {
22441 if (callback) callback(succeeded ? 1 : 0);
22442 } catch (e) {
22443 lib.report_error(e);
22444 }
22445 } else if (USE_XHR) try {
22446 var req = new XMLHttpRequest();
22447 req.open(options.method, url, true);
22448 var headers = this.get_config("xhr_headers");
22449 if (use_post) headers["Content-Type"] = "application/x-www-form-urlencoded";
22450 _$1.each(headers, function(headerValue, headerName) {
22451 req.setRequestHeader(headerName, headerValue);
22452 });
22453 if (options.timeout_ms && typeof req.timeout !== "undefined") {
22454 req.timeout = options.timeout_ms;
22455 var start_time = (/* @__PURE__ */ new Date()).getTime();
22456 }
22457 req.withCredentials = true;
22458 req.onreadystatechange = function() {
22459 if (req.readyState === 4) if (req.status === 200) {
22460 if (callback) if (verbose_mode) {
22461 var response;
22462 try {
22463 response = _$1.JSONDecode(req.responseText);
22464 } catch (e) {
22465 lib.report_error(e);
22466 if (options.ignore_json_errors) response = req.responseText;
22467 else return;
22468 }
22469 callback(response);
22470 } else callback(Number(req.responseText));
22471 } else {
22472 var error;
22473 if (req.timeout && !req.status && (/* @__PURE__ */ new Date()).getTime() - start_time >= req.timeout) error = "timeout";
22474 else error = "Bad HTTP status: " + req.status + " " + req.statusText;
22475 lib.report_error(error);
22476 if (callback) if (verbose_mode) {
22477 var response_headers = req["responseHeaders"] || {};
22478 callback({
22479 status: 0,
22480 httpStatusCode: req["status"],
22481 error,
22482 retryAfter: response_headers["Retry-After"]
22483 });
22484 } else callback(0);
22485 }
22486 };
22487 req.send(body_data);
22488 } catch (e) {
22489 lib.report_error(e);
22490 succeeded = false;
22491 }
22492 else {
22493 var script = document$1.createElement("script");
22494 script.type = "text/javascript";
22495 script.async = true;
22496 script.defer = true;
22497 script.src = url;
22498 var s = document$1.getElementsByTagName("script")[0];
22499 s.parentNode.insertBefore(script, s);
22500 }
22501 return succeeded;
22502 };
22503 /**
22504 * _execute_array() deals with processing any mixpanel function
22505 * calls that were called before the Mixpanel library were loaded
22506 * (and are thus stored in an array so they can be called later)
22507 *
22508 * Note: we fire off all the mixpanel function calls && user defined
22509 * functions BEFORE we fire off mixpanel tracking calls. This is so
22510 * identify/register/set_config calls can properly modify early
22511 * tracking calls.
22512 *
22513 * @param {Array} array
22514 */
22515 MixpanelLib.prototype._execute_array = function(array) {
22516 var fn_name;
22517 var alias_calls = [];
22518 var other_calls = [];
22519 var tracking_calls = [];
22520 _$1.each(array, function(item) {
22521 if (item) {
22522 fn_name = item[0];
22523 if (_$1.isArray(fn_name)) tracking_calls.push(item);
22524 else if (typeof item === "function") item.call(this);
22525 else if (_$1.isArray(item) && fn_name === "alias") alias_calls.push(item);
22526 else if (_$1.isArray(item) && fn_name.indexOf("track") !== -1 && typeof this[fn_name] === "function") tracking_calls.push(item);
22527 else other_calls.push(item);
22528 }
22529 }, this);
22530 var execute = function(calls, context) {
22531 _$1.each(calls, function(item) {
22532 if (_$1.isArray(item[0])) {
22533 var caller = context;
22534 _$1.each(item, function(call) {
22535 caller = caller[call[0]].apply(caller, call.slice(1));
22536 });
22537 } else this[item[0]].apply(this, item.slice(1));
22538 }, context);
22539 };
22540 execute(alias_calls, this);
22541 execute(other_calls, this);
22542 execute(tracking_calls, this);
22543 };
22544 MixpanelLib.prototype.are_batchers_initialized = function() {
22545 return !!this.request_batchers.events;
22546 };
22547 MixpanelLib.prototype.get_batcher_configs = function() {
22548 var queue_prefix = "__mpq_" + this.get_config("token");
22549 this._batcher_configs = this._batcher_configs || {
22550 events: {
22551 type: "events",
22552 api_name: "track",
22553 queue_key: queue_prefix + "_ev"
22554 },
22555 people: {
22556 type: "people",
22557 api_name: "engage",
22558 queue_key: queue_prefix + "_pp"
22559 },
22560 groups: {
22561 type: "groups",
22562 api_name: "groups",
22563 queue_key: queue_prefix + "_gr"
22564 }
22565 };
22566 return this._batcher_configs;
22567 };
22568 MixpanelLib.prototype.init_batchers = function() {
22569 if (!this.are_batchers_initialized()) {
22570 var batcher_for = _$1.bind(function(attrs) {
22571 return new RequestBatcher(attrs.queue_key, {
22572 libConfig: this["config"],
22573 errorReporter: this.get_config("error_reporter"),
22574 sendRequestFunc: _$1.bind(function(data, options, cb) {
22575 var api_routes = this.get_config("api_routes");
22576 this._send_request(this.get_api_host(attrs.api_name) + "/" + api_routes[attrs.api_name], this._encode_data_for_request(data), options, this._prepare_callback(cb, data));
22577 }, this),
22578 beforeSendHook: _$1.bind(function(item) {
22579 return this._run_hook("before_send_" + attrs.type, item);
22580 }, this),
22581 stopAllBatchingFunc: _$1.bind(this.stop_batch_senders, this),
22582 usePersistence: true
22583 });
22584 }, this);
22585 var batcher_configs = this.get_batcher_configs();
22586 this.request_batchers = {
22587 events: batcher_for(batcher_configs.events),
22588 people: batcher_for(batcher_configs.people),
22589 groups: batcher_for(batcher_configs.groups)
22590 };
22591 }
22592 if (this.get_config("batch_autostart")) this.start_batch_senders();
22593 };
22594 MixpanelLib.prototype.start_batch_senders = function() {
22595 this._batchers_were_started = true;
22596 if (this.are_batchers_initialized()) {
22597 this._batch_requests = true;
22598 _$1.each(this.request_batchers, function(batcher) {
22599 batcher.start();
22600 });
22601 }
22602 };
22603 MixpanelLib.prototype.stop_batch_senders = function() {
22604 this._batch_requests = false;
22605 _$1.each(this.request_batchers, function(batcher) {
22606 batcher.stop();
22607 batcher.clear();
22608 });
22609 };
22610 /**
22611 * push() keeps the standard async-array-push
22612 * behavior around after the lib is loaded.
22613 * This is only useful for external integrations that
22614 * do not wish to rely on our convenience methods
22615 * (created in the snippet).
22616 *
22617 * ### Usage:
22618 * mixpanel.push(['register', { a: 'b' }]);
22619 *
22620 * @param {Array} item A [function_name, args...] array to be executed
22621 */
22622 MixpanelLib.prototype.push = function(item) {
22623 this._execute_array([item]);
22624 };
22625 /**
22626 * Disable events on the Mixpanel object. If passed no arguments,
22627 * this function disables tracking of any event. If passed an
22628 * array of event names, those events will be disabled, but other
22629 * events will continue to be tracked.
22630 *
22631 * Note: this function does not stop other mixpanel functions from
22632 * firing, such as register() or people.set().
22633 *
22634 * @param {Array} [events] An array of event names to disable
22635 */
22636 MixpanelLib.prototype.disable = function(events) {
22637 if (typeof events === "undefined") this._flags.disable_all_events = true;
22638 else this.__disabled_events = this.__disabled_events.concat(events);
22639 };
22640 MixpanelLib.prototype._encode_data_for_request = function(data) {
22641 var encoded_data = JSONStringify(data);
22642 if (this.get_config("api_payload_format") === PAYLOAD_TYPE_BASE64) encoded_data = _$1.base64Encode(encoded_data);
22643 return { "data": encoded_data };
22644 };
22645 MixpanelLib.prototype._track_or_batch = function(options, callback) {
22646 var truncated_data = _$1.truncate(options.data, 255);
22647 var endpoint = options.endpoint;
22648 var batcher = options.batcher;
22649 var should_send_immediately = options.should_send_immediately;
22650 var send_request_options = options.send_request_options || {};
22651 callback = callback || NOOP_FUNC;
22652 var request_enqueued_or_initiated = true;
22653 var send_request_immediately = _$1.bind(function() {
22654 if (!send_request_options.skip_hooks) truncated_data = this._run_hook("before_send_" + options.type, truncated_data);
22655 if (truncated_data) {
22656 console$1.log("MIXPANEL REQUEST:");
22657 console$1.log(truncated_data);
22658 return this._send_request(endpoint, this._encode_data_for_request(truncated_data), send_request_options, this._prepare_callback(callback, truncated_data));
22659 } else return null;
22660 }, this);
22661 if (this._batch_requests && !should_send_immediately) batcher.enqueue(truncated_data).then(function(succeeded) {
22662 if (succeeded) callback(1, truncated_data);
22663 else send_request_immediately();
22664 });
22665 else request_enqueued_or_initiated = send_request_immediately();
22666 return request_enqueued_or_initiated && truncated_data;
22667 };
22668 /**
22669 * Track an event. This is the most important and
22670 * frequently used Mixpanel function.
22671 *
22672 * ### Usage:
22673 *
22674 * // track an event named 'Registered'
22675 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
22676 *
22677 * // track an event using navigator.sendBeacon
22678 * mixpanel.track('Left page', {'duration_seconds': 35}, {transport: 'sendBeacon'});
22679 *
22680 * To track link clicks or form submissions, see track_links() or track_forms().
22681 *
22682 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
22683 * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.
22684 * @param {Object} [options] Optional configuration for this track request.
22685 * @param {String} [options.transport] Transport method for network request ('xhr' or 'sendBeacon').
22686 * @param {Boolean} [options.send_immediately] Whether to bypass batching/queueing and send track request immediately.
22687 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
22688 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
22689 * with the tracking payload sent to the API server is returned; otherwise false.
22690 */
22691 MixpanelLib.prototype.track = addOptOutCheckMixpanelLib(function(event_name, properties, options, callback) {
22692 if (!callback && typeof options === "function") {
22693 callback = options;
22694 options = null;
22695 }
22696 options = options || {};
22697 var transport = options["transport"];
22698 if (transport) options.transport = transport;
22699 var should_send_immediately = options["send_immediately"];
22700 if (typeof callback !== "function") callback = NOOP_FUNC;
22701 if (_$1.isUndefined(event_name)) {
22702 this.report_error("No event name provided to mixpanel.track");
22703 return;
22704 }
22705 if (this._event_is_disabled(event_name)) {
22706 callback(0);
22707 return;
22708 }
22709 properties = _$1.extend({}, properties);
22710 properties["token"] = this.get_config("token");
22711 var start_timestamp = this["persistence"].remove_event_timer(event_name);
22712 if (!_$1.isUndefined(start_timestamp)) {
22713 var duration_in_ms = (/* @__PURE__ */ new Date()).getTime() - start_timestamp;
22714 properties["$duration"] = parseFloat((duration_in_ms / 1e3).toFixed(3));
22715 }
22716 this._set_default_superprops();
22717 var marketing_properties = this.get_config("track_marketing") ? _$1.info.marketingParams() : {};
22718 properties = _$1.extend({}, _$1.info.properties({ "mp_loader": this.get_config("mp_loader") }), marketing_properties, this["persistence"].properties(), this.unpersisted_superprops, this.get_session_recording_properties(), properties);
22719 var property_blacklist = this.get_config("property_blacklist");
22720 if (_$1.isArray(property_blacklist)) _$1.each(property_blacklist, function(blacklisted_prop) {
22721 delete properties[blacklisted_prop];
22722 });
22723 else this.report_error("Invalid value for property_blacklist config: " + property_blacklist);
22724 var data = {
22725 "event": event_name,
22726 "properties": properties
22727 };
22728 return this._track_or_batch({
22729 type: "events",
22730 data,
22731 endpoint: this.get_api_host("events") + "/" + this.get_config("api_routes")["track"],
22732 batcher: this.request_batchers.events,
22733 should_send_immediately,
22734 send_request_options: options
22735 }, callback);
22736 });
22737 /**
22738 * Register the current user into one/many groups.
22739 *
22740 * ### Usage:
22741 *
22742 * mixpanel.set_group('company', ['mixpanel', 'google']) // an array of IDs
22743 * mixpanel.set_group('company', 'mixpanel')
22744 * mixpanel.set_group('company', 128746312)
22745 *
22746 * @param {String} group_key Group key
22747 * @param {Array|String|Number} group_ids An array of group IDs, or a singular group ID
22748 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
22749 *
22750 */
22751 MixpanelLib.prototype.set_group = addOptOutCheckMixpanelLib(function(group_key, group_ids, callback) {
22752 if (!_$1.isArray(group_ids)) group_ids = [group_ids];
22753 var prop = {};
22754 prop[group_key] = group_ids;
22755 this.register(prop);
22756 return this["people"].set(group_key, group_ids, callback);
22757 });
22758 /**
22759 * Add a new group for this user.
22760 *
22761 * ### Usage:
22762 *
22763 * mixpanel.add_group('company', 'mixpanel')
22764 *
22765 * @param {String} group_key Group key
22766 * @param {*} group_id A valid Mixpanel property type
22767 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
22768 */
22769 MixpanelLib.prototype.add_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
22770 var old_values = this.get_property(group_key);
22771 var prop = {};
22772 if (old_values === void 0) {
22773 prop[group_key] = [group_id];
22774 this.register(prop);
22775 } else if (old_values.indexOf(group_id) === -1) {
22776 old_values.push(group_id);
22777 prop[group_key] = old_values;
22778 this.register(prop);
22779 }
22780 return this["people"].union(group_key, group_id, callback);
22781 });
22782 /**
22783 * Remove a group from this user.
22784 *
22785 * ### Usage:
22786 *
22787 * mixpanel.remove_group('company', 'mixpanel')
22788 *
22789 * @param {String} group_key Group key
22790 * @param {*} group_id A valid Mixpanel property type
22791 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
22792 */
22793 MixpanelLib.prototype.remove_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
22794 var old_value = this.get_property(group_key);
22795 if (old_value !== void 0) {
22796 var idx = old_value.indexOf(group_id);
22797 if (idx > -1) {
22798 old_value.splice(idx, 1);
22799 this.register({ group_key: old_value });
22800 }
22801 if (old_value.length === 0) this.unregister(group_key);
22802 }
22803 return this["people"].remove(group_key, group_id, callback);
22804 });
22805 /**
22806 * Track an event with specific groups.
22807 *
22808 * ### Usage:
22809 *
22810 * mixpanel.track_with_groups('purchase', {'product': 'iphone'}, {'University': ['UCB', 'UCLA']})
22811 *
22812 * @param {String} event_name The name of the event (see `mixpanel.track()`)
22813 * @param {Object=} properties A set of properties to include with the event you're sending (see `mixpanel.track()`)
22814 * @param {Object=} groups An object mapping group name keys to one or more values
22815 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
22816 */
22817 MixpanelLib.prototype.track_with_groups = addOptOutCheckMixpanelLib(function(event_name, properties, groups, callback) {
22818 var tracking_props = _$1.extend({}, properties || {});
22819 _$1.each(groups, function(v, k) {
22820 if (v !== null && v !== void 0) tracking_props[k] = v;
22821 });
22822 return this.track(event_name, tracking_props, callback);
22823 });
22824 MixpanelLib.prototype._create_map_key = function(group_key, group_id) {
22825 return group_key + "_" + JSON.stringify(group_id);
22826 };
22827 MixpanelLib.prototype._remove_group_from_cache = function(group_key, group_id) {
22828 delete this._cached_groups[this._create_map_key(group_key, group_id)];
22829 };
22830 /**
22831 * Look up reference to a Mixpanel group
22832 *
22833 * ### Usage:
22834 *
22835 * mixpanel.get_group(group_key, group_id)
22836 *
22837 * @param {String} group_key Group key
22838 * @param {Object} group_id A valid Mixpanel property type
22839 * @returns {Object} A MixpanelGroup identifier
22840 */
22841 MixpanelLib.prototype.get_group = function(group_key, group_id) {
22842 var map_key = this._create_map_key(group_key, group_id);
22843 var group = this._cached_groups[map_key];
22844 if (group === void 0 || group._group_key !== group_key || group._group_id !== group_id) {
22845 group = new MixpanelGroup();
22846 group._init(this, group_key, group_id);
22847 this._cached_groups[map_key] = group;
22848 }
22849 return group;
22850 };
22851 /**
22852 * Track a default Mixpanel page view event, which includes extra default event properties to
22853 * improve page view data.
22854 *
22855 * ### Usage:
22856 *
22857 * // track a default $mp_web_page_view event
22858 * mixpanel.track_pageview();
22859 *
22860 * // track a page view event with additional event properties
22861 * mixpanel.track_pageview({'ab_test_variant': 'card-layout-b'});
22862 *
22863 * // example approach to track page views on different page types as event properties
22864 * mixpanel.track_pageview({'page': 'pricing'});
22865 * mixpanel.track_pageview({'page': 'homepage'});
22866 *
22867 * // UNCOMMON: Tracking a page view event with a custom event_name option. NOT expected to be used for
22868 * // individual pages on the same site or product. Use cases for custom event_name may be page
22869 * // views on different products or internal applications that are considered completely separate
22870 * mixpanel.track_pageview({'page': 'customer-search'}, {'event_name': '[internal] Admin Page View'});
22871 *
22872 * ### Notes:
22873 *
22874 * The `config.track_pageview` option for <a href="#mixpanelinit">mixpanel.init()</a>
22875 * may be turned on for tracking page loads automatically.
22876 *
22877 * // track only page loads
22878 * mixpanel.init(PROJECT_TOKEN, {track_pageview: true});
22879 *
22880 * // track when the URL changes in any manner
22881 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'full-url'});
22882 *
22883 * // track when the URL changes, ignoring any changes in the hash part
22884 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path-and-query-string'});
22885 *
22886 * // track when the path changes, ignoring any query parameter or hash changes
22887 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path'});
22888 *
22889 * @param {Object} [properties] An optional set of additional properties to send with the page view event
22890 * @param {Object} [options] Page view tracking options
22891 * @param {String} [options.event_name] - Alternate name for the tracking event
22892 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
22893 * with the tracking payload sent to the API server is returned; otherwise false.
22894 */
22895 MixpanelLib.prototype.track_pageview = addOptOutCheckMixpanelLib(function(properties, options) {
22896 if (typeof properties !== "object") properties = {};
22897 options = options || {};
22898 var event_name = options["event_name"] || "$mp_web_page_view";
22899 var default_page_properties = _$1.extend(_$1.info.mpPageViewProperties(), _$1.info.campaignParams(), _$1.info.clickParams());
22900 var event_properties = _$1.extend({}, default_page_properties, properties);
22901 return this.track(event_name, event_properties);
22902 });
22903 /**
22904 * Track clicks on a set of document elements. Selector must be a
22905 * valid query. Elements must exist on the page at the time track_links is called.
22906 *
22907 * ### Usage:
22908 *
22909 * // track click for link id #nav
22910 * mixpanel.track_links('#nav', 'Clicked Nav Link');
22911 *
22912 * ### Notes:
22913 *
22914 * This function will wait up to 300 ms for the Mixpanel
22915 * servers to respond. If they have not responded by that time
22916 * it will head to the link without ensuring that your event
22917 * has been tracked. To configure this timeout please see the
22918 * set_config() documentation below.
22919 *
22920 * If you pass a function in as the properties argument, the
22921 * function will receive the DOMElement that triggered the
22922 * event as an argument. You are expected to return an object
22923 * from the function; any properties defined on this object
22924 * will be sent to mixpanel as event properties.
22925 *
22926 * @type {Function}
22927 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
22928 * @param {String} event_name The name of the event to track
22929 * @param {Object|Function} [properties] A properties object or function that returns a dictionary of properties when passed a DOMElement
22930 */
22931 MixpanelLib.prototype.track_links = function() {
22932 return this._track_dom.call(this, LinkTracker, arguments);
22933 };
22934 /**
22935 * Track form submissions. Selector must be a valid query.
22936 *
22937 * ### Usage:
22938 *
22939 * // track submission for form id 'register'
22940 * mixpanel.track_forms('#register', 'Created Account');
22941 *
22942 * ### Notes:
22943 *
22944 * This function will wait up to 300 ms for the mixpanel
22945 * servers to respond, if they have not responded by that time
22946 * it will head to the link without ensuring that your event
22947 * has been tracked. To configure this timeout please see the
22948 * set_config() documentation below.
22949 *
22950 * If you pass a function in as the properties argument, the
22951 * function will receive the DOMElement that triggered the
22952 * event as an argument. You are expected to return an object
22953 * from the function; any properties defined on this object
22954 * will be sent to mixpanel as event properties.
22955 *
22956 * @type {Function}
22957 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
22958 * @param {String} event_name The name of the event to track
22959 * @param {Object|Function} [properties] This can be a set of properties, or a function that returns a set of properties after being passed a DOMElement
22960 */
22961 MixpanelLib.prototype.track_forms = function() {
22962 return this._track_dom.call(this, FormTracker, arguments);
22963 };
22964 /**
22965 * Time an event by including the time between this call and a
22966 * later 'track' call for the same event in the properties sent
22967 * with the event.
22968 *
22969 * ### Usage:
22970 *
22971 * // time an event named 'Registered'
22972 * mixpanel.time_event('Registered');
22973 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
22974 *
22975 * When called for a particular event name, the next track call for that event
22976 * name will include the elapsed time between the 'time_event' and 'track'
22977 * calls. This value is stored as seconds in the '$duration' property.
22978 *
22979 * @param {String} event_name The name of the event.
22980 */
22981 MixpanelLib.prototype.time_event = function(event_name) {
22982 if (_$1.isUndefined(event_name)) {
22983 this.report_error("No event name provided to mixpanel.time_event");
22984 return;
22985 }
22986 if (this._event_is_disabled(event_name)) return;
22987 this["persistence"].set_event_timer(event_name, (/* @__PURE__ */ new Date()).getTime());
22988 };
22989 var REGISTER_DEFAULTS = { "persistent": true };
22990 /**
22991 * Helper to parse options param for register methods, maintaining
22992 * legacy support for plain "days" param instead of options object
22993 * @param {Number|Object} [days_or_options] 'days' option (Number), or Options object for register methods
22994 * @returns {Object} options object
22995 */
22996 var options_for_register = function(days_or_options) {
22997 var options;
22998 if (_$1.isObject(days_or_options)) options = days_or_options;
22999 else if (!_$1.isUndefined(days_or_options)) options = { "days": days_or_options };
23000 else options = {};
23001 return _$1.extend({}, REGISTER_DEFAULTS, options);
23002 };
23003 /**
23004 * Register a set of super properties, which are included with all
23005 * events. This will overwrite previous super property values.
23006 *
23007 * ### Usage:
23008 *
23009 * // register 'Gender' as a super property
23010 * mixpanel.register({'Gender': 'Female'});
23011 *
23012 * // register several super properties when a user signs up
23013 * mixpanel.register({
23014 * 'Email': '[email protected]',
23015 * 'Account Type': 'Free'
23016 * });
23017 *
23018 * // register only for the current pageload
23019 * mixpanel.register({'Name': 'Pat'}, {persistent: false});
23020 *
23021 * @param {Object} properties An associative array of properties to store about the user
23022 * @param {Number|Object} [days_or_options] Options object or number of days since the user's last visit to store the super properties (only valid for persisted props)
23023 * @param {boolean} [days_or_options.days] - number of days since the user's last visit to store the super properties (only valid for persisted props)
23024 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
23025 */
23026 MixpanelLib.prototype.register = function(props, days_or_options) {
23027 var options = options_for_register(days_or_options);
23028 if (options["persistent"]) this["persistence"].register(props, options["days"]);
23029 else _$1.extend(this.unpersisted_superprops, props);
23030 };
23031 /**
23032 * Register a set of super properties only once. This will not
23033 * overwrite previous super property values, unlike register().
23034 *
23035 * ### Usage:
23036 *
23037 * // register a super property for the first time only
23038 * mixpanel.register_once({
23039 * 'First Login Date': new Date().toISOString()
23040 * });
23041 *
23042 * // register once, only for the current pageload
23043 * mixpanel.register_once({
23044 * 'First interaction time': new Date().toISOString()
23045 * }, 'None', {persistent: false});
23046 *
23047 * ### Notes:
23048 *
23049 * If default_value is specified, current super properties
23050 * with that value will be overwritten.
23051 *
23052 * @param {Object} properties An associative array of properties to store about the user
23053 * @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'
23054 * @param {Number|Object} [days_or_options] Options object or number of days since the user's last visit to store the super properties (only valid for persisted props)
23055 * @param {boolean} [days_or_options.days] - number of days since the user's last visit to store the super properties (only valid for persisted props)
23056 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
23057 */
23058 MixpanelLib.prototype.register_once = function(props, default_value, days_or_options) {
23059 var options = options_for_register(days_or_options);
23060 if (options["persistent"]) this["persistence"].register_once(props, default_value, options["days"]);
23061 else {
23062 if (typeof default_value === "undefined") default_value = "None";
23063 _$1.each(props, function(val, prop) {
23064 if (!this.unpersisted_superprops.hasOwnProperty(prop) || this.unpersisted_superprops[prop] === default_value) this.unpersisted_superprops[prop] = val;
23065 }, this);
23066 }
23067 };
23068 /**
23069 * Delete a super property stored with the current user.
23070 *
23071 * @param {String} property The name of the super property to remove
23072 * @param {Object} [options]
23073 * @param {boolean} [options.persistent=true] - whether to look in persistent storage (cookie/localStorage)
23074 */
23075 MixpanelLib.prototype.unregister = function(property, options) {
23076 options = options_for_register(options);
23077 if (options["persistent"]) this["persistence"].unregister(property);
23078 else delete this.unpersisted_superprops[property];
23079 };
23080 MixpanelLib.prototype._register_single = function(prop, value) {
23081 var props = {};
23082 props[prop] = value;
23083 this.register(props);
23084 };
23085 /**
23086 * Identify a user with a unique ID to track user activity across
23087 * devices, tie a user to their events, and create a user profile.
23088 * If you never call this method, unique visitors are tracked using
23089 * a UUID generated the first time they visit the site.
23090 *
23091 * Call identify when you know the identity of the current user,
23092 * typically after login or signup. We recommend against using
23093 * identify for anonymous visitors to your site.
23094 *
23095 * ### Notes:
23096 * If your project has
23097 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
23098 * enabled, the identify method will connect pre- and
23099 * post-authentication events when appropriate.
23100 *
23101 * If your project does not have ID Merge enabled, identify will
23102 * change the user's local distinct_id to the unique ID you pass.
23103 * Events tracked prior to authentication will not be connected
23104 * to the same user identity. If ID Merge is disabled, alias can
23105 * be used to connect pre- and post-registration events.
23106 *
23107 * @param {String} [unique_id] A string that uniquely identifies a user. If not provided, the distinct_id currently in the persistent store (cookie or localStorage) will be used.
23108 */
23109 MixpanelLib.prototype.identify = function(new_distinct_id, _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback) {
23110 var previous_distinct_id = this.get_distinct_id();
23111 if (new_distinct_id && previous_distinct_id !== new_distinct_id) {
23112 if (typeof new_distinct_id === "string" && new_distinct_id.indexOf(DEVICE_ID_PREFIX) === 0) {
23113 this.report_error("distinct_id cannot have $device: prefix");
23114 return -1;
23115 }
23116 this.register({ "$user_id": new_distinct_id });
23117 }
23118 if (!this.get_property("$device_id")) {
23119 var device_id = previous_distinct_id;
23120 this.register_once({
23121 "$had_persisted_distinct_id": true,
23122 "$device_id": device_id
23123 }, "");
23124 }
23125 if (new_distinct_id !== previous_distinct_id && new_distinct_id !== this.get_property(ALIAS_ID_KEY)) {
23126 this.unregister(ALIAS_ID_KEY);
23127 this.register({ "distinct_id": new_distinct_id });
23128 }
23129 this._flags.identify_called = true;
23130 this["people"]._flush(_set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback);
23131 if (new_distinct_id !== previous_distinct_id) this.track("$identify", {
23132 "distinct_id": new_distinct_id,
23133 "$anon_distinct_id": previous_distinct_id
23134 }, { skip_hooks: true });
23135 if (new_distinct_id !== previous_distinct_id) this.flags.fetchFlags();
23136 };
23137 /**
23138 * Clears super properties and generates a new random distinct_id for this instance.
23139 * Useful for clearing data when a user logs out.
23140 */
23141 MixpanelLib.prototype.reset = function() {
23142 this.stop_session_recording();
23143 this["persistence"].clear();
23144 this._flags.identify_called = false;
23145 var uuid = _$1.UUID();
23146 this.register_once({
23147 "distinct_id": DEVICE_ID_PREFIX + uuid,
23148 "$device_id": uuid
23149 }, "");
23150 this._check_and_start_session_recording();
23151 };
23152 /**
23153 * Returns the current distinct id of the user. This is either the id automatically
23154 * generated by the library or the id that has been passed by a call to identify().
23155 *
23156 * ### Notes:
23157 *
23158 * get_distinct_id() can only be called after the Mixpanel library has finished loading.
23159 * init() has a loaded function available to handle this automatically. For example:
23160 *
23161 * // set distinct_id after the mixpanel library has loaded
23162 * mixpanel.init('YOUR PROJECT TOKEN', {
23163 * loaded: function(mixpanel) {
23164 * distinct_id = mixpanel.get_distinct_id();
23165 * }
23166 * });
23167 */
23168 MixpanelLib.prototype.get_distinct_id = function() {
23169 return this.get_property("distinct_id");
23170 };
23171 /**
23172 * The alias method creates an alias which Mixpanel will use to
23173 * remap one id to another. Multiple aliases can point to the
23174 * same identifier.
23175 *
23176 * The following is a valid use of alias:
23177 *
23178 * mixpanel.alias('new_id', 'existing_id');
23179 * // You can add multiple id aliases to the existing ID
23180 * mixpanel.alias('newer_id', 'existing_id');
23181 *
23182 * Aliases can also be chained - the following is a valid example:
23183 *
23184 * mixpanel.alias('new_id', 'existing_id');
23185 * // chain newer_id - new_id - existing_id
23186 * mixpanel.alias('newer_id', 'new_id');
23187 *
23188 * Aliases cannot point to multiple identifiers - the following
23189 * example will not work:
23190 *
23191 * mixpanel.alias('new_id', 'existing_id');
23192 * // this is invalid as 'new_id' already points to 'existing_id'
23193 * mixpanel.alias('new_id', 'newer_id');
23194 *
23195 * ### Notes:
23196 *
23197 * If your project does not have
23198 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
23199 * enabled, the best practice is to call alias once when a unique
23200 * ID is first created for a user (e.g., when a user first registers
23201 * for an account). Do not use alias multiple times for a single
23202 * user without ID Merge enabled.
23203 *
23204 * @param {String} alias A unique identifier that you want to use for this user in the future.
23205 * @param {String} [original] The current identifier being used for this user.
23206 */
23207 MixpanelLib.prototype.alias = function(alias, original) {
23208 if (alias === this.get_property(PEOPLE_DISTINCT_ID_KEY)) {
23209 this.report_error("Attempting to create alias for existing People user - aborting.");
23210 return -2;
23211 }
23212 var _this = this;
23213 if (_$1.isUndefined(original)) original = this.get_distinct_id();
23214 if (alias !== original) {
23215 this._register_single(ALIAS_ID_KEY, alias);
23216 return this.track("$create_alias", {
23217 "alias": alias,
23218 "distinct_id": original
23219 }, { skip_hooks: true }, function() {
23220 _this.identify(alias);
23221 });
23222 } else {
23223 this.report_error("alias matches current distinct_id - skipping api call.");
23224 this.identify(alias);
23225 return -1;
23226 }
23227 };
23228 /**
23229 * Provide a string to recognize the user by. The string passed to
23230 * this method will appear in the Mixpanel Streams product rather
23231 * than an automatically generated name. Name tags do not have to
23232 * be unique.
23233 *
23234 * This value will only be included in Streams data.
23235 *
23236 * @param {String} name_tag A human readable name for the user
23237 * @deprecated
23238 */
23239 MixpanelLib.prototype.name_tag = function(name_tag) {
23240 this._register_single("mp_name_tag", name_tag);
23241 };
23242 /**
23243 * Update the configuration of a mixpanel library instance.
23244 *
23245 * The default config is:
23246 *
23247 * {
23248 * // host for requests (customizable for e.g. a local proxy)
23249 * api_host: 'https://api-js.mixpanel.com',
23250 *
23251 * // endpoints for different types of requests
23252 * api_routes: {
23253 * track: 'track/',
23254 * engage: 'engage/',
23255 * groups: 'groups/',
23256 * }
23257 *
23258 * // HTTP method for tracking requests
23259 * api_method: 'POST'
23260 *
23261 * // transport for sending requests ('XHR' or 'sendBeacon')
23262 * // NB: sendBeacon should only be used for scenarios such as
23263 * // page unload where a "best-effort" attempt to send is
23264 * // acceptable; the sendBeacon API does not support callbacks
23265 * // or any way to know the result of the request. Mixpanel
23266 * // tracking via sendBeacon will not support any event-
23267 * // batching or retry mechanisms.
23268 * api_transport: 'XHR'
23269 *
23270 * // request-batching/queueing/retry
23271 * batch_requests: true,
23272 *
23273 * // maximum number of events/updates to send in a single
23274 * // network request
23275 * batch_size: 50,
23276 *
23277 * // milliseconds to wait between sending batch requests
23278 * batch_flush_interval_ms: 5000,
23279 *
23280 * // milliseconds to wait for network responses to batch requests
23281 * // before they are considered timed-out and retried
23282 * batch_request_timeout_ms: 90000,
23283 *
23284 * // override value for cookie domain, only useful for ensuring
23285 * // correct cross-subdomain cookies on unusual domains like
23286 * // subdomain.mainsite.avocat.fr; NB this cannot be used to
23287 * // set cookies on a different domain than the current origin
23288 * cookie_domain: ''
23289 *
23290 * // super properties cookie expiration (in days)
23291 * cookie_expiration: 365
23292 *
23293 * // if true, cookie will be set with SameSite=None; Secure
23294 * // this is only useful in special situations, like embedded
23295 * // 3rd-party iframes that set up a Mixpanel instance
23296 * cross_site_cookie: false
23297 *
23298 * // super properties span subdomains
23299 * cross_subdomain_cookie: true
23300 *
23301 * // debug mode
23302 * debug: false
23303 *
23304 * // if this is true, the mixpanel cookie or localStorage entry
23305 * // will be deleted, and no user persistence will take place
23306 * disable_persistence: false
23307 *
23308 * // if this is true, Mixpanel will automatically determine
23309 * // City, Region and Country data using the IP address of
23310 * //the client
23311 * ip: true
23312 *
23313 * // opt users out of tracking by this Mixpanel instance by default
23314 * opt_out_tracking_by_default: false
23315 *
23316 * // opt users out of browser data storage by this Mixpanel instance by default
23317 * opt_out_persistence_by_default: false
23318 *
23319 * // persistence mechanism used by opt-in/opt-out methods - cookie
23320 * // or localStorage - falls back to cookie if localStorage is unavailable
23321 * opt_out_tracking_persistence_type: 'localStorage'
23322 *
23323 * // customize the name of cookie/localStorage set by opt-in/opt-out methods
23324 * opt_out_tracking_cookie_prefix: null
23325 *
23326 * // type of persistent store for super properties (cookie/
23327 * // localStorage) if set to 'localStorage', any existing
23328 * // mixpanel cookie value with the same persistence_name
23329 * // will be transferred to localStorage and deleted
23330 * persistence: 'cookie'
23331 *
23332 * // name for super properties persistent store
23333 * persistence_name: ''
23334 *
23335 * // names of properties/superproperties which should never
23336 * // be sent with track() calls
23337 * property_blacklist: []
23338 *
23339 * // if this is true, mixpanel cookies will be marked as
23340 * // secure, meaning they will only be transmitted over https
23341 * secure_cookie: false
23342 *
23343 * // disables enriching user profiles with first touch marketing data
23344 * skip_first_touch_marketing: false
23345 *
23346 * // the amount of time track_links will
23347 * // wait for Mixpanel's servers to respond
23348 * track_links_timeout: 300
23349 *
23350 * // adds any UTM parameters and click IDs present on the page to any events fired
23351 * track_marketing: true
23352 *
23353 * // enables automatic page view tracking using default page view events through
23354 * // the track_pageview() method
23355 * track_pageview: false
23356 *
23357 * // if you set upgrade to be true, the library will check for
23358 * // a cookie from our old js library and import super
23359 * // properties from it, then the old cookie is deleted
23360 * // The upgrade config option only works in the initialization,
23361 * // so make sure you set it when you create the library.
23362 * upgrade: false
23363 *
23364 * // extra HTTP request headers to set for each API request, in
23365 * // the format {'Header-Name': value}
23366 * xhr_headers: {}
23367 *
23368 * // whether to ignore or respect the web browser's Do Not Track setting
23369 * ignore_dnt: false
23370 * }
23371 *
23372 *
23373 * @param {Object} config A dictionary of new configuration values to update
23374 */
23375 MixpanelLib.prototype.set_config = function(config) {
23376 if (_$1.isObject(config)) {
23377 _$1.extend(this["config"], config);
23378 if (config["batch_size"]) _$1.each(this.request_batchers, function(batcher) {
23379 batcher.resetBatchSize();
23380 });
23381 if (!this.get_config("persistence_name")) this["config"]["persistence_name"] = this["config"]["cookie_name"];
23382 if (!this.get_config("disable_persistence")) this["config"]["disable_persistence"] = this["config"]["disable_cookie"];
23383 if (this["persistence"]) this["persistence"].update_config(this["config"]);
23384 Config.DEBUG = Config.DEBUG || this.get_config("debug");
23385 if (("autocapture" in config || "record_heatmap_data" in config) && this.autocapture) this.autocapture.init();
23386 }
23387 };
23388 /**
23389 * returns the current config object for the library.
23390 */
23391 MixpanelLib.prototype.get_config = function(prop_name) {
23392 return this["config"][prop_name];
23393 };
23394 /**
23395 * Fetch a hook function from config, with safe default, and run it
23396 * against the given arguments
23397 * @param {string} hook_name which hook to retrieve
23398 * @returns {any|null} return value of user-provided hook, or null if nothing was returned
23399 */
23400 MixpanelLib.prototype._run_hook = function(hook_name) {
23401 var ret = (this["config"]["hooks"][hook_name] || IDENTITY_FUNC).apply(this, slice.call(arguments, 1));
23402 if (typeof ret === "undefined") {
23403 this.report_error(hook_name + " hook did not return a value");
23404 ret = null;
23405 }
23406 return ret;
23407 };
23408 /**
23409 * Returns the value of the super property named property_name. If no such
23410 * property is set, get_property() will return the undefined value.
23411 *
23412 * ### Notes:
23413 *
23414 * get_property() can only be called after the Mixpanel library has finished loading.
23415 * init() has a loaded function available to handle this automatically. For example:
23416 *
23417 * // grab value for 'user_id' after the mixpanel library has loaded
23418 * mixpanel.init('YOUR PROJECT TOKEN', {
23419 * loaded: function(mixpanel) {
23420 * user_id = mixpanel.get_property('user_id');
23421 * }
23422 * });
23423 *
23424 * @param {String} property_name The name of the super property you want to retrieve
23425 */
23426 MixpanelLib.prototype.get_property = function(property_name) {
23427 return this["persistence"].load_prop([property_name]);
23428 };
23429 /**
23430 * Get the API host for a specific endpoint type, falling back to the default api_host if not specified
23431 *
23432 * @param {String} endpoint_type The type of endpoint (e.g., "events", "people", "groups")
23433 * @returns {String} The API host to use for this endpoint
23434 */
23435 MixpanelLib.prototype.get_api_host = function(endpoint_type) {
23436 return this.get_config("api_hosts")[endpoint_type] || this.get_config("api_host");
23437 };
23438 MixpanelLib.prototype.toString = function() {
23439 var name = this.get_config("name");
23440 if (name !== PRIMARY_INSTANCE_NAME) name = PRIMARY_INSTANCE_NAME + "." + name;
23441 return name;
23442 };
23443 MixpanelLib.prototype._event_is_disabled = function(event_name) {
23444 return _$1.isBlockedUA(userAgent) || this._flags.disable_all_events || _$1.include(this.__disabled_events, event_name);
23445 };
23446 MixpanelLib.prototype._gdpr_init = function() {
23447 if (this.get_config("opt_out_tracking_persistence_type") === "localStorage" && _$1.localStorage.is_supported()) {
23448 if (!this.has_opted_in_tracking() && this.has_opted_in_tracking({ "persistence_type": "cookie" })) this.opt_in_tracking({ "enable_persistence": false });
23449 if (!this.has_opted_out_tracking() && this.has_opted_out_tracking({ "persistence_type": "cookie" })) this.opt_out_tracking({ "clear_persistence": false });
23450 this.clear_opt_in_out_tracking({
23451 "persistence_type": "cookie",
23452 "enable_persistence": false
23453 });
23454 }
23455 if (this.has_opted_out_tracking()) this._gdpr_update_persistence({ "clear_persistence": true });
23456 else if (!this.has_opted_in_tracking() && (this.get_config("opt_out_tracking_by_default") || _$1.cookie.get("mp_optout"))) {
23457 _$1.cookie.remove("mp_optout");
23458 this.opt_out_tracking({ "clear_persistence": this.get_config("opt_out_persistence_by_default") });
23459 }
23460 };
23461 /**
23462 * Enable or disable persistence based on options
23463 * only enable/disable if persistence is not already in this state
23464 * @param {boolean} [options.clear_persistence] If true, will delete all data stored by the sdk in persistence and disable it
23465 * @param {boolean} [options.enable_persistence] If true, will re-enable sdk persistence
23466 */
23467 MixpanelLib.prototype._gdpr_update_persistence = function(options) {
23468 var disabled;
23469 if (options && options["clear_persistence"]) disabled = true;
23470 else if (options && options["enable_persistence"]) disabled = false;
23471 else return;
23472 if (!this.get_config("disable_persistence") && this["persistence"].disabled !== disabled) this["persistence"].set_disabled(disabled);
23473 if (disabled) {
23474 this.stop_batch_senders();
23475 this.stop_session_recording();
23476 } else if (this._batchers_were_started) this.start_batch_senders();
23477 };
23478 MixpanelLib.prototype._gdpr_call_func = function(func, options) {
23479 options = _$1.extend({
23480 "track": _$1.bind(this.track, this),
23481 "persistence_type": this.get_config("opt_out_tracking_persistence_type"),
23482 "cookie_prefix": this.get_config("opt_out_tracking_cookie_prefix"),
23483 "cookie_expiration": this.get_config("cookie_expiration"),
23484 "cross_site_cookie": this.get_config("cross_site_cookie"),
23485 "cross_subdomain_cookie": this.get_config("cross_subdomain_cookie"),
23486 "cookie_domain": this.get_config("cookie_domain"),
23487 "secure_cookie": this.get_config("secure_cookie"),
23488 "ignore_dnt": this.get_config("ignore_dnt")
23489 }, options);
23490 if (!_$1.localStorage.is_supported()) options["persistence_type"] = "cookie";
23491 return func(this.get_config("token"), {
23492 track: options["track"],
23493 trackEventName: options["track_event_name"],
23494 trackProperties: options["track_properties"],
23495 persistenceType: options["persistence_type"],
23496 persistencePrefix: options["cookie_prefix"],
23497 cookieDomain: options["cookie_domain"],
23498 cookieExpiration: options["cookie_expiration"],
23499 crossSiteCookie: options["cross_site_cookie"],
23500 crossSubdomainCookie: options["cross_subdomain_cookie"],
23501 secureCookie: options["secure_cookie"],
23502 ignoreDnt: options["ignore_dnt"]
23503 });
23504 };
23505 /**
23506 * Opt the user in to data tracking and cookies/localstorage for this Mixpanel instance
23507 *
23508 * ### Usage:
23509 *
23510 * // opt user in
23511 * mixpanel.opt_in_tracking();
23512 *
23513 * // opt user in with specific event name, properties, cookie configuration
23514 * mixpanel.opt_in_tracking({
23515 * track_event_name: 'User opted in',
23516 * track_event_properties: {
23517 * 'Email': '[email protected]'
23518 * },
23519 * cookie_expiration: 30,
23520 * secure_cookie: true
23521 * });
23522 *
23523 * @param {Object} [options] A dictionary of config options to override
23524 * @param {function} [options.track] Function used for tracking a Mixpanel event to record the opt-in action (default is this Mixpanel instance's track method)
23525 * @param {string} [options.track_event_name=$opt_in] Event name to be used for tracking the opt-in action
23526 * @param {Object} [options.track_properties] Set of properties to be tracked along with the opt-in action
23527 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
23528 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23529 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23530 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
23531 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
23532 * @param {boolean} [options.cross_site_cookie] Whether the opt-in cookie is set as cross-site-enabled (overrides value specified in this Mixpanel instance's config)
23533 * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this Mixpanel instance's config)
23534 * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this Mixpanel instance's config)
23535 */
23536 MixpanelLib.prototype.opt_in_tracking = function(options) {
23537 options = _$1.extend({ "enable_persistence": true }, options);
23538 this._gdpr_call_func(optIn, options);
23539 this._gdpr_update_persistence(options);
23540 };
23541 /**
23542 * Opt the user out of data tracking and cookies/localstorage for this Mixpanel instance
23543 *
23544 * ### Usage:
23545 *
23546 * // opt user out
23547 * mixpanel.opt_out_tracking();
23548 *
23549 * // opt user out with different cookie configuration from Mixpanel instance
23550 * mixpanel.opt_out_tracking({
23551 * cookie_expiration: 30,
23552 * secure_cookie: true
23553 * });
23554 *
23555 * @param {Object} [options] A dictionary of config options to override
23556 * @param {boolean} [options.delete_user=true] If true, will delete the currently identified user's profile and clear all charges after opting the user out
23557 * @param {boolean} [options.clear_persistence=true] If true, will delete all data stored by the sdk in persistence
23558 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23559 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23560 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
23561 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
23562 * @param {boolean} [options.cross_site_cookie] Whether the opt-in cookie is set as cross-site-enabled (overrides value specified in this Mixpanel instance's config)
23563 * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this Mixpanel instance's config)
23564 * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this Mixpanel instance's config)
23565 */
23566 MixpanelLib.prototype.opt_out_tracking = function(options) {
23567 options = _$1.extend({
23568 "clear_persistence": true,
23569 "delete_user": true
23570 }, options);
23571 if (options["delete_user"] && this["people"] && this["people"]._identify_called()) {
23572 this["people"].delete_user();
23573 this["people"].clear_charges();
23574 }
23575 this._gdpr_call_func(optOut, options);
23576 this._gdpr_update_persistence(options);
23577 };
23578 /**
23579 * Check whether the user has opted in to data tracking and cookies/localstorage for this Mixpanel instance
23580 *
23581 * ### Usage:
23582 *
23583 * var has_opted_in = mixpanel.has_opted_in_tracking();
23584 * // use has_opted_in value
23585 *
23586 * @param {Object} [options] A dictionary of config options to override
23587 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23588 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23589 * @returns {boolean} current opt-in status
23590 */
23591 MixpanelLib.prototype.has_opted_in_tracking = function(options) {
23592 return this._gdpr_call_func(hasOptedIn, options);
23593 };
23594 /**
23595 * Check whether the user has opted out of data tracking and cookies/localstorage for this Mixpanel instance
23596 *
23597 * ### Usage:
23598 *
23599 * var has_opted_out = mixpanel.has_opted_out_tracking();
23600 * // use has_opted_out value
23601 *
23602 * @param {Object} [options] A dictionary of config options to override
23603 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23604 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23605 * @returns {boolean} current opt-out status
23606 */
23607 MixpanelLib.prototype.has_opted_out_tracking = function(options) {
23608 return this._gdpr_call_func(hasOptedOut, options);
23609 };
23610 /**
23611 * Clear the user's opt in/out status of data tracking and cookies/localstorage for this Mixpanel instance
23612 *
23613 * ### Usage:
23614 *
23615 * // clear user's opt-in/out status
23616 * mixpanel.clear_opt_in_out_tracking();
23617 *
23618 * // clear user's opt-in/out status with specific cookie configuration - should match
23619 * // configuration used when opt_in_tracking/opt_out_tracking methods were called.
23620 * mixpanel.clear_opt_in_out_tracking({
23621 * cookie_expiration: 30,
23622 * secure_cookie: true
23623 * });
23624 *
23625 * @param {Object} [options] A dictionary of config options to override
23626 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
23627 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23628 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23629 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
23630 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
23631 * @param {boolean} [options.cross_site_cookie] Whether the opt-in cookie is set as cross-site-enabled (overrides value specified in this Mixpanel instance's config)
23632 * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this Mixpanel instance's config)
23633 * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this Mixpanel instance's config)
23634 */
23635 MixpanelLib.prototype.clear_opt_in_out_tracking = function(options) {
23636 options = _$1.extend({ "enable_persistence": true }, options);
23637 this._gdpr_call_func(clearOptInOut, options);
23638 this._gdpr_update_persistence(options);
23639 };
23640 MixpanelLib.prototype.report_error = function(msg, err) {
23641 console$1.error.apply(console$1.error, arguments);
23642 try {
23643 if (!err && !(msg instanceof Error)) msg = new Error(msg);
23644 this.get_config("error_reporter")(msg, err);
23645 } catch (err) {
23646 console$1.error(err);
23647 }
23648 };
23649 MixpanelLib.prototype["init"] = MixpanelLib.prototype.init;
23650 MixpanelLib.prototype["reset"] = MixpanelLib.prototype.reset;
23651 MixpanelLib.prototype["disable"] = MixpanelLib.prototype.disable;
23652 MixpanelLib.prototype["time_event"] = MixpanelLib.prototype.time_event;
23653 MixpanelLib.prototype["track"] = MixpanelLib.prototype.track;
23654 MixpanelLib.prototype["track_links"] = MixpanelLib.prototype.track_links;
23655 MixpanelLib.prototype["track_forms"] = MixpanelLib.prototype.track_forms;
23656 MixpanelLib.prototype["track_pageview"] = MixpanelLib.prototype.track_pageview;
23657 MixpanelLib.prototype["register"] = MixpanelLib.prototype.register;
23658 MixpanelLib.prototype["register_once"] = MixpanelLib.prototype.register_once;
23659 MixpanelLib.prototype["unregister"] = MixpanelLib.prototype.unregister;
23660 MixpanelLib.prototype["identify"] = MixpanelLib.prototype.identify;
23661 MixpanelLib.prototype["alias"] = MixpanelLib.prototype.alias;
23662 MixpanelLib.prototype["name_tag"] = MixpanelLib.prototype.name_tag;
23663 MixpanelLib.prototype["set_config"] = MixpanelLib.prototype.set_config;
23664 MixpanelLib.prototype["get_config"] = MixpanelLib.prototype.get_config;
23665 MixpanelLib.prototype["get_api_host"] = MixpanelLib.prototype.get_api_host;
23666 MixpanelLib.prototype["get_property"] = MixpanelLib.prototype.get_property;
23667 MixpanelLib.prototype["get_distinct_id"] = MixpanelLib.prototype.get_distinct_id;
23668 MixpanelLib.prototype["toString"] = MixpanelLib.prototype.toString;
23669 MixpanelLib.prototype["opt_out_tracking"] = MixpanelLib.prototype.opt_out_tracking;
23670 MixpanelLib.prototype["opt_in_tracking"] = MixpanelLib.prototype.opt_in_tracking;
23671 MixpanelLib.prototype["has_opted_out_tracking"] = MixpanelLib.prototype.has_opted_out_tracking;
23672 MixpanelLib.prototype["has_opted_in_tracking"] = MixpanelLib.prototype.has_opted_in_tracking;
23673 MixpanelLib.prototype["clear_opt_in_out_tracking"] = MixpanelLib.prototype.clear_opt_in_out_tracking;
23674 MixpanelLib.prototype["get_group"] = MixpanelLib.prototype.get_group;
23675 MixpanelLib.prototype["set_group"] = MixpanelLib.prototype.set_group;
23676 MixpanelLib.prototype["add_group"] = MixpanelLib.prototype.add_group;
23677 MixpanelLib.prototype["remove_group"] = MixpanelLib.prototype.remove_group;
23678 MixpanelLib.prototype["track_with_groups"] = MixpanelLib.prototype.track_with_groups;
23679 MixpanelLib.prototype["start_batch_senders"] = MixpanelLib.prototype.start_batch_senders;
23680 MixpanelLib.prototype["stop_batch_senders"] = MixpanelLib.prototype.stop_batch_senders;
23681 MixpanelLib.prototype["start_session_recording"] = MixpanelLib.prototype.start_session_recording;
23682 MixpanelLib.prototype["stop_session_recording"] = MixpanelLib.prototype.stop_session_recording;
23683 MixpanelLib.prototype["pause_session_recording"] = MixpanelLib.prototype.pause_session_recording;
23684 MixpanelLib.prototype["resume_session_recording"] = MixpanelLib.prototype.resume_session_recording;
23685 MixpanelLib.prototype["get_session_recording_properties"] = MixpanelLib.prototype.get_session_recording_properties;
23686 MixpanelLib.prototype["get_session_replay_url"] = MixpanelLib.prototype.get_session_replay_url;
23687 MixpanelLib.prototype["get_tab_id"] = MixpanelLib.prototype.get_tab_id;
23688 MixpanelLib.prototype["DEFAULT_API_ROUTES"] = DEFAULT_API_ROUTES;
23689 MixpanelLib.prototype["__get_recorder"] = MixpanelLib.prototype.__get_recorder;
23690 MixpanelPersistence.prototype["properties"] = MixpanelPersistence.prototype.properties;
23691 MixpanelPersistence.prototype["update_search_keyword"] = MixpanelPersistence.prototype.update_search_keyword;
23692 MixpanelPersistence.prototype["update_referrer_info"] = MixpanelPersistence.prototype.update_referrer_info;
23693 MixpanelPersistence.prototype["get_cross_subdomain"] = MixpanelPersistence.prototype.get_cross_subdomain;
23694 MixpanelPersistence.prototype["clear"] = MixpanelPersistence.prototype.clear;
23695 var instances = {};
23696 var extend_mp = function() {
23697 _$1.each(instances, function(instance, name) {
23698 if (name !== PRIMARY_INSTANCE_NAME) mixpanel_master[name] = instance;
23699 });
23700 mixpanel_master["_"] = _$1;
23701 };
23702 var override_mp_init_func = function() {
23703 mixpanel_master["init"] = function(token, config, name) {
23704 if (name) {
23705 if (!mixpanel_master[name]) {
23706 mixpanel_master[name] = instances[name] = create_mplib(token, config, name);
23707 mixpanel_master[name]._loaded();
23708 }
23709 return mixpanel_master[name];
23710 } else {
23711 var instance = mixpanel_master;
23712 if (instances[PRIMARY_INSTANCE_NAME]) instance = instances[PRIMARY_INSTANCE_NAME];
23713 else if (token) {
23714 instance = create_mplib(token, config, PRIMARY_INSTANCE_NAME);
23715 instance._loaded();
23716 instances[PRIMARY_INSTANCE_NAME] = instance;
23717 }
23718 mixpanel_master = instance;
23719 if (init_type === INIT_SNIPPET) win[PRIMARY_INSTANCE_NAME] = mixpanel_master;
23720 extend_mp();
23721 }
23722 };
23723 };
23724 var add_dom_loaded_handler = function() {
23725 function dom_loaded_handler() {
23726 if (dom_loaded_handler.done) return;
23727 dom_loaded_handler.done = true;
23728 DOM_LOADED = true;
23729 ENQUEUE_REQUESTS = false;
23730 _$1.each(instances, function(inst) {
23731 inst._dom_loaded();
23732 });
23733 }
23734 function do_scroll_check() {
23735 try {
23736 document$1.documentElement.doScroll("left");
23737 } catch (e) {
23738 setTimeout(do_scroll_check, 1);
23739 return;
23740 }
23741 dom_loaded_handler();
23742 }
23743 if (document$1.addEventListener) if (document$1.readyState === "complete") dom_loaded_handler();
23744 else document$1.addEventListener("DOMContentLoaded", dom_loaded_handler, false);
23745 else if (document$1.attachEvent) {
23746 document$1.attachEvent("onreadystatechange", dom_loaded_handler);
23747 var toplevel = false;
23748 try {
23749 toplevel = win.frameElement === null;
23750 } catch (e) {}
23751 if (document$1.documentElement.doScroll && toplevel) do_scroll_check();
23752 }
23753 _$1.register_event(win, "load", dom_loaded_handler, true);
23754 };
23755 function init_as_module(bundle_loader) {
23756 load_extra_bundle = bundle_loader;
23757 init_type = INIT_MODULE;
23758 mixpanel_master = new MixpanelLib();
23759 override_mp_init_func();
23760 mixpanel_master["init"]();
23761 add_dom_loaded_handler();
23762 return mixpanel_master;
23763 }
23764 function loadNoop(_src, onload) {
23765 onload();
23766 }
23767 var mixpanel = init_as_module(loadNoop);
23768
23769 //#endregion
23770 //#region assets/dev/js/utils/tiers.js
23771 var TIERS_PRIORITY = Object.freeze([
23772 "free",
23773 "essential",
23774 "essential-oct2023",
23775 "advanced",
23776 "expert",
23777 "agency"
23778 ]);
23779 /**
23780 * @type {Readonly<{
23781 * free: string;
23782 * essential: string;
23783 * 'essential-oct2023': string;
23784 * advanced: string;
23785 * expert: string;
23786 * agency: string;
23787 * }>}
23788 */
23789 var TIERS = Object.freeze(TIERS_PRIORITY.reduce(function(acc, tier) {
23790 acc[tier] = tier;
23791 return acc;
23792 }, {}));
23793
23794 //#endregion
23795 //#region core/common/modules/events-manager/assets/js/module.js
23796 init_defineProperty();
23797 function ownKeys(e, r) {
23798 var t = Object.keys(e);
23799 if (Object.getOwnPropertySymbols) {
23800 var o = Object.getOwnPropertySymbols(e);
23801 r && (o = o.filter(function(r) {
23802 return Object.getOwnPropertyDescriptor(e, r).enumerable;
23803 })), t.push.apply(t, o);
23804 }
23805 return t;
23806 }
23807 function _objectSpread(e) {
23808 for (var r = 1; r < arguments.length; r++) {
23809 var t = null != arguments[r] ? arguments[r] : {};
23810 r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
23811 _defineProperty(e, r, t[r]);
23812 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
23813 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
23814 });
23815 }
23816 return e;
23817 }
23818 function _callSuper$1(t, o, e) {
23819 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$1() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
23820 }
23821 __name(_callSuper$1, "_callSuper");
23822 function _isNativeReflectConstruct$1() {
23823 try {
23824 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
23825 } catch (t) {}
23826 return (_isNativeReflectConstruct$1 = function _isNativeReflectConstruct() {
23827 return !!t;
23828 })();
23829 }
23830 __name(_isNativeReflectConstruct$1, "_isNativeReflectConstruct");
23831 /** @type {typeof mixpanel | null} */
23832 var mixpanelInstance = null;
23833 var _default = /*#__PURE__*/ function(_elementorModules$Mod) {
23834 function _default() {
23835 var _this;
23836 _classCallCheck(this, _default);
23837 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
23838 _this = _callSuper$1(this, _default, [].concat(args));
23839 _defineProperty(_this, "trackingEnabled", false);
23840 _defineProperty(_this, "availableExperiments", []);
23841 return _this;
23842 }
23843 _inherits$1(_default, _elementorModules$Mod);
23844 return _createClass(_default, [
23845 {
23846 key: "onInit",
23847 value: function onInit() {
23848 var _this2 = this;
23849 this.config = eventsConfig;
23850 if (!this.canSendEvents()) return;
23851 this.initializeMixpanel(function() {
23852 return _this2.enableTracking();
23853 });
23854 }
23855 },
23856 {
23857 key: "initializeMixpanel",
23858 value: function initializeMixpanel(onLoaded) {
23859 var editorEventsConfig = elementorCommon.config.editor_events;
23860 installEventsProxyFetch(editorEventsConfig === null || editorEventsConfig === void 0 ? void 0 : editorEventsConfig.proxy_api_host, editorEventsConfig === null || editorEventsConfig === void 0 ? void 0 : editorEventsConfig.proxy_lib_base_path, editorEventsConfig === null || editorEventsConfig === void 0 ? void 0 : editorEventsConfig.token);
23861 if (mixpanelInstance && mixpanelInstance.isInitialized) onLoaded(mixpanelInstance);
23862 else {
23863 var _elementorCommon$conf;
23864 var _elementorCommon$conf2;
23865 var _elementorCommon$conf3;
23866 var _elementorCommon$conf4;
23867 var _elementorCommon$conf5;
23868 var _elementorCommon$conf6;
23869 var _elementorCommon$conf7;
23870 mixpanelInstance = mixpanel.init((_elementorCommon$conf = elementorCommon.config.editor_events) === null || _elementorCommon$conf === void 0 ? void 0 : _elementorCommon$conf.token, {
23871 persistence: "localStorage",
23872 persistence_name: "elementor-builder-editor",
23873 debug: (_elementorCommon$conf2 = (_elementorCommon$conf3 = elementorCommon.config.editor_events) === null || _elementorCommon$conf3 === void 0 ? void 0 : _elementorCommon$conf3.debug) !== null && _elementorCommon$conf2 !== void 0 ? _elementorCommon$conf2 : false,
23874 autocapture: false,
23875 flags: true,
23876 api_host: (_elementorCommon$conf4 = elementorCommon.config.editor_events) === null || _elementorCommon$conf4 === void 0 ? void 0 : _elementorCommon$conf4.proxy_api_host,
23877 lib_base_path: (_elementorCommon$conf5 = elementorCommon.config.editor_events) === null || _elementorCommon$conf5 === void 0 ? void 0 : _elementorCommon$conf5.proxy_lib_base_path,
23878 loaded: onLoaded,
23879 record_sessions_percent: (_elementorCommon$conf6 = (_elementorCommon$conf7 = elementorCommon.config.editor_events) === null || _elementorCommon$conf7 === void 0 ? void 0 : _elementorCommon$conf7.session_recording_percent) !== null && _elementorCommon$conf6 !== void 0 ? _elementorCommon$conf6 : 0,
23880 record_idle_timeout_ms: 60 * 1e3,
23881 record_min_ms: 5 * 1e3,
23882 record_mask_text_selector: "",
23883 remote_settings_mode: "strict"
23884 }, "elementor-builder-editor");
23885 }
23886 elementorCommon.config.editor_events.mixpanelInstance = mixpanelInstance;
23887 }
23888 },
23889 {
23890 key: "enableTracking",
23891 value: function enableTracking() {
23892 var _elementorCommon$conf8;
23893 if (!this.isMixpanelReady()) return;
23894 var userId = (_elementorCommon$conf8 = elementorCommon.config.editor_events) === null || _elementorCommon$conf8 === void 0 ? void 0 : _elementorCommon$conf8.user_id;
23895 mixpanelInstance.register({ appType: "Editor" });
23896 if (userId) {
23897 var _elementorCommon$conf9;
23898 mixpanelInstance.identify(userId);
23899 mixpanelInstance.people.set_once({
23900 $user_id: userId,
23901 $last_login: (/* @__PURE__ */ new Date()).toISOString(),
23902 $plan_type: ((_elementorCommon$conf9 = elementorCommon.config.library_connect) === null || _elementorCommon$conf9 === void 0 ? void 0 : _elementorCommon$conf9.plan_type) || TIERS.free
23903 });
23904 }
23905 this.trackingEnabled = true;
23906 this.availableExperiments = Object.keys(elementorCommon.config.experimentalFeatures || {});
23907 }
23908 },
23909 {
23910 key: "dispatchEvent",
23911 value: function dispatchEvent(name, data) {
23912 var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
23913 if (!this.canSendEvents()) return;
23914 try {
23915 var _elementorCommon$conf0;
23916 var _elementorCommon$conf1;
23917 var _elementorCommon$conf10;
23918 var _elementorCommon$conf11;
23919 var _elementorCommon$conf12;
23920 var _elementorCommon$conf13;
23921 var _elementorCommon$conf14;
23922 var _elementorCommon$conf15;
23923 var _elementorCommon$conf16;
23924 if (!this.trackingEnabled) this.enableTracking();
23925 var eventData = _objectSpread({
23926 user_id: ((_elementorCommon$conf0 = elementorCommon.config.editor_events) === null || _elementorCommon$conf0 === void 0 ? void 0 : _elementorCommon$conf0.user_id) || null,
23927 user_roles: ((_elementorCommon$conf1 = elementorCommon.config.library_connect) === null || _elementorCommon$conf1 === void 0 ? void 0 : _elementorCommon$conf1.user_roles) || [],
23928 subscription_id: ((_elementorCommon$conf10 = elementorCommon.config.editor_events) === null || _elementorCommon$conf10 === void 0 ? void 0 : _elementorCommon$conf10.subscription_id) || null,
23929 user_tier: ((_elementorCommon$conf11 = elementorCommon.config.library_connect) === null || _elementorCommon$conf11 === void 0 ? void 0 : _elementorCommon$conf11.current_access_tier) || null,
23930 url: (_elementorCommon$conf12 = elementorCommon.config.editor_events) === null || _elementorCommon$conf12 === void 0 ? void 0 : _elementorCommon$conf12.site_url,
23931 wp_version: (_elementorCommon$conf13 = elementorCommon.config.editor_events) === null || _elementorCommon$conf13 === void 0 ? void 0 : _elementorCommon$conf13.wp_version,
23932 client_id: (_elementorCommon$conf14 = elementorCommon.config.editor_events) === null || _elementorCommon$conf14 === void 0 ? void 0 : _elementorCommon$conf14.site_key,
23933 app_version: (_elementorCommon$conf15 = elementorCommon.config.editor_events) === null || _elementorCommon$conf15 === void 0 ? void 0 : _elementorCommon$conf15.elementor_version,
23934 site_language: (_elementorCommon$conf16 = elementorCommon.config.editor_events) === null || _elementorCommon$conf16 === void 0 ? void 0 : _elementorCommon$conf16.site_language,
23935 experiments: this.availableExperiments
23936 }, data);
23937 mixpanelInstance.track(name, eventData, options);
23938 } catch (error) {
23939 var _elementorCommon$conf17;
23940 if ((_elementorCommon$conf17 = elementorCommon.config.editor_events) !== null && _elementorCommon$conf17 !== void 0 && _elementorCommon$conf17.debug) console.error("Events Manager dispatch failed:", error);
23941 }
23942 }
23943 },
23944 {
23945 key: "featureFlagIsActive",
23946 value: function() {
23947 var _featureFlagIsActive = _asyncToGenerator(/*#__PURE__*/ import_regenerator.default.mark(function _callee(flagName) {
23948 var _mixpanelInstance;
23949 var isEnabled;
23950 return import_regenerator.default.wrap(function(_context) {
23951 while (1) switch (_context.prev = _context.next) {
23952 case 0:
23953 if (!("function" !== typeof ((_mixpanelInstance = mixpanelInstance) === null || _mixpanelInstance === void 0 || (_mixpanelInstance = _mixpanelInstance.flags) === null || _mixpanelInstance === void 0 ? void 0 : _mixpanelInstance.is_enabled))) {
23954 _context.next = 1;
23955 break;
23956 }
23957 return _context.abrupt("return", false);
23958 case 1:
23959 _context.next = 2;
23960 return mixpanelInstance.flags.is_enabled(flagName, false);
23961 case 2:
23962 isEnabled = _context.sent;
23963 return _context.abrupt("return", true === isEnabled);
23964 case 3:
23965 case "end": return _context.stop();
23966 }
23967 }, _callee);
23968 }));
23969 function featureFlagIsActive(_x) {
23970 return _featureFlagIsActive.apply(this, arguments);
23971 }
23972 return featureFlagIsActive;
23973 }()
23974 },
23975 {
23976 key: "getExperimentVariant",
23977 value: function() {
23978 var _getExperimentVariant = _asyncToGenerator(/*#__PURE__*/ import_regenerator.default.mark(function _callee2(experimentName) {
23979 var defaultValue;
23980 var _elementorCommon$conf18;
23981 var _elementorCommon$conf19;
23982 var isAbTestingEnabled;
23983 var variant;
23984 var _args2 = arguments;
23985 return import_regenerator.default.wrap(function(_context2) {
23986 while (1) switch (_context2.prev = _context2.next) {
23987 case 0:
23988 defaultValue = _args2.length > 1 && _args2[1] !== void 0 ? _args2[1] : "control";
23989 _context2.prev = 1;
23990 if (this.canSendEvents()) {
23991 _context2.next = 2;
23992 break;
23993 }
23994 return _context2.abrupt("return", defaultValue);
23995 case 2:
23996 isAbTestingEnabled = (_elementorCommon$conf18 = (_elementorCommon$conf19 = elementorCommon.config.editor_events) === null || _elementorCommon$conf19 === void 0 ? void 0 : _elementorCommon$conf19.flags_enabled) !== null && _elementorCommon$conf18 !== void 0 ? _elementorCommon$conf18 : false;
23997 if (isAbTestingEnabled) {
23998 _context2.next = 3;
23999 break;
24000 }
24001 return _context2.abrupt("return", defaultValue);
24002 case 3:
24003 if (mixpanelInstance) {
24004 _context2.next = 4;
24005 break;
24006 }
24007 return _context2.abrupt("return", defaultValue);
24008 case 4:
24009 if (!this.trackingEnabled) this.enableTracking();
24010 if (mixpanelInstance.flags) {
24011 _context2.next = 5;
24012 break;
24013 }
24014 return _context2.abrupt("return", defaultValue);
24015 case 5:
24016 if (!("function" !== typeof mixpanelInstance.flags.get_variant_value)) {
24017 _context2.next = 6;
24018 break;
24019 }
24020 return _context2.abrupt("return", defaultValue);
24021 case 6:
24022 _context2.next = 7;
24023 return mixpanelInstance.flags.get_variant_value(experimentName, defaultValue);
24024 case 7:
24025 variant = _context2.sent;
24026 if (!(void 0 === variant || null === variant)) {
24027 _context2.next = 8;
24028 break;
24029 }
24030 return _context2.abrupt("return", defaultValue);
24031 case 8: return _context2.abrupt("return", variant);
24032 case 9:
24033 _context2.prev = 9;
24034 _context2["catch"](1);
24035 return _context2.abrupt("return", defaultValue);
24036 case 10:
24037 case "end": return _context2.stop();
24038 }
24039 }, _callee2, this, [[1, 9]]);
24040 }));
24041 function getExperimentVariant(_x2) {
24042 return _getExperimentVariant.apply(this, arguments);
24043 }
24044 return getExperimentVariant;
24045 }()
24046 },
24047 {
24048 key: "startExperiment",
24049 value: function startExperiment(experimentName, experimentVariant) {
24050 if (!this.trackingEnabled) return;
24051 mixpanelInstance.track("$experiment_started", {
24052 "Experiment name": experimentName,
24053 "Variant name": experimentVariant
24054 });
24055 }
24056 },
24057 {
24058 key: "isMixpanelReady",
24059 value: function isMixpanelReady() {
24060 if ("undefined" === typeof mixpanelInstance || !mixpanelInstance) return false;
24061 try {
24062 var distinctId = mixpanelInstance.get_distinct_id();
24063 return distinctId !== void 0 && distinctId !== null;
24064 } catch (error) {
24065 return false;
24066 }
24067 }
24068 },
24069 {
24070 key: "canSendEvents",
24071 value: function canSendEvents() {
24072 var _elementorCommon;
24073 return !!((_elementorCommon = elementorCommon) !== null && _elementorCommon !== void 0 && (_elementorCommon = _elementorCommon.config) !== null && _elementorCommon !== void 0 && (_elementorCommon = _elementorCommon.editor_events) !== null && _elementorCommon !== void 0 && _elementorCommon.can_send_events);
24074 }
24075 },
24076 {
24077 key: "getMixpanelInstance",
24078 value: function getMixpanelInstance() {
24079 return this.isMixpanelReady() ? mixpanelInstance : void 0;
24080 }
24081 }
24082 ]);
24083 }(elementorModules.Module);
24084
24085 //#endregion
24086 //#region assets/dev/js/utils/notifications.js
24087 var require_notifications = /* @__PURE__ */ __commonJSMin(((exports, module) => {
24088 init_defineProperty();
24089 function ownKeys(e, r) {
24090 var t = Object.keys(e);
24091 if (Object.getOwnPropertySymbols) {
24092 var o = Object.getOwnPropertySymbols(e);
24093 r && (o = o.filter(function(r) {
24094 return Object.getOwnPropertyDescriptor(e, r).enumerable;
24095 })), t.push.apply(t, o);
24096 }
24097 return t;
24098 }
24099 function _objectSpread(e) {
24100 for (var r = 1; r < arguments.length; r++) {
24101 var t = null != arguments[r] ? arguments[r] : {};
24102 r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
24103 _defineProperty(e, r, t[r]);
24104 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
24105 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
24106 });
24107 }
24108 return e;
24109 }
24110 module.exports = elementorModules.Module.extend({
24111 initToast: function initToast() {
24112 var toast = elementorCommon.dialogsManager.createWidget("buttons", {
24113 id: "elementor-toast",
24114 position: {
24115 my: "center bottom",
24116 at: "center bottom-10",
24117 of: "#elementor-panel-inner",
24118 autoRefresh: true
24119 },
24120 hide: {
24121 onClick: true,
24122 auto: true,
24123 autoDelay: 1e4
24124 },
24125 effects: {
24126 show: function show() {
24127 var $widget = toast.getElements("widget");
24128 $widget.show();
24129 toast.refreshPosition();
24130 var top = parseInt($widget.css("top"), 10);
24131 $widget.hide().css("top", top + 100);
24132 $widget.animate({
24133 opacity: "show",
24134 height: "show",
24135 paddingBottom: "show",
24136 paddingTop: "show",
24137 top
24138 }, {
24139 easing: "linear",
24140 duration: 300
24141 });
24142 },
24143 hide: function hide() {
24144 var $widget = toast.getElements("widget");
24145 var top = parseInt($widget.css("top"), 10);
24146 $widget.animate({
24147 opacity: "hide",
24148 height: "hide",
24149 paddingBottom: "hide",
24150 paddingTop: "hide",
24151 top: top + 100
24152 }, {
24153 easing: "linear",
24154 duration: 300
24155 });
24156 }
24157 },
24158 button: { tag: "button" }
24159 });
24160 toast.getElements("widget").attr({
24161 role: "status",
24162 "aria-live": "polite",
24163 "aria-atomic": "true"
24164 });
24165 this.getToast = function() {
24166 return toast;
24167 };
24168 },
24169 showToast: function showToast(options) {
24170 var toast = this.getToast();
24171 toast.setMessage(options.message);
24172 toast.getElements("buttonsWrapper").empty();
24173 toast.focusedButton = null;
24174 toast.buttons = [];
24175 var isPositionValid = this.isPositionValid(options === null || options === void 0 ? void 0 : options.position);
24176 if (!isPositionValid) this.positionToWindow();
24177 if (options !== null && options !== void 0 && options.position && isPositionValid) toast.setSettings("position", options.position);
24178 if (options.buttons) options.buttons.forEach(function(button) {
24179 toast.addButton(button);
24180 });
24181 if (options.classes) toast.getElements("widget").addClass(options.classes);
24182 if (options.sticky) toast.setSettings({ hide: {
24183 auto: false,
24184 onClick: false
24185 } });
24186 return toast.show();
24187 },
24188 isPositionValid: function isPositionValid(position) {
24189 var _position$of;
24190 var positionToCheck = (_position$of = position === null || position === void 0 ? void 0 : position.of) !== null && _position$of !== void 0 ? _position$of : this.getToast().getSettings("position").of;
24191 if (!positionToCheck) return false;
24192 return !!document.querySelector(positionToCheck);
24193 },
24194 positionToWindow: function positionToWindow() {
24195 var toast = this.getToast();
24196 var position = _objectSpread(_objectSpread({}, toast.getSettings("position")), {}, {
24197 my: "right top",
24198 at: "right-10 top+42",
24199 of: ""
24200 });
24201 toast.setSettings("position", position);
24202 toast.getElements("widget").addClass("dialog-position-window");
24203 },
24204 onInit: function onInit() {
24205 this.initToast();
24206 }
24207 });
24208 }));
24209
24210 //#endregion
24211 //#region core/common/assets/js/common.js
24212 var import_notifications = /* @__PURE__ */ __toESM(require_notifications());
24213 function _callSuper(t, o, e) {
24214 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
24215 }
24216 function _isNativeReflectConstruct() {
24217 try {
24218 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
24219 } catch (t) {}
24220 return (_isNativeReflectConstruct = function _isNativeReflectConstruct() {
24221 return !!t;
24222 })();
24223 }
24224 function _superPropGet(t, o, e, r) {
24225 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
24226 return 2 & r && "function" == typeof p ? function(t) {
24227 return p.apply(e, t);
24228 } : p;
24229 }
24230 var ElementorCommonApp = /*#__PURE__*/ function(_elementorModules$Vie) {
24231 function ElementorCommonApp() {
24232 _classCallCheck(this, ElementorCommonApp);
24233 return _callSuper(this, ElementorCommonApp, arguments);
24234 }
24235 _inherits$1(ElementorCommonApp, _elementorModules$Vie);
24236 return _createClass(ElementorCommonApp, [
24237 {
24238 key: "setMarionetteTemplateCompiler",
24239 value: function setMarionetteTemplateCompiler() {
24240 Marionette.TemplateCache.prototype.loadTemplate = function(templateId) {
24241 var $template = "#" === templateId.charAt(0) ? Backbone.$("script" + templateId) : Backbone.$(templateId);
24242 if (!$template.length) throw new Marionette.Error({
24243 name: "NoTemplateError",
24244 message: "Could not find template: \"" + templateId + "\""
24245 });
24246 return $template.html();
24247 };
24248 Marionette.TemplateCache.prototype.compileTemplate = function(rawTemplate, options) {
24249 options = {
24250 evaluate: /<#([\s\S]+?)#>/g,
24251 interpolate: /{{{([\s\S]+?)}}}/g,
24252 escape: /{{([^}]+?)}}(?!})/g
24253 };
24254 return _.template(rawTemplate, options);
24255 };
24256 }
24257 },
24258 {
24259 key: "getDefaultElements",
24260 value: function getDefaultElements() {
24261 return {
24262 $window: jQuery(window),
24263 $document: jQuery(document),
24264 $body: jQuery(document.body)
24265 };
24266 }
24267 },
24268 {
24269 key: "initComponents",
24270 value: function initComponents() {
24271 this.events = new Events();
24272 this.eventsManager = new _default();
24273 this.debug = new import_debug.default();
24274 this.helpers = new Helpers();
24275 this.storage = new _default$11();
24276 this.dialogsManager = new DialogsManager.Instance();
24277 this.notifications = new import_notifications.default();
24278 this.api = window.$e;
24279 $e.components.register(new Component());
24280 elementorCommon.elements.$window.on("elementor:init-components", function() {
24281 $e.components.register(new Component$1());
24282 });
24283 this.initModules();
24284 }
24285 },
24286 {
24287 key: "initModules",
24288 value: function initModules() {
24289 var _this = this;
24290 var activeModules = this.config.activeModules;
24291 var modules = {
24292 ajax: _default$10,
24293 finder: _default$2,
24294 connect: _default$1
24295 };
24296 activeModules.forEach(function(name) {
24297 if (modules[name]) _this[name] = new modules[name](_this.config[name]);
24298 });
24299 }
24300 },
24301 {
24302 key: "compileArrayTemplateArgs",
24303 value: function compileArrayTemplateArgs(template, templateArgs) {
24304 return template.replace(/%(?:(\d+)\$)?s/g, function(match, number) {
24305 if (!number) number = 1;
24306 number--;
24307 return void 0 !== templateArgs[number] ? templateArgs[number] : match;
24308 });
24309 }
24310 },
24311 {
24312 key: "compileObjectTemplateArgs",
24313 value: function compileObjectTemplateArgs(template, templateArgs) {
24314 return template.replace(/{{(?:([ \w]+))}}/g, function(match, name) {
24315 return templateArgs[name] ? templateArgs[name] : match;
24316 });
24317 }
24318 },
24319 {
24320 key: "compileTemplate",
24321 value: function compileTemplate(template, templateArgs) {
24322 return jQuery.isPlainObject(templateArgs) ? this.compileObjectTemplateArgs(template, templateArgs) : this.compileArrayTemplateArgs(template, templateArgs);
24323 }
24324 },
24325 {
24326 key: "translate",
24327 value: function translate(stringKey, context, templateArgs, i18nStack) {
24328 if (context) i18nStack = this.config[context].i18n;
24329 if (!i18nStack) i18nStack = this.config.i18n;
24330 var string = i18nStack[stringKey];
24331 if (void 0 === string) string = stringKey;
24332 if (templateArgs) string = this.compileTemplate(string, templateArgs);
24333 return string;
24334 }
24335 },
24336 {
24337 key: "onInit",
24338 value: function onInit() {
24339 _superPropGet(ElementorCommonApp, "onInit", this, 3)([]);
24340 this.config = elementorCommonConfig;
24341 this.setMarionetteTemplateCompiler();
24342 }
24343 }
24344 ]);
24345 }(elementorModules.ViewModule);
24346 window.elementorCommon = new ElementorCommonApp();
24347 elementorCommon.initComponents();
24348
24349 //#endregion
24350 })(elementorVendors.reduxToolkit, wp.i18n);
24351 //# sourceMappingURL=common.js.map